Download presentation
Presentation is loading. Please wait.
1
CURRENT TOPICS IN PROGRAMMING LANGUAGES
LECTURE 1 GEORGE KOUTSOGIANNAKIS George Koutsogiannakis / Summer 2011
2
Course Objective Practice building reliable GUI (Graphical User Interface) using Java. Create Client Server architectures : Networking protocols. Design of Internet Client Server enterprises (applications). Java will be used to build Client/Server architectures. Other platforms follow similar approaches to Java.
3
Course Material THE PRESENTATIONS PROVIDE A LIST OF TOPICS DISCUSSED IN CLASS ON THE DAY OF THE LECTURE. A SORT DISCUSSION IS PRESENTED IN THE POWER POINT PRESENTATION. YOU MUST EITHER KEEP NOTES IN THE LIVE CLASS OR, IF YOU ARE A REMOTE STUDENT, WATCH THE TAPE FOR THE COMPLETE COVERAGE OF THE TOPICS. IN ADDITION YOU CAN DOWNLOAD THE POWER POINT PRESENTATIONS FROM THE COURSE’ S WEB SITE:
4
Course Material THIS SUMMARY DOES NOT NECESSARILLY LIMIT THE TOPICS DISCUSSED IN CLASS. TOPICS NOT LISTED HERE CAN BE DISCUSSED (FOR INSTANCE SAMPLE COD EWRITTEN ON THE WHITE BOARD). IT ONLY SERVES AS A GUIDELINE!. PROGRAMMING EXAMPLES ARE GIVEN FOR SOME TOPICS IN SUPPLEMENT YOUR UNDERSTANDING OF THE MATERIAL BY ALSO READING THE RECOMMENDED CHAPTERS FROM THE ASSIGNED TEXTS, NOTED ON THE SCHEDULE PAGE OF THE COURSE’S WEB SITE.
5
COURSE ADMINISTRATION
TOPICS DISCUSSED: COURSE WEB SITE: http// USAGE OF BLACKBOARD TOOLS NEEDED FOR THE COURSE: OFFICE HOURS ASSIGNMENTS / PROJECT. COURSE SYLLABUS THIS IS AN INTERMEDIATE TO ADVANCE LEVEL COURSE IN JAVA. BASIC KNOWLEDGE OF JAVA IS ASSUMED. MUST KNOW HOW TO COMPILE AND INTERPRET. MUST KNOW HOW TO USE NUMEROUS FILES TOGETHER.
6
COURSE ADMINISTRATION
REVIEW OF COURSE’ S WEB SITE: COURSE GRADING COURSE ASSIGNMENTS DOWNLOADING OF ASSIGNMENTS DEADLINES FOR ASSIGNMENT TOOLS REQUIRED OTHER METHOD OF ASSIGNMENTS SUBMISSION. BLACKBOARD’ S INDIVIDUAL ASSIGNMENT FOLDERS- DO NOT SUBMIT TO DIGITAL DROP BOX!!!! ETHICS
7
JAVA FRAMEWORKS AND ACCEPTABLE PLATFORMS
DISCUSSION OF VARIOUS JAVA FRAMEWORKS AVAILABLE AND THEIR FUNCTIONALITY: JDK1.6 STANDARD EDITION UPDATE 23 or latest update. RECOMMEND THAT YOU DOWNLOAD AND INSTALL ON YOUR COMPUTER. EARLIER VERSIONS ARE ACCEPTABLE. JAVA ENTERPRISE EDITION 6 (EE 6) . INCLUDES A JDK PLUS OTHER APIs. WINDOWS ENVIRONMENT IS THE PREFERRED ENVIRONMENT FOR ASSIGNMENTS AND PROJECTS. I WILL BE CHECKING YOUR WORK USING WINDOWS. If another environment is used you can demo your assignment to me on your laptop.
8
JAVA FRAMEWORKS AND ACCEPTABLE PLATFORMS
DURING THE FIRST PART OF THE COURSE EDIT PLUS IS THE PREFERRED IDE FOR WRITNG PROGRAMS. DO NOT USE NetBeans IN THE FIRST HAL F OF THE COURS EASSIGNMENTS UNLESS THE ASSIGNMENT SPECIFICALLY SAYS SO. YOU CAN USE OTHER JAVA FRIENDLY IDEs AS LONG AS THEY DON’T USE THEIR OWN JDK. YOU MUST INSTALL A VERSION OF THE JDK AND LINK YOUR IDE TO THAT INSTALLATION. DO NOT USE ECLIPSE AS IT USES ITS OWN JDK. IF YORU PROGRAM DOES NOT WORK BECAUSE YOU USED ECLIPSE TIME WILL BE WAISTED DEBUGGING IT (IT WILL BE RETURNE DTO YOU). PREFERRED DATABASES: MySQL / ACCESS/DERBY WEB SERVER: TOMCAT VERSION 6.0 AND UP NET BEANS 6.5 AND UP (LATEST VERSION IS 6.9) . NOTE THAT EACH VERSION HA SITS OWN ISSUES AND PROBLEMS.
9
JAVA PROGRAMS DIVISION OF JAVA PROGRAMS APPLICATIONS. APPLETS.
SERVER SIDE JAVA- SERVLETS, JAVA SERVER PAGES, JAVA SERVER FACES. ENTERPRISE JAVA BEANS WEB SERVICES DISTRIBUTED SERVICES USING RMI OR RMI OVER IIOP (OR JAVA IDL). SOME PROGRAMS REQUIRE SPECIAL TOOLS NOT AVAILABLE IN THE STANDARD EDITION JDK (AVAILABLE IN ENTERPRISE EDITION) SERVLETS AND JAVA SERVER PAGES
10
APPLETS AND BROWSERS BROWSERS AND WEB SERVERS (SERVER / CLIENT )
APPLETS AND THE BROWSER. APPLETS AND SECURITY. BROWSER ACTS AS A SANDBOX. WEB SERVER AND APPLETS. WEB SERVER AND SERVLETS. WEB SERVER AND JAVA SERVER PAGES.
11
Applets SERVER SIDE CLIENT SIDE Internet Web Server Browser #1
myApplet.html #1 #1 Web Server Browser myApplet.class #2 #2 #2 #1 Http request/response for html file//file is sent to Browser Browser interprets the html script # 2 Http request/response for file myApplet.class// file is sent to Browser Browser interprets java bytecodes File is destroyed when Browser is closed.
12
myJavaApplication.class
Servelts Java Client Application Servlet executes on the server side Internet #1 myServelt.class #1 #1 myJavaApplication.class Web Server #4 #3 #2 #3 #1 Http request sent to Web Server for servelt file execution #2 Servelet executes on the Server side and returns response to Web Server # 3 Http response formed by the Web Server based on the response from Servlet Http response is sent to Client Application # 4 Http response passes contents to input stream of the client application (myJavaApplication.class)
13
myJavaApplication.class
Java Server Pages Web Server Internet #1 myJSP.class #3 #2 myJavaApplication.class Java Client Application JSP contains java code and Other formats such as html , XML, special tags. #4 #1 Http request sent to Web Server for jsp file execution #2 java code of jsp executes on the Server side initially # 3 Http response formed by the Web Server based on the response from jsp. The java part of jsp is converted to a Servlet Http response is sent to Client Application # 4 Http response passes contents to input stream of the client application (myJavaApplication.class). The browser interprets the particular format sent (html, XML etc.).
14
Other communication forms
html -> applet -> servlet Client (Browser or some Java application program) interprets html which calls an applet from the server. Applet bytecodes are interpreted by the browser (or java application program). Applet calls back to the server for the execution of a servlet. Server executes the servlet. The response of the servlet is sent back to the browser 9or java application program) in some format (like html). Browser (or java application program) interprets response.
15
Other communication forms
html-> servlet-> applet In this example of different modules communicating with each other, first the html code interpreted by the client (Browser or a Java application program) calls for a servlet to be executed by the server. The server executes the servlet and sends the http response to the client. The client interprets the response and as a result a call to an applet is made (to the server). The server sends the applet to the client. The client interprets the applet code.
16
Other communication forms
In this course we will examine some of the previous communication architectures as well as more complicated architectures on the server side i.e. The servlet could be calling another server called a RMI server which in turn queries a data base. Or, the servlet calls a session Enterprise Java Bean which in turn calls an Entity bean which in turn queries a database.
17
INHERITANCE REVIEW JAVA DOES NOT SUPPORT MULTIPLE INHERITANCE
SINGLE INHERITANCE IS APPLIED IN JAVA VIA KEYWORD extends MULTIPLE INHERITANCE CAN BE SIMULATED BY USING INTERFACES
18
A Sample Vehicle Hierarchy
This hierarchy is depicted using a Unified Modeling Language (UML) diagram. In UML diagrams, arrows point from the subclass to the superclass.
19
Superclasses and Subclasses
A big advantage of inheritance is that we can write code that is common to multiple classes once and reuse it in subclasses A subclass can define new methods and instance variables, some of which may override (hide) those of a superclass
20
Inheritance Rules Superclass Members Inherited by subclass?
Directly Accessible by Subclass? Directly Accessible by Client of Subclass? public fields yes yes, by using field name public methods yes, by calling method from subclass methods protected fields no, must call accessors and mutators protected methods no private fields private methods
21
Inheritance Rules for Constructors
Superclass Members Inherited by subclass? Directly Accessible by Subclass? Directly Accessible by Client of Subclass Using a Subclass Reference? constructors no yes, using super( arg list ) in a subclass constructor
22
Subclass Constructors
Constructors are not inherited. However, the subclass can call the constructors of the super class to initialize inherited fields. Implicit invocation The default constructor of the subclass automatically calls the default constructor of the superclass. For explicit invocation, use this syntax: super( argument list ); If used, this statement must be the first statement in the subclass constructor.
23
Multiple Inheritance The concept of multiple inheritance is shown below (even though Java does not allow it). Class A Class B Class C Class D
24
abstract Classes and Methods
An abstract class is a class that is not completely implemented. Usually, the abstract class contains at least one abstract method. An abstract method specifies an API but does not provide an implementation. The abstract method is used as a pattern for a method the subclasses should implement.
25
More on abstract Classes
An object reference to an abstract class can be declared. We use this capability in polymorphism, which will be discussed later. An abstract class cannot be used to instantiate objects (because the class is not complete). An abstract class can be extended. subclasses can complete the implementation and objects of those subclasses can be instantiated
26
Defining an abstract class
To declare a class as abstract, include the abstract keyword in the class header: accessModifier abstract class ClassName { // class body }
27
Example Hierarchy We can define a Figure hierarchy.
The superclass is Figure, which is abstract. (In the UML diagram, Figure is set in italics to indicate that it is abstract.) We will derive two subclasses: Circle and Square.
28
Subclasses of abstract Classes
A subclass of an abstract class can implement all, some, or none of the abstract methods. If the subclass does not implement all of the abstract methods, it must also be declared as abstract. Our Circle subclass adds a radius instance variable and implements the draw method. Our Square subclass adds a length instance variable and implements the draw method.
29
Restrictions for Defining abstract Classes
Classes must be declared abstract if the class contains any abstract methods abstract classes can be extended An object reference to an abstract class can be declared abstract classes cannot be used to instantiate objects
30
Restrictions for Defining abstract Methods
abstract methods can be declared only within an abstract class An abstract method must consist of a method header followed by a semicolon abstract methods cannot be called abstract methods cannot be declared as private or static A constructor cannot be declared abstract
31
The Figure Class public abstract class Figure { private int x; private int y; private Color color; // usual constructors, accessors, // and mutators // abstract draw method public abstract void draw( Graphics g ); } All classes in the hierarchy will have an (x, y) coordinate and color. Subclasses will implement the draw method.
32
Polymorphism An important concept in inheritance is that an object of a subclass is also an object of any of its super classes. That concept is the basis for an important OOP feature, called polymorphism. Polymorphism simplifies the processing of various objects in the same class hierarchy because we can use the same method call for any object in the hierarchy using a super class object reference.
33
Polymorphism Conditions
conditions for polymorphism: The Figure, Circle, and Square classes are in the same hierarchy. The non-abstract Circle and Square classes implement the draw method. We assigned the Circle and Square objects to Figure references. We called the draw method using Figure references.
34
Example Suppose we have a class FigureClient.
This class uses the previous classes to actually draw figures. i.e. (assuming that all classes are in the same folder) public class FigureClient { public static void main ( String [] rags) Circle circle=new Circle(); Square square=new Square(); Figure figure; //just declaration, no instantiation is allowed figure=circle; figure.draw(); // a circle will be drawn figure=square; figure.draw(); // a square will be drawn now. …………………………………………………………………………………
35
Superclasses and Subclasses
A big advantage of inheritance is that we can write code that is common to multiple classes once and reuse it in subclasses A subclass can define new methods and instance variables, some of which may override (hide) those of a superclass
36
Interfaces A class can inherit directly from only one class, that is, a class can extend only one class. To allow a class to inherit behavior from multiple sources, Java provides the interface. An interface typically specifies behavior that a class will implement. Interface members can be any of the following: · classes · constants · abstract methods · other interfaces
37
Interface Syntax To define an interface, use the following syntax:
accessModifier interface InterfaceName { // body of interface } All interfaces are abstract; thus, they cannot be instantiated. The abstract keyword, however, can be omitted in the interface definition.
38
Finer Points of Interfaces
An interface's fields are public, static, and final. These keywords can be specified or omitted. When you define a field in an interface, you must assign a value to the field. All methods within an interface must be abstract, so the method definition must consist of only a method header and a semicolon. The abstract keyword also can be omitted from the method definition.
39
Inheriting from an Interface
To inherit from an interface, a class declares that it implements the interface in the class definition, using the following syntax: accessModifier class ClassName extends SuperclassName implements Interface1, Interface2, … The extends clause is optional. A class can implement 0, 1, or more interfaces. When a class implements an interface, the class must provide an implementation for each method in the interface.
40
Example We define an abstract class Animal with one abstract method :
public abstract void draw( Graphics g ); We define a Moveable interface with one abstract method: public interface Moveable { int FAST = 5; // static constant int SLOW = 1; // static constant void move( ); // abstract method }
41
Derived Classes TortoiseRacer class TortoiseNonRacer class
extends Animal class implements Moveable interface implements draw and move methods TortoiseNonRacer class (does not implement Moveable interface) implements draw method only
42
Multiple Inheritance Suppose we have abstract class Student (template class). This class has abstract method getGPA which returns the gpa. Suppose we also have abstract class Employee (template class) This class has abstract method getSalary which returns the salary. Class StudentEmployee wants to inherit both classes and implement both the gpa and the salary. It can not do that because multiple inheritance is not allowed public class StudentEmployee extends Student extends Employee ABOVE IS NOT LEGAL!!!!!!!
43
Multiple Inheritance Let us leave Employee intact and instead remove the abstract method getGPA from the Student class. Thus there is no need for Student to be abstract any more. Let us create an interface : public interface StudentInterface defines the method getGPA Let us create a class StudentImpl which inherits Student and implements interface StudentInterface. It implements the method getGPA which calculates the gpa.
44
Multiple Inheritance Now class StudentEmployee extends Employee and it also implements the interface StudentInterface. Therefore it implements the method getGPA but kind of indirectly (via the implementation of the method in the StudentImpl class): StudentImpl st=new StudentImpl(); public float getGPA() { return st.getGPA(); } StudentEmployee object can invoke other methods of class Student since StudentImpl also inherits student. It also can use the class Employee since it inherited that class directly.
45
Multiple Inheritance Abstract Employee class
Student class Interface StudentInterface Class StudentEmployee Uses StudentImpl StudentImpl
46
Example of Multiple Inheritance
Example of a Multiple Inheritance Implementation is posted on the Web Site Examples page. In the example our goal it create a class called Expenses that inherits from both classes Employee and OperatingExpenses. Class CorporationTest tests the multiple inheritance.
47
Example of Multiple Inheritance
Class Employee is abstract because method compensation is abstract. Classes Engineer, Management, AdministartivePersonel inherit Employee and implement compensation according to their requirements. Interface ExpenseInterface defines method getOperatingExpenses Class Expense extends Employee and implements interface ExpenseInterface Class OperatingExpenses has methods that calculates different operating expenses for the corporation. Class ExpenseImpl extends OperatingExpenses and implements the interface ExpenseInterface
48
Abstract class Employee OperatingExpenses
Administrative Personel Engineer Management ExpensesInterface Abstract class Employee OperatingExpenses OperatingExpensesImpl Expenses Uses OperatingExpensesImpl
49
Example of Multiple Inheritance
Study program “Multiple Inheritance Example” available in the Examples (page) of the course’ s web site.
50
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES
LECTURE 2 George Koutsogiannakis / Summer 2011
51
Overview of Java EE Past EE
discreet APIs allowed building of complex enterprise solutions. EE combines most of the above and new APIs into one enterprise bundle of tools and APIs.
52
Distributed Multi-tiered Applications
Enterprise applications can be distributed in various servers located in different locations. They are comprised of various tiers i.e.: Client Tier (Presentation Tier): Consists of components that run on the client machine. Can be applets working in a Browser or application programs. These components can communicate with a Web Server using HTTP protocol to send requests and receive responses. Or They can communicate via another protocol with the Business Tier applications.
53
Distributed Multi-tiered Applications
Web Tier: Consists of the Web Server and applications that run in the web server using special containers that the web server must have, i.e. Servlet container. The Web Server can be Jakarta Tomcat or any other Web Server that has the proper containers. The term container refers to special executable programs (sometimes called engines) that a server can have . These containers are capable of recognizing the particular type of java program that the server is interfacing with.
54
Distributed Multi-tiered Applications
Business Tier: Components that run on distributed servers. Those servers can be RMI (Remote Method Invocation) servers or Application Servers with Enterprise Java Beans. Notice that either the web server applications act as client to the remote servers (to RMI or Application Servers) Or, that the Client Tier can directly contacts these distributed services via some protocol (without going through the web server). The application servers are available through various vendors including Sun Microsystems (on April 20, 2009 Oracle announced that it is acquiring Sun MS- the deal is still pending closure).
55
Distributed Multi-tiered Applications
Enterprise Information System Tier (Data Tier): Data bases that run on legacy machines and have various data that the customer at the Client Tier needs. The Enterprise hires developers (and other software engineers) and obtains tools to establish the tiers. A number of developers are working on the various tiers. Developers have specialized experiences based on the tier they are working with. Their experience also is tool depended. Some are familiar with NetBeans, others with Websphere , others with .NET tools (Microsoft) and so on.
56
Distributed Multi-tiered Applications
Other software engineers are responsible for the Temporary deployment in the servers and the testing of the various parts of the enterprise application. The final deployment in the servers.
57
Example of Past Implementations
Web Server: Jakarta Tomcat JDK SE: SWING AND AWT Graphical Components JDBC (Java Data Base Connectivity) RMI (Remote Method Invocation) RMI over IIOP (RMI over Internet Inter-Operability Protocol) Servlet and Java Server Pages API could be added to SE Java API couled be added to SE Java Messaging Services API could be added to SE Java Beans API
58
3-TIER ARCHITECTURE- Example from CS441 Project 2 Spring 08
THE BASIC BANK SERVICES ARCHITECTURE IS: INTERNET CLIENT GUI BROWSER WEB SERVER Customer Accounts Servlet, Users Servlet, Updated Selections Servlet e.t.c, Applet, html files, images RMI SERVER /JDBC / JDBC DATA BASE PRESENTATION TIER WEB TIER AND BUSINESS RULES TIER DATA TIER
59
3 Tier Example discrete API usage
The Web Server was Jakarta Tomcat The Client GUI was an Applet The business rules were applied via servlets, jsp The RMI server demonstrated distributed applications (not necessarily collocated with the web server). The distributed services used JDBC to connect to respective databases Client Request -> Web Server-> proper servlet (servlet was a client to a RMI server) -> RMI server JDBC query->Database Database query result (data)-> RMI server-> corresponding servlet (its client)-> response to web server servlet container-> HTTP response packets to client Applet
60
Revised 3 tier architecture using Enterprise Java Beans and Application Servers
INTERNET CLIENT GUI BROWSER WEB SERVER Servlets/ Java Server Pages Application Server EJBs DATA BASE PRESENTATION TIER BUSINESS RULES TIER DATA TIER Distributed Applications WEB TIER
61
Revised 3 tier architecture using Enterprise Java Beans and Application Servers
Notice that the Communication between the client and the service needed can also be direct by passing the web tier and going through a private network: APPLICATION SERVER CLIENT NETWORK
62
Revised 3 tier architecture using Enterprise Java Beans and Application Servers
Quite often the Application Server (such as GlassFish) contain the web server and the database. Note that GlassFish used to be called Sun Application Server
63
Multi Tier Multi Tier architectures can be built where additional servers become part of the architecture such as: Firewall server: handles all incoming traffic from the Internet, helps protect the rest of the system from attacks. Local Balancer: Distributes transactions to various servers.
64
Multi Tier Transaction Processing Monitor: Handles incoming requests and forwards the request to the proper application server. The above 3 types of servers define what is called PortalServices.
65
Java EE Integrates all API s and tools needed for establishing multi-tiered applications. Combines Web Server and Application Server into Java EE Server. GUI components for the client tier are created using Java Server Faces technology Graphical Components are created on the server side and rendered as an object in a mark up language (HTML, XML etc.)
66
Java EE Tiers Web Tier (Web Server) Java EE Server
CLIENT TIER- Java Application/Dynamic HTML pages/Java Script / Java Bean components Web Tier (Web Server) Java EE Server Enterprise Java Beans (Application Server) Databases
67
Naming Services Distributed Services Need to be discovered.
For Example: RMI provides a simple server called rmiregistry where remote servers can register their remote objects. A client first contacts the registry to get a reference to the remote object (i.e. the name of the server, the port number that the server listens, the remote object id).
68
Naming Services Java EE includes the Java Naming and Directory Interface API ( JNDI). This API allows clients to discover remote objects (provided those remote objects have registered with the JNDI)
69
Java EE Security Java EE allows security to be defined at the time of deployment of the application. In discrete APIs security needs to be defined with special policy files and certificates. In addition separate programs are needed by using the various Security APIs. Cumbersome and application specific. Java EE utilizes the various Security APIs in an integrated approach to provide security settings at the time of deployment. Uses the Java Authentication and Authorization Service.
70
JEE APIs Other APIs included in JEE:
JDBC (Java Data Base Connectivity) Java Servlets and Java Server Pages (JSP) Java Server Faces Java Enterprise Beans Java Message Service Java Transactions Java JavaBeans Activation Framework Various APIs for Web Services implementation
71
Types of Tasks in an Enterprise
Purchasing of software from Java EE vendors who have implemented the Java EE server. Tool providers for development tools and also packaging tools (i.e. NetBeans Development tool). Development of Java Enterprise Beans, web components (applets,servlet, jsp other programs, java applications for client and other programs) Assembly of the application into an EAR file. Temporary Deployment of the application by an administrator into the server(s). Testing Final Deployment into the server(s).
72
JAVA GRAPHICS Let us revert to some basic Java Graphics before we return to the topics of server side Java. Graphics should be understood before the concept of Java Server Faces as a substitute for graphical components is discussed or Before the usage of NetBeans to create graphical components is discussed.
73
JAVA GRAPHICS BASICS JAVA CONCEPTS INVOLVED AWT & SWING APIs PROVIDE
TOP CONTAINERS OBJECTS COMPONENTS OBJECTS SUB CONTAINERS OBJECTS LAYOUT MANAGERS OBJECTS PAINT / UPDATE/ REPAINT METHODS FOR EACH CONTAINER
74
Java Graphics Involves knowledge of various containers
i.e. Top Containers: JFrame, JApplet, JDialog Other containers can be dropped into top containers: JPanel JInternal Frame Other components can be dropped in a Container i.e. JTextArea JTextField JButton JEditorPane ( a component that allows html files to be displayed plus other text formats).
75
Java Graphics Involves knowledge of Layout Managers:
FlowLayout manager (default) BorderLayout Manager GridLayout Manager GridBagLayout Manager GridBagLayout is the one Layout manager used for professional presentations.
76
BorderLayout Manager Divides Screen up to 5 Areas: NORTH WEST CENTER
EAST SOUTH
77
BorderLayout Manager Set up the top Container first by extending your class to inherit the container: public class MyClass extends JFrame { //call super class’ constructor to pass a name for the Frame public MyClass() super(“My Frame Name”);
78
BorderLayout Manager Usage: Container c= getContentPane();
c.setLayout(new BorderLayout(5,5)); JButton b1=new Jbutton(“First Action”); c.add(b1, BorderLayout.NORTH); ……………………………………………………
79
EVENT HANDLING EVENT LISTENER INTERFACES. EVENT OBJECTS.
EVENT ADAPTER CLASSES TECHNIQUES FOR GENERATING EVENTS.
80
EVENT HANDLING EVENT SOURCE EVENT OBJECT EVENT LISTENER
81
Event Handling Create component object
Register component object with the event handler object. Create an event handler class that implements the Event Listener interface that goes with the particular component Implement the proper method of the Even Listener Interface.
82
MORTGAGE CALCULATOR –APPLICATION VERSION
JFRAME AND BORDER LAYOUT MANAGER USAGE OF JPANEL AND BOX MANAGER. JTABLE COMPONENT. MODEL/ VIEW / CONTROLLER DESIGN PATTERN DEMONSTRATION OF EVENT HANDLING USING ANONYMOUS INNER CLASS USING AN INNER CLASS USING A SEPARATE FILE ANOTHER VERSION USES GRID BAG LAYOUT MANAGER
83
STUDY GUIDE Read Web Based Applications Development: chapters 2 and 3
Read Java EE Tutorial: Part II Chapter 3. Study Mortgage Calculator examples for Graphics.
84
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES
LECTURE 3 GEORGE KOUTSOGIANNAKIS George Koutsogiannakis / Summer 2011
85
Summary of topics Web Applications Platforms. More on Java Graphics
BorderLayout Manager GridBagLayout Manager Using the paint method to update GUI Some Graphical Components Model View Controller Architecture.
86
Web Application Platforms
Enterprises can be built using: Individual APIs and script languages, i.e. in Java: For server side you can use: Servlets, javascript (server side), java server pages etc. For client presentation: You can create a GUI for the client using applets, or a Java application, or mixture of HTML and client side javascript etc. For the Data Tier You can use RMI servers and various databases JDBC compatible.
87
Web Application Platforms
You have to create the security required (like user Authentication and Authorization, certificates to validate the server and the web site etc) manually yourself. Notice that all programming and system testing is done by you the developer manually by bringing together all these different APIs.. Deployment is up to you also. You have to choose a web server, an application server, a database. All of these probably OS specific (for the machine where the system is going to reside). You have to deploy the programs you wrote in each type of server(s) and you have to integrate all the parts of the system working on different servers.
88
Web Application Platforms
A Better approach these days is to use various platforms that allow you to bring all the tools you need together under one environment. These IDEs go also under the name WAP (Web Application Platforms). There are many different platforms available utilizing different programming languages i.e.
89
Web Application Platforms
Web Application Platforms include some or all of the items below: An Operating System for platforms that are not OS neutral). A web server (for the web tier part) An Application server (for the business logic part). Programming Languages and compilers/interpreters. Run time support systems Databases management and drivers for various databases. A Web Development Environment (WDE) that:
90
Web Application Platforms
WDE (continued from previous slide) Provides reusable components-drag and drop operations without writing any code, the development environment creates the source code files for you. Template to create a client GUI. User Authentication and authorization mechanisms and other security settings. Transaction processing. Other services.
91
Web Application Platforms
A Content Management System (CMS) that includes: Access to html , images, video for user (client) GUIs. Version control. Other .
92
Web Application Platforms
Architecture of a WEB APPLICATION (Enterprise Application) APPLICATION DEVELOPMENT FRAMEWORK CMS WEB AND APPLICATION SERVERS VARIOUS LANGUAGES RUNTIME DATA BASE MANAGEMENT OPERATING SYSTEM HARDWARE
93
Some WEDs LAMP : Primarily use din Europe. Consists of Linux, Apache (web server), MySQL, PHP (or PERL or PYTHON). Mostly open source availability. Microsoft .NET: Windows, IIS (web server), SQL, other tools such as Active Server Pages etc. Sun’ s JAVA EE: Operating System independent, GlassFish (web server and application server), MySQL, Derby other databases, Tools for developing web application such a servlets, jsp, html, other.
94
Graphics In Java to create a GUI you need:
To decide on the type of containers that you are going to use. The components that you will place on the container(s) The way that you are going to place the components on the container, using one of the Layout Manager objects. The events that you are going to attach to each component.
95
Graphics- Some Layout Managers
BorderLayout Manager Does not behave very well when screen is resized! Need to use GridBagLayout in order to accommodate screen resizing. See Mortgage Calculator example using BorderLayout (from course’s web site- examples link).
96
GRAPHICS GRID BAG LAYOUT MANAGER Need 3 objects:
Container c; // to get hold of the content Pane GridBagConstraints constraints; //to establish settings for various attributes GriDBagLayout gbl; //layout manager object Need a separate helper method that sets the constraints for a component. This method will accept as arguments whatever number of constraints we decide to use and the component object whose constraints are being set . The method sets the particular constraints to the specified values and adds the component to the pane (container).
97
GridBagLayout Manager
Container is divided into rows and columns Column numbers 1 2 3 n …………………………………………………………………………………………… 1 Component A r ows 2 . m
98
GridBagLayout Manager
Example of Typical Constraints: gridx : column # gridy: row # gridx, gridy identify the coordinate where the upper left corner of the component will be placed. Notice that column and row numbers start with 0. i.e gridx=2, gridy =1 for component A in previous slide. gridwidth: number of columns to be occupied by the component. gridheight: number of rows to be occupied by the component. anchor: used when the component’ s area is smaller than the allocated area. Values of anchor are: CENTER, NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, and NORTHWEST Default is CENTER
99
GridBagLayout Manager
fill: used when the component’ s size is larger than the allocated area. Determines if component should be resized. Values : NONE: Do not resize the component. HORIZONTAL: Make the component wide enough to fill its display area horizontally, but do not change its height. VERTICAL: Make the component tall enough to fill its display area vertically, but do not change its width. BOTH: Make the component fill its display area entirely. The default value is NONE.
100
GridBagLayout Manager
weightx and weighty: Take non negative values like 10, 50, 100 . Difficult to predict the value. Default is zero. These constraints specify how to distribute extra horizontal and vertical space respectively. If component does not show up or if it is distorted adjust the values. Start with zero values. Use small values if components are partially shown. Increment as needed Look up more constraints in the API
101
GridBagLayout Manager
Container is divided into rows and columns and the size of the container is defined as 800 pixels horizontally by 400 pixels vertically. Supose n=15 and m=5 Column numbers 1 2 3 n …………………………………………………………………………………………… 1 Component A r ows 2 3 m
102
GridBagLayout Manager
The values of n and m depend on the sum of all the widthx and heighty used in the various components i.e. component A : gridx=0, gridy=0, gridwidth=5, gridheight=2 Component B: gridx=5, gridy=0, gridwidth=10, gridheight=4 Component C: gridx=0, gridy=2, gridwidth=5, gridheight=3 Component D: gridx=5, gridy=4, gridwidth=10, gridheight=1 Therefore the total number of columns is: 5+10 =15 And the total number of rows is: 2+3=5 If the size of the container was: width 150 pixels and height= 100 pixels then each column is 10 pixels wide and each row is 20 pixels in height.
103
GridBagLayout Manager
Another example: If n=20 then each column is 40 pixels wide (800/20) If m=8 then each row is 50 pixels wide (400/8) A component’ s size can be set before its constraints are used on the component. Suppose component A is a button (slide #8). i.e. JButton b=new JButton(“A”); b.setPreferredSize(new Dimension(120, 100)); sets the size of b to 120 pixels wide by 100 pixels in height or gridwidth=3 gridheight=2 in terms of columns and rows for the example in slide #8 .
104
GridBagLayout Manager
The position of the component is specified by gridx= 2; gridy=1; Let us assume that the GridBagConstraints objects is : constraint and that the GriBagLayout object is: gridbag A call to the helper method would be made as follows: addComponent( b, 1, 2, 3,2, 50, 100);
105
Helper Method for GridBagConstraints
private void addComponent(Component component, int row, int column, int width, int height , int wx, int wy) { constraints.gridx=column; constraints.gridy=row; constraints.gridwidth=width; constraints.gridheight=height; constraints.weightx=wx; Constraints.weighty=wy constraints.fill=GridBagConstraints.BOTH; constraints.anchor=GridBagConstraints.CENTER; gridbag.setConstraints(component, constraints); c.add(component); }
106
Graphical User Interface with Menu Bar
We could add a menu bar to a container like JFrame. The menu bar takes some space that is not included in the GridBagLayout for the remaining space on the frame. First we create a menu bar object MenuBar mb=new MenuBar(); Then we create Menu objects JMenu m1=new JMenu(“File”); JMenu m2=new JMenu(“Edit”); JMenu m3=new JMenu(“View”); Each Menu has Menu Items. JMenuItem mi11=new JMenuItem(“New File”); JMenuItem mi12=new JMenuItem(“Save As”); m1.add(m11); m1.add(m12); JMenuItem mi21=new JMenuItem(“Copy”); JMenuItem mi22=new JMenuItem(“Paste”); m2.add(mi21); m2.add(mi22); etc..
107
Graphical User Interface with Menu Bar
JMenuItem m31=new JMenuItem(“List”); JMenuItem m32= new JMenuItem(“Details”); m3.add(m31); m3.add(m32); Now we add them Menu objects to the MenuBar object mb.add(m1); mb.add(m2); mb.add(m3); The MenuBar will be add by default at the top of the JFrame but it could also be directed to be placed on the bottom or the sides. setJMenuBar(mb);
108
Graphical User Interface
4 JPanels dropped in a JFrame using GridBagLayout manager JPanel 1 JPanel 2 JPanel 3 JPanel 4
109
Graphical User Interface
JPanel1: gridx=0, grid y=0 gridwidth=10, gridheight=7 JPanel2: gridx=10, gridy=0 gridwidth=20, gridheight=7 JPanel3: gridx=0, gridy=7 gridwidth=20, gridheight=8 JPanel4: gridx=20, gridy=7 gridwidth=10, gridheight=8
110
Graphical User Interface
Each JPanel has components dropped in it. A layout of your choice can be used with each JPanel to place the components. A Box can be used to tightly box components together either vertically or horizontally. The box (or multiple boxes) can then be dropped in each Panel.
111
Graphical User Interface
JTextField 1 Vertical Box Box boxv=Box.createVerticalBox(); boxv.add(jtf1); boxv.add(jtf2); boxv.add(jb); JPanel panel1=new JPanel(); panel1.add(boxv); JTextField 2 JButton
112
Paint Methods Every container has a paint method associated with it.
The method for JFrame is: public void paint(Graphics g) The method for JPanel is called: public void paintComponent ( Graphics g) Default paint methods are called first to paint the components. The paint methods can be overridden so that we can paint other information. A paint method is called via a call to repaint(); repaint calls update method which calls paint.
113
Special Components JFileChooser is a component that allows us to browse the directory and either find a file to open or save a file (including the creation of a new folder) JColorChooser is a component that allows the user to choose a color. JTable is a component that allows the creation of a matrix of rows and columns and the placement of data in the cells created. JEditorPane is a component that allows ,for instance ,the interpretation of html code , as in a Browser, plus other formats. JInternalFrame is used for the creation of a Desktop like GUI. Each JInternalFrame can be dropped in a Desktop container object and it can be maximized, minimized, iconified.
114
Calling Of Overridden paint Method
Example of Mortgage Calculator with JTable: JFrame’ s default paint method is called to paint the static GUI on the screen Program waits for user inputs. The user enters values in TextFields and presses enter. The event handler method is called which in turn calls the method calculate(). The method calculate() calculates the pertinent financial quantities and calls repaint() Method repaint() calls the overridden version of paint method (s). The overridden version of paint method updates the JTable with the rows and columns and places the proper values in the various cells of the JTable. Notice that multiple paint methods will be called with the call repaint() i.e. each JPanel will call its paintComponent method also. Mouse events will also call the paint methods (need to be masked).
115
JTable JTable is a complex component that creates a matrix of rows and columns and allows data to be entered and edited in the cells. Follows the Model View Controller (MVC) Design Pattern. It can be created using a default table model or a table model created by the developer. Model refers to what methods are available for the data manipulation. View is the visible part to the user, the rows and columns, Control is whatever event handling is available to for instance change the data in the cells etc. Event Handlers (Controller part) can allow updating of the data as well as selection of rows and column by the user.
116
JTable Discussion on examples of JTable Using default table model
Using a user defined model. Selecting cells for editing Event Listener for JTable.
117
MODEL VIEW CONTROLLER ARCHITECTURE
The JTable component is an example of a software architecture called: Model View Component (MVC) MVC consists of: Model: Part of the application responsible for handling data and the state of the application (session management, database ). View: Part of the application that is responsible for the GUI , passes actions to the controller , obtains data from MVC to present to user. Controller: Part of the application that coordinates all parts of the application. It handles user action by activating the proper model components to present to the user. Selects the appropriate view for the user.
118
MODEL VIEW CONTROLLER ARCHITECTURE
MVC pattern for a Web Application: VIEW User Event Data Set View CONTROLLER Transaction/Command Data Query Data MODEL
119
Study Guide Read Chapters 9, 13, 14 of “Web Based Application Development ” text. Graphics and JTable is not covered by the texts. Use examples from class (see following examples posted on course’ s web) . Mortgage Calculation – Border Layout version Mortgage Calculation - Grid Bag Layout version. EditableTable
120
George Koutsogiannakis/Summer 2011
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 4 George Koutsogiannakis/Summer 2011
121
Examples of Programs Source code is available on the course’s web site under examples: Mortgage Calculator- Border Layout Mortgage Calculator – GridBagLayout JTable – Editable Table JTable – Selecting Rows/Columns Mortgage Calculator Applet version – Using Appletviewer with Policy File.
122
Applets Java programs that are intended to be stored on the web server side but executed on the client side by a browser. Applets do not need a main method. Applet is actually a top graphical container. To create an Applet class we inherit the library class JApplet.
123
Applets Browser with access to JRE Web Server
Asks for html file and interprets it. Asks for applet .class file Calls JRE to interpret it Web Server Html file that calls the applet Applet bytecodes file
124
Applets Example of creating an Applet class import java.swing.JApplet;
class MyApplet extends JApplet { }
125
Applets Inside our class we can override one or more of the methods in the JApplet class that define an Applet’s lifecycle: public MyApplet() Default constructor called by the Browser after the applet is loaded. public void init() Used for initialization code i.e assigning initial values to variables. It is called by the Browser every time the page is visited including the first time it is loaded.
126
Applets public void start() public void stop() public void Destroy()
Called by the Browser right after int() or every time the web page is visited public void stop() Called by the Browser when the page becomes inactive. public void Destroy() Called by the Browser to exit the applet. public void paint(Graphics g) Called by the Browser the first time that the Applet is drawn. Called by the Applet every time repaint is called. Called by the Applet if there is some action o n the screen like the clicking of mouse.
127
Calling an Applet from html
To call an Applet program use an html file with the html tag: <applet code=“MyApplet.class” width=350 height=200> </applet>
128
Applet Security Browser acts as a sandbox for an applet:
It does not allow an applet to make system calls. As a result it can’t for example: Open a File for reading or writing. Call exit to exit the applet program. Any other system call. The above restrictions can be removed if the applet is declared to be “trusted code”. We will learn how to do that by using policy files and certificates.
129
Applets and Policy Files
Appletviewer allows non-production testing of an applet. Behaves like a Browser. We can provide security overrides via a policy file. Policy file scan be created using the Policy Tool that comes with the jdk. C:>policytool The above simple command activates the policy file tool
130
Java Security-Policy File
Simple policy file to be used with appletviewer: grant { permission java.security.AllPermission; }; The policy file is saved as: policy_file_name.policy In the same directory as the applet class file.
131
Java Security- Policy File
The policy file can be also written manually scripting using a text editor, no compilation is needed. Here is another example of a more elaborate policy file: grant signedBy “George” , codebase “file:C:\\myjavaprograms\cs441\.*” { permission java.security.SecurityPermission “Security.insertProvider.*”; permission java.security.SecurityPermission “Security.removeProvider.*”; Permission java.security.SecurityPermission “Security.setProperty.*”; } This policy file: indicates that code was packaged in a signed JAR file and placed in the directory (folder) cs441. The term signs implies that the JAR file was signed with a digital signature (will be explained later in more detail). The signature can be verified by using the “public key” (term to be explained later) referenced by the alias “George”
132
Java Security- Policy File
The code can then access the security system of Java and change provider. Provider= The class that implements security The code is allowed to change security properties.
133
Java Security Architecture
Java security provided by the JVM and the language: Applies to application programs. Applets that are transferred over the web. Network security. Server side security.
134
Java Security Architecture
Java Security Model characteristics: Enforced via policy files. JVM resources can be controlled via the policy file. It is a domain based security model. Allows cryptographic digital signatures to be generated and attached to a JAR file. Resources downloaded over the web (applets) have restricted access to local resources (sandbox). Those are un trusted resources. i.e applets are not allowed system calls on local system i.e applets are not allowed to connect back to the server they came from.
135
Java Security Architecture
Resources downloaded over the web can become trusted resources. Via digital signatures. Via certificates. Via policy files. Trusted resources override the sandbox restrictions. All applications have full control of local system resources unless they are restricted access via a ProtectionDomain. ProtectionDomain are either ‘System Domains” or “Application Domains” They group classes into a group and associate them with permissions on specific resources. A Java application program can have both system and application specific domains (i.e. allow certain system calls but only on specific resources for this application).
136
Java Security Architecture
SecurityManager class (java.lang.Security) enforces the security policy of an application. An application ‘s security manager can be activated to use a specific policy file for an application by using the command: C:> java –Djava.security.manager –Djava.security.policy=mypolicy.policy MyJavaApplication Every application gets a default security manager object. You can create your own SecurityManager class and be a provider of security. Java Web Start Security allows java applications to be deployed, launched, and updated from a web server.
137
Java Security Tools Tools are part of the jdk and facilitate the enforcement of security. policytool: generates policy files. keystore: a database where keys (encrypted passwords) can be stored along with certificates. keytool: allows users to administer their own public/private keys and certificates. jarsigner: digitally signs Java Archive Files (JAR files).
138
JAVA SECURITYARCHITECTURE
User Classes Bytecodes Verifier Class Loader Non Trusted Code Trusted Code Policy File Public Domain Sandbox Security Manager Keystore System Resources
139
Java System Security Master Files
JSE SecurityFiles are located at: /Program Files/Java/jdk1.6.0_11/jre/lib/security/ Files are: cacerts: The default keystore that comes with the java system. Used to store keys and certificates. java.policy: The default master policy file for the SecurityManager java.security: The master property file that contains security related properties. File is read every time a program is executed. It identifies providers of security javaaws.policy: The master policy file for Web Services. local-policy.jar and Usexport-policy.jar: Used when an application needs to be used in another country. Some countries have restrictions on cryptography.
140
Java System Security- Security Properties File
Properties file security.properties sets the properties to be used by the java.security library classes. The term “provider” refers to the user’ s cryptographic packages to be used by the java.security library classes. Example of properties: #List of providers is given by property lines: security.provider.1=sun.security.provider.Sun Security.provider.2=com.sun.rsajca.Provider # where Sun and Provider are library classes that control the security and the cryptographic algorithms used. # Sun class identifies the signature algorithms available (i.e. DSA, DSS, SHA/DSA, MD5 etc.).
141
Java System Security- Security Properties File
# Provider class represents the provider of security in terms of implementing the cryptographic algorithms and the key generation. # Provider class can be used by new security providers to register themselves in the properties file. # A new Provider can implement new security services and add them to the security mechanism of Java. # The specification “Java Cryptography Architecture API Specification and Reference” describes how a new provider with new services are added to the security mechanism.
142
Java System Security- Security Properties File
#Identification of the library class that will be used to instantiate the system policy Object: policy.provider.=sun.security.provider.PolicyFile #The system policy file is identified by: policy.url.1=file:$(java.home)/lib/security/java.policy policy.url.2=file:$(user.home)/.java.policy # We can add our own security policy file right underneath the previous policy files policy.url.3=file:/C:/MyJavaPrograms/cs441/mypolicy.policy Warning: Any changes to the properties file will apply to any java program executed on the local system.
143
Java System Security- Master Policy File
Lists default permissions: permission java.util.PropertyPermission "java.version", "read"; permission java.util.PropertyPermission "java.vendor", "read"; permission java.util.PropertyPermission "java.vendor.url", "read"; permission java.util.PropertyPermission "java.class.version", "read"; permission java.util.PropertyPermission "os.name", "read"; permission java.util.PropertyPermission "os.version", "read"; The master policy file can be amended (not recommended!!). The master policy file applies to all java programs executed by the local system.
144
Java System Security- Master Policy File
The Java Runtime System creates a global Policy Object which is used to encapsulate the permissions granted in the master policy file. We can set a different master policy file or add additional policy permissions to the default permissions for a one time execution when we start the interpreter with the command: >java –Djava.security.policy=“mypolicy.policy” MyJavaProgram Or >java –Djava.security.policy==“mypolicy.policy” MyJavaProgram Where single “=“ means add to existing permissions in master file and Double “ ==“ means use instead of master file permissions. This command adds the policy file that is in the current directory otherwise the url path to the file needs to be entered before the name of the policy file.
145
Policy File Syntax Besides permissions a Java Policy File can have some other entries: Keystore entry: Identifies the keystore (database) where keys (passwords) and certificates are stored. It is used if the signer entry shows an alias name. The public key of the signer will be looked up in the keystore. i.e. keystore url with_respect_to_policy_file After grant we can specify the signer : i.e. grand signedBy “signer_name” , codebase “URL” Where “signer_name” is the alias that was used when the certificate for the keystore was created and the “URL”is the path to where the code is located. No codebase URL entry means that permissions are granted to any code anywhere as opposed to the code stored at URL.
146
Importance of Security
Questions that need to be answered: Which applications are we protecting? Who are we protecting the applications from? Where should we protect these applications/? Why are we protecting these applications? Compliance with Federal and State laws Sarbanes_Oxley Act of companies must secure data Gramm-Leach-Bliley act of financial institutions must adapt strict privacy measures relating to customer data.
147
Requirements of Network Security
Privacy: did a third unauthorized party captured information transmitted between two parties? Integrity: has the information transmitted from party A to party B altered on the way? Authentication: how do the sender and the receiver of information prove their identity to each other? Authorization: allow the user to access the information while preventing others from accessing. Non-repudiation: how do we legally prove that a message was sent and received (i.e. a contract) ? Prevent Breach of Availability: unauthorized distribution of data Prevent Unauthorized usage of system resources. Prevent Denial of Service: prevention of legitimate usage of message transferring
148
Java Implementation of Security Goals
Security Tools: Tools that create keystores, policy files, digital signatures (encrypted passwords), issuance of certificates. Special APIs (library classes) that extend the Security Architecture of Java: JCE: Java Cryptography Extension provides java applications that allow: Secret key encryption ( using 3DES algorithm). Public key algorithms (Diffie-Hellman or RSA). Adding new algorithms. JAAS: Java Authentication and Authorization Service addresses problems associated with authentication and controlling access to the information via the Pluggable Authentication Module (PAM). PAM supports kerberos, smart cards and other.
149
Java Implementation of Security Goals
Security Manager API allows the generation of user defined permissions via a user defined SecurityManager class. SSL: Secure Socket Layer implements a public key using RSA algorithm and digital certificates to authenticate the server in a transaction and to protect private information. It also encrypts the TCP/IP packets sent over the network. It is part of java.net.ssl library package.
150
Study Guide Read the online Java Tutorial on Security
“Web Based Application Development” text Chapter 3 Chapter 10 As an example look at the Applet version of the Mortgage Calculator example. Download it from the course’s web site.
151
Appendix on JAR Allows compression of files.
Allows execution of a java program in the jar file by clicking on the jar icon. Allows signing of the jar file for secured transmission.
152
Appendix -JAR C:\current_directory>jar cf name_of_jar.jar .*class
Command to create a jar file: C:\current_directory>jar cf name_of_jar.jar .*class Compresses all files with extension .class in the current directory. Decompressing jar files: C:\current_directory>jar xvf name_of_jar.jar Viewing the files in a jar file: C:\current_directory>jar tvf name_of_jar.jar
153
Appendix -JAR To create a jar executable file (where the java program in the jar file is executed by clicking on the jar file icon): Create a manifest file using Notepad i.e. Manifest-Version 2.0 Main-Class: MyProgram Use command C:\current_directory> jar cfmv MyManifestFile.mf NameofJar.jar .*class
154
George Koutsogiannakis/ Summer 2011
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 5 George Koutsogiannakis/ Summer 2011
155
Applet Security Browsers act as sandboxes to Applets thus preventing the execution of system calls. We can defeat the security restrictions by making the applet ‘trusted code” via the usage of a certificate.
156
APPLET SECURITY Using Certificates
Certificates are issued by a Certificate Authority (CA) i.e VeriSign provides digital certificates besides other services. A certificate is normally issued to: Authenticate a server to a client Makes code passed to a receiver “trusted code”. It provides information about the sender of the code.
157
Using Digital Signatures- Possible Scenario
Certification Authority Developer Code Private Key Certificate Includes information About the developer and a public key that the user can use to verify the code. Signature Algorithm Verified Code User Signed Code
158
Encryption Encryption is the process of taking data (called cleartext) and a sort String (called the key), and producing data (called ciphertext) that is meaningless to someone who does not know the key. Decryption is the inverse process of getting back the so called cleartext
159
Encryption Two forms: Symmetric Encryption: The same key is used for encryption and decryption Asymmetric Encryption: Two different keys used, one for encryption and the other for decryption.
160
Message Digest Message Digest is the application of a hashing function on a message to produce a file called the message digest file. Goal: ensures data integrity Hashing algorithms used: SHA-1 (Secure Hashing Algorithm- 160 bits) MD5 (uses 128 bit) Note: Newer algorithms SHA-256 and SHA-512 provide 256 and 512 bits encryption
161
Security Scenarios-Using a Message Digest
Bob wants to send a message to Mary Bob hashes the message and sends the original message and the message digest to Mary. Mary applies the same hashing function to the original message and creates her own message digest for the original message. Mary compares the message digest received from Bob and the one she generated. If the two message digests match then the message was received unaltered (ensures integrity). PROBLEM: A third party captures the original message and the digest sent by Bob. Third party sends its own version of the message with the corresponding digest for it (provided it knows the hashing algorithm agreed between Bob and Mary)
162
Security Scenarios-Using a Message Digest
Notice that there is not an unhashing process. In other words reversing the hashing process to get the original message back is not possible.
163
Security Scenarios-Using Secret Key (symmetric encryption)
Bob wants to send a message to Mary. Both Bob and Mary share a secret key. Bob encrypts the message with the secret key. Mary decrypts the message with the same secret key. This is symmetric encryption and ensures that a third party can not read or alter the message. The key must be sent to the parties over some secure channel. PROBLEM: There is no guarantee that the encrypted message came from Bob. Other parties can get hold of the secret key.
164
Security Scenarios-Using Secret Keys (asymmetric encryption).
Suppose that Mary wants to verify that the message came from Bob Bob uses a private key to sign the data and create a digital signature. Mary uses a public key which she uses to verify Bob ‘s digital signature.
165
Security Scenarios-Using Message Digest and Asymmetric Encryption
Combine scenario #1 (message digest) with scenario #3. It ensures privacy, integrity and authentication.
166
Security Scenarios-add SSL
Use scenario #4 plus Apply SSL (Secure Socket Extension) Client uses server’s certificate stored in a trust store (keystore) to verify the server. Server uses keystore that has the server’ s private and public keys. Client create san instance of SSLSocketFactory and SSLSocket and specifies the server’ s name and port.
167
Security Scenarios-Another Assymmetric Approach
# 6 scenario (asymmetric) Bob encrypts message with Mary’ s public key. Sends message to Mary. Mary decrypts the message with her private key. Mary sends a response message to Bob by encrypting the message with Bob’s public key . Bob decrypts the message with his private key. Public keys can be sent to anybody. RSA is the most popular asymmetric cipher.
168
Secure Web Transaction Using Certificates-(Scenario # 4- slide 12)
Client Server CA sends certificate and policy file to client -Certificate is stored in client’s keystore (i.e. cacerts) -Client requests connection to a server /receives html file/ html file calls for applet. Server sends applet to client (signed jar file) Applet can execute system calls on the client’s host and communicate with the server (based on the fact that the jar file that has the applet is signed with the keys listed in the certificate) .
169
Digital Signatures The idea is the reverse process of using public/private keys (asymmetric - i.e. Opposite of scenario #6). Mary uses her private key to encrypt her message (or code). Anybody who has Mary’ s public key can decrypt Mary’s message. This approach does not secure the integrity of the message. It just ensures that the message came from Mary (otherwise her public key will not be able to decrypt it). Problem: How do we know that the public key actually came from Mary? Maybe a third party pretends to be Mary and sends out a public key. Then, the third party sends a message encrypted with the third party’s private key pretending that the message is coming from Mary.
170
Digital Certificate Someone has to verify that the public key actually comes from Mary. 3 1 CA 2 4 Bob Mary 5 Mary sends CA her public key. CA verifies public key and creates certificate. Sends certificate to Mary. 3. CA sends to Bob a public key that allows the reading of the certificate..
171
Digital Certificate Mary sends message and certificate to Bob. Bob verifies CA’s signature using CA’s public key . Bob can now read Mary ‘s public key from the certificate and trust that the public key is actually Mary’s public key. Bob can now encrypt his message (i.e. his credit card number) using Mary ‘s public key and send it to Mary. Suppose that a third party has interrupted step 4 (getting hold of the certificate) and intersected in the certificate their own public key and send it to Bob. Bob’s verification of the certificate will fail based on CA’s public key.
172
Digital Signatures- Sender
Original Document Hash Function Private key encryption Digital Signature
173
Digital Signatures- Receiver
Message Digest Apply Hash Function Message Compare The 2 digests Digital Signature Message Digest Public Key
174
Steps to Create Certificate
Follow the following steps to create a certificate Use the command below (from DOS) to genearate keys. Use a name as alias and make sure that you record it. If you forget it you will have to generate the certificate again C:\Myprograms >keytool –genkey –keyalg RSA –alias youralias Keytool asks for : Keystore password: Personal Information Alias Password: Make note of the passwords and alias you entered. Now export the certificate information into a file named by you with the extension .cer >keytool –export –alias youralias –file MyCertificateName.cer Enter the keystore password from above when asked. The certificate file MyCertificate.cer will be created.
175
Steps to Create Certificate
Go to Program Files/Java/jdk1.6.0_23/jre/lib/security. Place the certificate file MycertificateName.cer in that directory. Execute the following command in a DOS window in the security directory: >keytool –import –alias MyTrustedCertificate –keystore cacerts –file MyCertificateName.cer This command will import the information from the certificate to the default keystore cacerts Note that the alias in this command is not youralias generated at the beginning of this process but rather the default alias required by the default keystore. When prompted enter keystore password: changeit (Note that changeit is the password for default keystore cacerts located in the security directory of the jdk). NOTICE THAT CERTIFICATES ARE ONLY GOOD FOR 6 MONTHS!!!
176
Steps to Create Certificate
Jar the applet class (or multiple files) >jar cf MyApplet.jar *.class (you have to be in the same directory as the applet class) Create the signed jar now >jarsigner –signedjar sMyApplet.jar MyApplet.jar youralias A new jar file will be created under the name sMyAppletclass.jar The system will ask you for the first password entered (keyword password) when you created the certificate and then for the second password entered when you created the certificate (step 1 from this procedure). Changes to the applet code do not require re-issuance of the certificate but the jar file and the signed jar file have to be regenerated The jar file will have to be placed in the proper directory in the web server.
177
Steps to Create Certificate
The html file that the client is going to use to call the applet will have to have the archive attribute in the applet tag: <APPLET CODE = "MyApplet.class" ARCHIVE="MyJarFile.jar" WIDTH = "600" HEIGHT = "600"> </APPLET> OR YOU COULD ADD A CODEBASE LIKE: <APPLET CODE = "MyApplet.class" CODEBASE=“ ARCHIVE="MyJarFile.jar" WIDTH = "600" HEIGHT = "600"> </APPLET> Note: MyApplat.jar represents the signed version of the jar file that has the applet code.
178
Example Programs Message Digest Encrypt Decrypt
Login Client and Login Server Create Keys
179
USING JAKARTA TOMCAT INSTALL TOMCAT HOW TO CREATE A CONTEXT ROOT
STRUCTURE OF WEBAPPS CONTEXT ROOT FOLDER DEPLOYING A NEW CONTEXT ROOT APPLICATION. USING THE WEB SERVER LOCALHOST. DEMONSTRATION OF USING AN APPLET IN A CONTEXT ROOT.
180
DEPLOYING A CONTEXT ROOT
FIRST MAKE SURE THAT YOUR JDK DOES NOT HAVE ANY SERVLET JAR FILES IN THE DIRECTORY /Program Files/Java/jdk1.5/jre/lib/ext THERE IS A CONFLICT WITH TOMCAT’S SERVLET ENGINE IF YOU LEAVE THE SERVLET JAR FILE IN THAT DIRECTORY. TEMPORARILY REMOVE THAT JAR FILE WHILE YOU NEED TOMCAT. REINSERT THE JAR FILE IN THE EXT FOLDER WHEN YOU ARE WRITING SERVLET PROGRAMS AND YOU NEED TO COMPILE THEM NOTE: PROBABLY YOU DON’T HAVE THE SERVLET FILE IN YOUR EXT DIRECTORY IF YOU NEVER USED SERVLETS BEFORE.
181
DEPLOYING A CONTEXT ROOT FOR AN APPLET
CREATE A NEW FOLDER UNDER TOMCAT’S WEB APPS DIRECTORY. GIVE THE FOLDER THE NAME OF THE WEB APPLICATION THAT YOU WANT TO CREATE. THAT IS CALLED THE “CONTEXT ROOT”. CREATE A FOLDER CALLED WEB-INF INSIDE YOUR CONTEXT ROOT FOLDER. INSERT A SIMPLE WEB.XML FILE IN THE WEB-INF FOLDER. CREATE A FOLDER NAMED CLASSES IN THE WEB-INF FOLDER. LEAVE IT EMPTY FOR NOW. PLACE ALL HTML AND APPLET CLASSESS DIRECTLY UNDER THE CONTEXT ROOT FOLDER.
182
DEPLOYING A CONTEXT ROOT
FROM YOUR BROWSER CALL: = / name_of_context_root IF EVERYTHING IS OK THE RESPONSE SHOULD BE: OK DEPLOYED APPLICATION AT PATH /context_root_name FROM BROWSER CALL TO VERIFY THE STATUS OF ALL APPLICATIONS ON TOMCAT YOUR CONTEXT ROOT NAME YOU PROVIDED SHOULD SHOW UP AS RUNNING. YOU CAN STOP IT, UNDEPLOY IT AND REDEPLOY IT FROM THE STATUS SCREEN. SEE DOCUMENT TomcatDeployment.txt IN THE EXAMPLES PAGE OF THE COURSE’ S WEB SITE FOR MORE DETAILS.
183
DEPLOYING A CONTEXT ROOT
Note: A more dependable way for deploying a web application is to use a war file. This is described in a document posted on the course’ s web site that describes how to deploy on Tomacat.
184
Study Guide Study security examples posted on the web site.
Search Internet for information on Digital Certificates. Download Tomcat and its documentation. Read documentation package for installation and usage. Tomcat comes with help files also.
185
George Koutsogiannakis /Summer 2011
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 6 George Koutsogiannakis /Summer 2011
186
Topics Starting a child process. More on Special Graphical Components.
JEditorPane / JTable Editable and Selectable cells. I/O Streams Client Server / Using sockets. Client / Server steps for Connection Oriented Multithreaded server Connectionless Client / Server Multicasting
187
Start Child Process C exe } C java public class StartChildProcess {
public static void main(String[] args) { Runtime rt=Runtime.getRuntime(); Process proc; String cmd[]=new String[3]; cmd[0]="V1T4.exe"; cmd[1]="newtst22.txt"; cmd[2]="6"; try { proc=rt.exec(cmd); DataInputStream in=new DataInputStream(proc.getInputStream()); byte[] buf=new byte[256]; int cbRead=0; while(cbRead>=0) cbRead=in.read(buf); in.close(); String str=new String(buf); //write the data into a file FileOutputStream file=new FileOutputStream("testout.txt"); OutputStreamWriter out=new OutputStreamWriter(new BufferedOutputStream(file)); out.write(str); out.flush(); file.close();} catch(IOException e) {System.out.println(e);}} } C java C exe Data stream
188
Start Child Process The child process is a C program that has a main that takes as arguments two parameters. main(argc, argv) Where argc is an integer that represents the number of arguments And argv is an array of Strings that represents the arguments to be passed to this process. The first entry into the array is always the name of the child process’ executable. For more details see example posted on the course ‘ s web site: start a child process with a Java program.
189
JEditorPane Component
Special component that can display different formats of files. It supports: HTML. RTF (Rich Text Format). Special purpose applications via a ‘Editor Kits”. Display could be editable by the user and saved.
190
JEditorPane Component
Usage: Within try/catch block that captures IOException: Create an object of the class: JEditorPane editorpane= new JEditorPane (url ); Where url is a String that points to either a web resource (i.e. Or to a file in the local system (i.e. file://C:/MyPrograms/index.html ) editorpane.set(false); prevents editing on the text area.
191
JEditorPane Component
Register the component with a listener so that when user clicks on a url the file gets retrieved and displayed: html.addHyperlinkListener(this); Add the editor pane component to a container like a JPanel (possibly add it to a JScrollPane before adding it to a JPanel). Override the hyperlinkUpdate method of the HyperlinkListener Interface.
192
JEditorPane Component
public void hyperlinkUpdate ( HyperlinkEvent e) { if (e.getEventType() = = HyperlinkEvent.EventType.ACTIVATED) try editorpane.setPage(e.getURL()); ………………………………………………………… ………………………………………………………………………. It is assumed that a text field has been created with the proper listener for the text field where the user can type the url that leads to the file to be displayed. For more details see example poste don the course ‘s web site:browser.java
193
JTable When we create a JTable we can have the user: Edit the cells.
Select rows and columns whose data the user wants to save maybe in a file or in a data structure.
194
Editing JTable Example of EditableTable.java program on course ‘s web site. Program lets user create a model object: Override various methods of TableModel. Calling the method fireTableCellUpdated(row, column) in turn calls the listener (event handler) of the Controller part. Overriding method isCellEditable can identify the specific cells that the user can edit when the Table and its data is displayed. Create the View: Wrap the model object with a JTable object and then with a JScrollPane object. Set the viewing size using the JTable object: Mytable.setPreferredScrollableViewportSize(new Dimension( 500, 300);
195
Editing JTable Create the Controller by implementing the Listener interface TableCellEditor and overriding its methods: public Component getTableCellEditorComponent (JTable table, Object value, boolean isSelected, int row, int column) and public Object getCellEditorValue() Notice that editing can be done directly ion the displayed cell or on a special JTextArea or JTextField component that can be presented to the user.
196
JTable –Selecting Rows and Columns.
See example SimpleTableSelectionDemo.java on the course’ s web site. Create the model and view as in previous example of Editable Table. Use the JTable object to set the mode of selection by the user” Allow single row selection only or Allow multiple rows to be selected or Allow intervals of multiple rows to be selected. i.e table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); Create a reference of ListSelectionModel and register it with an event handler. The event handler overrides method valueChanged of ListSelectionListener interface. In this method w e can sense the beginning index of the row selected and the ending index. Once we know the rows we can capture the row data and do whatever we want to do with it.
197
I/O Streams Java uses many different types. Which stream you use depends on the type of communication i.e. Are we opening a particular type of file for reading or writing? What data types are involved? Are we setting up a communication path between a client and a server? Are we transmitting entire objects?
198
File Types Java basically supports two types of files:
text files: data is stored as characters binary files: data is stored as raw bytes The type of a file is determined by the classes used to write to the file. Types of Files can be: Files written using Bytes Streams (1s and 0s). Files written using Character Streams (char types). Files written in terms of Strings (text). Files written using primitive data types (int, double etc) Files written using entire object streams (recording all information about an object in a coded format).
199
File Types To read an existing file, you must know the file's type in order to select and import the appropriate library classes for reading the file.
200
Writing to Text Files Several situations can exist:
the file does not exist the file exists and we want to replace the current contents the file exists and we want to append to the current contents We specify whether we want to replace the contents or append to the current contents.
201
Streams Therefore: To read a file input stream is needed. To write to a file output stream is needed. The java.io package provides the classes for establishing input and output streams.
202
Selected Input Classes in the java.io Package
Description InputStream Abstract superclass representing a stream of raw bytes FileInputStream Input stream to read raw bytes of data from files ObjectInputStream Class to read/recover objects from a file written using ObjectOutputStream
203
Hierarchy for Input Classes
204
Selected java.io Output Classes
Description Writer Abstract superclass for output classes OutputStreamWriter Class to write output data streams OutputStream Abstract superclass representing an output stream of raw bytes FileWriter Class for writing to character files BufferedWriter More efficient writing to character files PrintWriter Prints basic data types, Strings, and objects PrintStream Supports printing various data types conveniently FileOutputStream Output stream for writing raw bytes of data to files ObjectOutputStream Class to write objects to a file
205
Hierarchy for Output Classes
206
Reading Text Files with Scanner
In CS115 we used the File object and the Scanner object to read a text file i.e. import java.io.File; import java.io.IOException; import java.util.Scanner; Public class ReadFile { Public static void main(String[] args) { try { File myfile=new File(“mytextfiel.txt”); Scanner scan=new Scanner(myfile); while(scan.hasMoreTokens()) String str=scan.next(); System.out.println(str); } catch)(IOException ioe) { System.out.println(ioe.toString()); }
207
Opening and Closing an Input Stream
When we construct an input stream or output stream object, the JVM associates the file name, standard input stream, or standard output stream with our object. This is opening the file. When we are finished with a file, we optionally call the close method to release the resources associated with the file. Return value Method name and argument list void close( ) releases resources associated with an open input stream. Throws an IOException.
208
Closing an output stream
When closing a Buffered output stream in addition to the close() method for the stream the methdod flush() should also be invoked: datastreamobject.flush(); Flushing the output stream forces any buffered output bytes to be written out.
209
Opening and Closing Standard Streams
Some streams are standard and the are available to any java program. The standard input stream (System.in), the standard output stream (System.out), and the standard error stream (System.err) are open when the program begins. They are intended to stay open and should not be closed.
210
Exceptions While Reading from a File
We can catch this exception: FileNotFoundException thrown by the Scanner constructor if the filename is not found when opening the file We do not expect these exceptions to occur, so we will catch them as subclasses of IOException, and print the stack trace. InputMismatchException if the input does not match the expected data type. (The next method does not throw this exception, so we don’t need to catch this exception). NoSuchElementException if we attempt to read beyond the end of the file. IllegalStateException if we attempt to read after calling the close method.
211
Buffering Writing data to the disk is much slower than writing data into main memory. When a class uses buffering, instead of writing one character at a time to the file, it accumulates the data in a temporary location in memory, called a buffer. When the buffer is full or is flushed, the accumulated data is written to the file in one efficient operation.
212
Writing Primitive Types to Text Files
FileOutputStream, a subclass of the OutputStream class, is designed to write a stream of bytes to a file. The PrintWriter class is designed for converting primitive data types to characters and writing them to an output stream. print method, writes data without a newline println method, writes data then adds a newline
213
Example: Writing to a Text File
Suppose we want to write a String aString to a File try { FileOutputStream file = new FileOutputStream(filename, true); OutputStreamWriter filestream = new OutputStreamWriter(new BufferedOutputStream(file)); filestream.write(aString); filestream.flush(); file.close(); } Catch(IOException ioe) { System.out.ptintln(ioe.toString()); If more than one String is to be written then a loop can be used. Notice that the flush method needs to be called at the end to flush out the stream into the file. If this is not done the String is not written in the file!
214
Serialization Writing objects into a file involves a protocol of Java called: Serialization Objects are converted (serialized) into a byte stream and stored in the file. Reading objects from a file involves a protocol called deserialization. Objects are converted back to the particular data type that they belong to.
215
Serialization A State of an object is the particular value sof its attributes (fields) at a particular time. Saving a particular state via serialization is called “persistence”.
216
Writing Objects to a File
To write an object to a file, its class must implement the Serializable interface, which indicates that: the object can be converted to a byte stream to be written to a file that byte stream can be converted back into a copy of the object when read from the file The Serializable interface has no methods to implement. All we need to do is: import the java.io.Serializable interface add implements Serializable to the class header i.e public class MyClass implements Serializable
217
The ObjectOutputStream Class
The ObjectOutputStream class, coupled with the FileOutputStream class, provides the functionality to write objects to a file. The ObjectOutputStream class provides a convenient way to write objects to a file. Its writeObject method takes one argument: the object to be written.
218
Constructors for Writing Objects
Class Constructor FileOutputStream FileOutputStream( String filename, boolean mode ) creates a FileOutputStream object from a String representing the name of a file. If the file does not exist, it is created. If mode is false, the current contents of the file, if any, will be replaced. If mode is true, writing will append data to the end of the file. Throws a FileNotFoundException. ObjectOutputStream ObjectOutputStream( OutputStream out ) creates an ObjectOutputStream that writes to the OutputStream out. Throws an IOException.
219
The writeObject Method
Return value Method name and argument list void writeObject( Object o ) writes the object argument to a file. That object must be an instance of a class that implements the Serializable interface. Otherwise, a run-time exception will be generated. Throws an IOException.
220
Omitting Data from the File
The writeObject method does not write any object fields declared to be static or transient. You can declare a field as transient if you can easily reproduce its value or if its value is 0. Syntax to declare a field as transient: accessModifier transient dataType fieldName Example: private transient double totalRevenue;
221
Reading Objects from a File
The ObjectInputStream class, coupled with FileInputStream, provides the functionality to read objects from a file. The readObject method of the ObjectInputStream class is designed to read objects from a file. Because the readObject method returns a generic Object, we must type cast the returned object to the appropriate class. When the end of the file is reached, the readObject method throws an EOFException, so we detect the end of the file when we catch that exception.
222
Constructors for Reading Objects
Class Constructor FileInputStream FileInputStream( String filename ) constructs a FileInputStream object from a String representing the name of a file. Throws a FileNotFoundException. ObjectInputStream ObjectInputStream( InputStream in ) creates an ObjectInputStream from the InputStream in. Throws an IOException.
223
The readObject Method Note:
Return value Method name and argument list Object readObject( ) reads the next object and returns it. The object must be an instance of a class that implements the Serializable interface. When the end of the file is reached, an EOFException is thrown. Also throws an IOException and ClassNotFoundException Note: we detect reaching the end of the file in the EOFException catch block we use a finally block to close the file
224
Example Of Writing Objects
Suppose that we have a class called Vehicle. We could serialize the Vehicle class by making a minor change to the class: public class Vehicle implements Serializable We can exclude certain fields of the class from being serialized (and thus have their values written) by using the keyword transient in front of the declaration of the field. i.e. private transient double init_v; private transient double init_d;
225
Example Of Writing Objects
Vehicle va=new Vehicle(“My Vehicle”, 2, 3, 2.1, 3.5); try{ FileOutputStream fos=new FileOutputStream(“MyFile.ser”); ObjectOutputStream oos=new ObjectOutputStream(fos); oos.writeObject(va); oos.close(); } catch(IOException ioe) { System.out.println(“Error writing into file”); ioe.printStackTrace();
226
Example of Reading the Object From the File
try{ FileInputStream fis = new FileInputStream(“MyFile.ser”); ObjectInputStream ois = new ObjectInputStream(fis); Vehicle vh = (Vehicle)ois.readObject(); ois.close(); } Catch(IOException ioe) { System.out.println(“Error writing into file”); ioe.printStackTrace(); We can output the object’s attributes and observe that the values are the same as the ones we wrote in the file.
227
Client / Server client server 1 2
Socket: holds IP address and software port number number client server 1 Client’s Socket Listening Socket Data Port 2 1. Client contacts server’s listening port requesting permission to connect. If permission is granted communications take place via a data port dedicated to this client. Other clients can request permission to connect and also be given their own data port on the server.
228
Client / Server A multithreaded server handles each client communication with it in a separate thread for each client. Networking can be established in Java by using the java.net classes. In setting up the communications we can have two kinds of sockets : Connection oriented: Uses TCP/IP protocols. Requires a handshake to establish the communication and a handshake to end it. Reliable . Ensures that packets reach destination. Continuous Stream sockets. Think of it a s a phone call type of communication. Connectionless oriented: Uses datagram packets Does not require a handshake to start the communication or to end it. Unreliable. No guarantee that packets will arrive to their destination. Better performance than TCP but requires more coding. Think of it as writing a 10 page letter and putting it in 10 different envelops (one page in each envelop) and then mailing them.
229
Client /Server Three steps to create a Server process for TCP/IP:
Create a server socket object: ServerSocket ss= new ServerSocket ( 5000, 100); Where 5000 is the listening port for the server and 100 is the maximum number of clients that can connect. ss object represents the listening socket The following code lets the listening port to accept a request from a client: Socket connection=ss.accept();
230
Client /Server Notice that:
Program execution blocks at this line waiting for a client send connection request packets. Socket type object connection encapsulates the information about the client when it arrives i.e. client’s IP address, client ‘s port number. That when the server accepts it sends packets with information about itself including the port that is assigned to this client for data exchange. This port is assigned on the fly by the O.S. Program execution now resumes. Create input and Output Stream objects: ObjectInputStream input= new ObjectInputStream( connection.getInputStream()); //server gets input from client’s output stream ObjectOutputStream output=new ObjectOutputStream (connection.getOutputStream()); //server sends output out to the client’s input stream
231
Client /Server Notice that connection is the object that encapsulates the information about the particular client. Use the object streams to either read incoming data from the Input Stream (on the port assigned to this particular client) or write into the Output Stream to send data to the client. i.e. Output.writeObject(String message); Or (String) input.readObject(); Notice that objects can be serialized and exchanged between the client and the server in a serializable format (streams of ones and zeros).
232
Client /Server Steps 2 and 3 should be in a while loop that lets the server run continually and block while it is waiting fro a client’s request. The server should be started on its own DOS pane and then minimized letting it run in the background.
233
Client / Server Three steps to create a client process:
Create a Socket to ask connection with a server. Socket cs= new Socket(serverIP , port) Where serverIP is the IP address of the server (could be localhost if both client and server are on the same machine) and Port is the listening port number of the server (i.e in our example). Create Input and Output Stream objects as in step 3 of the server. i.e. ObjectOutputStream os= new ObjectOutputStream (cs.getOutputSream()); ObjectInputStream is= new ObjectInputStream (cs.getInputStream()); Process incoming and outgoing data.
234
Client / Server See example on the course’s web site for client server processes. Multithreaded Server: Needs a main thread that allocates threads to clients requesting connection. This main thread passes to the allocated thread a reference of the Socket objec that represents the particular client from step 2 of the server example. The allocated thread handles the subsequent communications between the client and the server by overriding the Thread class’ run method.
235
Client / Server Datagrams
Create Datagram Socket DatagramSocket socket= new DatagramSocket ( 5000) where 5000 is the assigned port Wait for incoming packets from client and capture them (notice that no listening port is involve d). DatagramPacket receivedpacket= new DatagramPacket ( data, data.length); Where data is a byte array to store the data read fro m the incoming datagram packets. program execution blocks at the following line of code: socket.receive(receivepacket);
236
Client / Server Datagrams
Process packet i.e. String mydata= new String (receivepacket.getData(), 0, receivepacket.length()); String clientaddress= receivepacket.getAddress(); String clientport= receivepacket.getPort(); Create datagram to send to data back to client. DatagramPacket sendpacket= new DatagramPacket (data) where data is some String. socket.send (sendpacket); Notice that 1) steps 2 and 3 should be within a while loop that keeps the server running while it blocks 2) that the cod efor 2 and 3 should be within try/catch for IOException 3) that th eserver should be in its own DOD pane.
237
Client / Server - Multicasting
See example Settingup Multicasting on the course’ s web site. In Multicasting we use connectionless communications (datagrams). A multicast group needs to be created and the group needs to be joined by members.
238
Client / Server - Multicasting
Let us look at example where we set up a messaging service that is controlled by a messaging server: 1 Client 1 2 Client 2 Server 3 Client 3
239
Client / Server - Multicasting
Client port created on the fly asks for permission to connect. The server accepts and creates a data port for the client on the fly. The information is sent to the client Client sends a message to a multithreaded port on the server if the request is accepted. The server creates a thread for this client to handle the client’ s message. The server has a multicast port to send data out to subscribers. The server sends out the message to all clients who have subscribe to the multicast port. The clients receive the message on a special port.
240
Client / Server - Multicasting
A Multicast group is identified by a class D IP address and by standard UDP port (datagram port). The allowable IP addresses are in the range: to inclusive. Address is reserved and not be used. One joins the group as follows: MulticastSocket ms = new MulticastSocket (6000); where 6000 is the agreed multicast port. InetAddress group =InetAddress.getByName(“ ”); where is the agreed multicast IP
241
Client / Server - Multicasting
ms.jointGroup ( group ); Now the member has joined other members that have done the same. To send a message to the members: create an array of type byte. place the message into the byte array. create the Datagram packet: DatagramPacket packet = new DatagramPacket ( buffer, buffer.length, address, port). where buffer is the byte array, address is the multicast IP and port is the port agreed for multicasting. socket.send ( packet );
242
Client / Server - Multicasting
To receive a packet: create a byte type array to store data from incoming datagram packet call it buffer. DatagramPacket receivedpacket= new DatagramPacket buffer, buffer.length); socket.receive ( receivedpacket); String message = new String ( receivepacket.getData () ); A member can leave the group by invoking: socket.leaveGroup ( address) ; where address is the multicast IP
243
Study Guide Look up examples on Client/Server posted on the course’s web site under the examples page.
244
George Koutsogiannakis/Summer 2011
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 7 George Koutsogiannakis/Summer 2011
245
Topics Javadoc tool. Java Database Connectivity (JDBC).
Using the Java Server (as an independent application server outside of NetBeans).
246
JAVADOCS CREATE AUTOMATICALLY HTML DOCUMENTATION FOR YOUR PROGRAMS SIMILAR TO THE JAVA API. EMBED THE PROPER COMMENTS FOR EACH CLASS, EACH METHOD, EACH PARAMETER. IDENTIFY AUTHOR, DATE AND VERSION NUMBER. CALL THE javadocs TOOL COMMAND LINE >javadoc –d name_of_directory_to_place_docs Package_name The folder for the documentation is with respect to the current directory where the source code is located.
247
Java Database Connectivity (JDBC)
An Application Server delivers applications to the Database. Handles the business logic of an application Database Application Server Queries submitted to the database and receive a response with data
248
Java Database Connectivity (JDBC)
The idea with Application Server is to centralize the business applications thus providing Data and Code integrity. Thus: Query updates are common to all users Security is common Performance is common Configuration handled by a single administrative unit. Some Java Platform Application Servers are: Java Server (Glass Fish) open source – SUN Microsystems BEA - WebLogic Websphere – IBM Red Hat – JBoss Apache Geronimo – Apache Foundation JRun - Adobe
249
Java Database Connectivity (JDBC)
Structure Query Language – SQL Provides keywords that allow to query a database in terms of performing: Searching for records (i.e. Select keyword). Updates of records. Creation of a database ( a collection of Tables). Creation of a Table within the database. Table shave records. Tables relate to each other. Deletion of records. Etc. DB Application Server Client
250
Structure Query Language (SQL)
Standard language for every relational database. Developed by IBM in the early 1970s. Includes operations for data definition and manipulation. i.e CREATE TYPE (user defined SQL data types) CREATE TABLE (defines name of table, names of columns, data type for each column, identify primary key column)
251
Structure Query Language (SQL)
SELECT, INSERT,DELETE, UPDATE (data manipulative operations). Other operations facilitate view of data in a table, and there are also other keywords that can be part of an SQL statement. Complete set SQL keywords can be found on the web.
252
DATABASE DATABASE SCHEMA: refers to the tables that make up the database and their relationships to each other. For each table the previous slide description of columns has to be provided.
253
DATABASE Most Databases allow SQL statements to be executed
directly (in other words the scripted SQL statements) As part of another language. SQL statements are mixed with other language coded in which case it is called “Embedded SQL”
254
DATABASE The term “database server” is the same as the DBMS (data base management system) The database server supports all the SQL operations. Clients to the database server provide the applications that are to be run by the DBMS.
255
DATABASES and JDBC Client applications can be written as embedded SQL in other languages such as JAVA. JAVA has an API called JAVA Database Connectivity (JDBC) for that purpose. JDBC provides the ability to connect to a database server and to send embedded SQL statements to the database server for execution. JDBC also provides the ability to process data returned from the database server.
256
Java Database Connectivity (JDBC)
Problem: There are many versions of SQL. Vendors of Databases provide their own version. Solution Provide drivers that translate a version. Need to be installed on both sides -client to the database (Application Server) and server (the server for the database).
257
Java Database Connectivity (JDBC)
Java provides its set of drivers for various databases. Microsoft has its own set of drivers for various databases called: ODBC – Open Data Base Connectivity. Problem with Java: More database vendors support ODBC than they support JDBC.
258
Java Database Connectivity (JDBC)
For example: Client’ query gets translated to ODBC driver on the client side. The ODBC driver on the server side translates back to the query version for the database. Drivers Drivers Server-host of database Client-Application server
259
Java Database Connectivity (JDBC)
Java Drivers: Type 1: JDBC-ODBC bridge. Provides access to a database from a Java application (JDBC) via ODBC drivers. Type 2: Native API: converts JDBC calls to calls understood by the particular database. Requires some binary code proprietary to the database be installed on client machines. Type 3: Net-protocol: Translates JDBC calls into some independent network protocol which in turn gets translated into the database protocol by a server. Supports internet access of a database. Vendors need to provide the middleware. Type 4: Database supports JDBC drivers directly. JDBC to JDBC driver communication.
260
Java Database Connectivity (JDBC)
In our examples we will use ODBC drivers. Therefore we will use the JDBC to ODBC bridge driver. We assume that our database has ODBC capability. Therefore we need to register our database with the ODBC drivers in our local environment where the database resides. Procedure for registering a Database with ODBC drivers: Control Panel -> Performance and Maintenance -> Administrative Tools. Click on Data Sources (ODBC) In User DSN Select Data Source (database) ie. Access Click Add
261
Java Database Connectivity (JDBC)
Create New Data Source Select Driver (i.e MS Access Database *.mdb ) Click Finish MS Access Set Up Dialog appears Data Source Name: Add name of your database without extension. Description: Optional entries. Click Advanced. Set Advanced Options appears: Enter a login user name and a password for your database. Click OK
262
Java Database Connectivity (JDBC)
Back to Microsoft Access Set Up Dialog window: Click Select Browse to your database’s directory (folder) Highlight path and click OK. Registration process completed. Close all windows.
263
Java Database Connectivity (JDBC)
Code highlights for establishing a query and executing it: import java.sql package URL String : String url = “jdbc:odbc myDB” ; //where myDB is the name of your database. Class Definition for the proper Driver to establish the JDBC to ODBC bridge: Class forName(“sun.jdbc.odbc.JdbcOdbcDriver”); returns the class object associated with the driver . Declare a reference of the Connection interface; Connection con: Use static method getConnection of the DriverManager class to attempt a connection to the database: con = DriverManager.getConnection( url, username, password);
264
Java Database Connectivity (JDBC)
Establish the query as a String i.e.: String query= “Select *From Authors” ; // Select all fields from table Authors in the database. Need a reference of the Statement interface in order to submit the query: Statement stat; stat = con. createStatement() ; Execute the query and get the results: ResultSet results= stat.executeQuery(query); object results encapsulates the data provided by the execution of the query (if successful).
265
Java Database Connectivity (JDBC)
We can analyze the ResultSet results object to extract the data and display it, for example, to the user. A JTable component would be ideal for such a display. The ResultSet object contains rows of data and the names of the fields (columns). We can move a cursor from row to row: results.next(); moves the cursor and return s a boolean true if there is another record. boolean moreRecords= results.next(); We also need to capture the data type of record in each field: Class ResultSetMatadata allows discovery of data types ResultSetMetadata rsmd = result.s getMetadata(); int col = rsmd.getColumnCount(); String name = rsmd.getColumnName (col); int type = rsmd.getColumnType(col); //type is the coded sql data type String type_name = rsmd.getColumnTypeName(type);
266
Java Database Connectivity (JDBC)
Column names are represented by class java.sql.Types Types are coded by an integer value: 1 means CHAR type 3 means DECIMAL type 8 means DOUBLE type etc. Types here are SQL types used when the fields (columns) of the database are created.
267
Java Database Connectivity (JDBC)
More on ResultSet object: ResultSet object has characteristics: result set type: Determines ways the cursor can be manipulated and how concurrent changes made to the database are reflected in the resultSet object. Types are: TYPE_FORWARD_ONLY: Cursor moves forward only. Data can be either at the time the query was executed or at the time the rows were retrieved. TYPE_SCROLL_INCENSITIVE: Cursor is scrollable in both directions from current position. Not sensitive to changes to the data made by others concurrently. TYPE_SCROLL_SENSITIVE: Cursor is scrollable in both directions. Sensitive to concurrent changes to data.
268
Java Database Connectivity (JDBC)
Set these attributes by using the createStatement method: Statement stat = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); where con is the Connection object. If no arguments are given to createStatement the default settings are then: TYPE_FORWARD_ONLY and CONCUR_READ_ONLY
269
Java Database Connectivity (JDBC)
RowSet Interface Configures the database connection automatically and prepares query statements. Used by JavaBeans and EJB s Need a tool like NetBeans to use RowSet. Connected RowSet –connects to database and remains connected until the application terminates (i.e possibly more than one query needs to be submitted). Disconnected RowSet –connects , executes query and disconnects.
270
Java Database Connectivity (JDBC)
PreparedStatements interface Provides objects that are maintained in a compiled form. Can specify parameters where a query can be executed with different parameters each time. The advantage is that we don’t have to recompile if we want to change the parameters in the query.
271
Java Database Connectivity (JDBC)
PreparedStatement authorBooks = con. prepareStament (“Select lastName, firstName, title From Authors, Titles, AuthorISBN Where Authors.authorID=AuthorISBN.authorID AND Titles.ISBN=AuthorISBN.isbn AND lastName=? AND firstName= ?”); Authors, Titles, AuthorISBN are table sof the database ? Acts as a placeholder for values that will be passed programmatically to the query during execution. It is assumed that set methods for the variables exist in the program. The parameters can be set like: authorBooks.setString(1, “Kay”); authorBooks.setString(2, “George”);
272
Java Database Connectivity (JDBC)
Transaction Processing. A set of database operations that are treated as a single operation. Method setAutoCommit(true) of interface Connection specifies that a single operation at a time completes execution and that data in the database is changed. Method setAutoCommit(false) specifies that a group of statements are to be executed. When all statements are executed method commit is called to finalize the data in the database. If the transaction fails: con.rollback() clears the data and the data is not changed in the database (where con is the Connection object)
273
Java Database Connectivity (JDBC)
STORED PROCEDURES SQL Statements are stored in the database . Applications accessing the database can invoke them. The SQL statement (s) execute and return the results. An application can pass parameters to a stored procedure (like in a prepared statement). To implement it you create the SQL statement (query) String createProcedure = “create procedure SHOW_SUPPLIERS as Select Suppliers.supplierName from Suppliers, Coffee where Suppliers.suplpierID=Coffee.supplierID”; Statement stat = con.createStatement(); Stat.executeUpdate(createProcedure);
274
Java Database Connectivity (JDBC)
The result of the previous code is that procedure SHOW_SUPPLIERS will be compiled and stored in the database as a database object that can be invoked. To call a stored procedure from JDBC application: Create a CallableStatement object: CallableStatement cs= con.prepareCall(“(call SHOW_SUPPLIERS)”); ResultSet rs = cs.executeQuery();
275
Java Database Connectivity (JDBC)
Parameters can be passed if the proper SQL syntax is used both when the procedure was created and when it is called. Use IN, OUT INOUT SQL syntax when the procedure is craeted. call procedure_name(param1, param2….) Or we can do it programmatically like a prepared statement: i.e. Suppose the procedure setDeathAge is stored in the DB. CallableStatement proc= con.prepareCall (“(call setDeathAge(?, ?))”); proc.setStrng(1, name); proc.setInt(2, int); proc.execute();
276
JDBC Example public BasicJDBCDemo()
package com.devdaily.sqlprocessortests; import java.sql.*; public class BasicJDBCDemo { Connection conn; public static void main(String[] args) { new BasicJDBCDemo(); } public BasicJDBCDemo() try
277
JDBC Example Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://localhost/coffeebreak"; conn = DriverManager.getConnection(url, "username", "password"); doTests(); conn.close(); } //end of try
278
JDBC Example catch (ClassNotFoundException ex) {System.err.println(ex.getMessage());} catch (IllegalAccessException ex) {System.err.println(ex.getMessage());} catch (InstantiationException ex) {System.err.println(ex.getMessage());} catch (SQLException ex) { System.err.println(ex.getMessage()); } } // end of public BasicJDBCDemo() method
279
JDBC Example private void doTests() { doSelectTest(); doInsertTest(); doUpdateTest(); doDeleteTest(); }
280
JDBC Example private void doSelectTest() { System.out.println("[OUTPUT FROM SELECT]"); String query = "SELECT COF_NAME, PRICE FROM COFFEES"; try Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(query); while (rs.next()) String s = rs.getString("COF_NAME"); float n = rs.getFloat("PRICE");
281
JDBC Example System.out.println(s + " " + n); }
catch (SQLException ex) { System.err.println(ex.getMessage()); private void doInsertTest() System.out.print("\n[Performing INSERT] ... ");
282
JDBC Example try { Statement st = conn.createStatement(); st.executeUpdate("INSERT INTO COFFEES " + "VALUES ('BREAKFAST BLEND', 200, 7.99, 0, 0)"); } catch (SQLException ex) System.err.println(ex.getMessage()); }
283
JDBC Example private void doUpdateTest() { System.out.print("\n[Performing UPDATE] ... "); try { Statement st = conn.createStatement(); st.executeUpdate("UPDATE COFFEES SET PRICE=4.99 WHERE COF_NAME='BREAKFAST BLEND'"); } catch (SQLException ex) System.err.println(ex.getMessage()); } }
284
JDBC Example private void doDeleteTest() {
System.out.print("\n[Performing DELETE] ... "); try { Statement st = conn.createStatement(); st.executeUpdate("DELETE FROM COFFEES WHERE COF_NAME='BREAKFAST BLEND'"); } catch (SQLException ex) { System.err.println(ex.getMessage()); }
285
Using the Database in a Web Application Development
The database queries will come from either one of two architectures of a Web Application Development that we are going to study: Web Server to an RMI server or Web Server to an Application Server. The first Half of the course will use RMI servers to connect to the database server. In the second half we will use an Application server: Let us however cover some basics about the Application Server that we will be using in the second half of the course.
286
IT IS THE CLIENT TO THE DATABASE SERVER
APPLICATION SERVER APPLICATION SERVER DATABASE SERVER IT IS THE CLIENT TO THE DATABASE SERVER
287
Using The Java Server. The Java Server is an Application Server (Glass Fish server -version 3 at this time). The Java Application Server is free and can be downloaded from Sun’ s site. It is available as an independent download from Or, it can be downloaded as part of NetBeans. The next few slides discuss the Java Server as a stand alone server outside of NetBeans.
288
Using The Java Server. Java Server provides Tool: Admin Console
A web-based GUI Enterprise Server administration utility. Used to stop the Enterprise Server and manage users, resources, and applications. Tool:asadmin A command-line Enterprise Serveradministration utility. Used to start and stop the Enterprise Server and manage users, resources, and applications. Tool:appclient A command-line tool that launches the application client container and invokes the client application packaged in the application client JAR file. Tool:capture-schema A command-line tool to extract schema information from a database, producing a schema file that the Enterprise Server can use for container-managed persistence.
289
Using The Java Server. Tool: package-appclient Tool:Java DB database
A command-line tool to package the application client container libraries and JAR files. Tool:Java DB database A copy of the Java DB database server. Tool:xjc A command-line tool to transform, or bind, a source XML schema to a set of JAXB content classes in the Java programming language. Tool:schemagen A command-line tool to create a schema file for each namespace referenced in your Java classes.
290
Using The Java Server. Tool:wsimport Tool:wsgen
A command-line tool to generate JAX-WS portable artifacts for a given WSDL file. After generation, these artifacts can be packaged in a WAR file with the WSDL and schema documents along with the endpoint implementation and then deployed. Tool:wsgen A command-line tool to read a web service endpoint class and generate all the required JAX-WS portable artifacts for web service deployment and invocation.
291
Using The Java Server. General Information about the Java Server.
See site: Or, See information which is part of NetBeans Help.
292
Using The Sun Java Server
Default port : 8080 (could conflict with your installation of Tomcat- change the default port to 80 in one or the other during installation). Administrative server default port: 4848 (make sure it is not used by another application in your system). A domain is a one or more Java Server instances managed by the same administrative server. If you start the server command line you can specify a domain otherwise the default domain is domain1.
293
Java Server What is GlassFish v3?
GlassFish Enterprise Server v3 is the industry’s supports Java Platform, Enterprise Edition 6 (the Java EE 6 platform). Installations requires JDK 6. The minimum and certified version of the JDK software depends on the operating system. Included in GlassFish if you do a download independent of NetBeans: Java Platform, Enterprise Edition 6 JTS/JTA 1.1 JPA 2.0, (EclipseLink), JDBC Connection Pooling JDBC 4.0 OMG CORBA APIs 3.0 JavaMail 1.4 Web Services APIs Many Other APIs
294
Using The Java Server. To stop the server after you start it from start menu . >asadmin stop-domain domain1 (or from start menu) You can start the db server from the start menu. You can stop the db server command line > asadmin stop-database (or from start menu). You can start the administrative console after you start the Java Server from start menu or by opening an instance of your browser and entering the address: Just like in Tomcat there is a log file in the Java Server that can give you debugging information. The log file is located in your Java Server installation home directory /domains/domain1/logs/server.log It can be viewed from the administrative console log viewer or with a text editor.
295
Study Guide Web Based Applications Development chapter 8.
296
George Koutsogiannakis/Summer 2011
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 8 George Koutsogiannakis/Summer 2011
297
Topics Web Applications and the Java Server. HTTP protocol. Servlets
298
Web Applications Two Types of Web Applications:
Presentation oriented: Interactive web applications with dynamic content usually provided with DHTML, XML, servlets or java server pages. Service oriented: Web applications that utilize presentation oriented applications as clients. They consist of web services, SOAP protocol services, RMI etc.
299
Web Applications For example an Aplication server or an RMI server that processes Queries to the databse server. It receives the results of the query formats it and passes it over to the presentation oriented application so that it can be sent to the requestor (client of the presentation application)
300
Web Applications Web Components: Servlets, JSP (Java Server Pages).
Web Components are supported by a web container. For instance: Tomcat has a servlet engine and a JSP engine. Those engines are the web containers.
301
Web Applications Web Containers provide to web components: Activation
Initialization Configuration Translation from http to a servlet request object and Translation from a servlet response object to http.
302
Web Applications Web Components can communicate directly with a database (via JDBC) or They can communicate with a database via Java Beans components or They can communicate with other service oriented applications such as a RMI server, or web services, or an application server.
303
Web Applications Database Database Client RMI Server Web Components
HTTPServletRequest Object Database HTTP Request Containers Web Components Client HTTPServletResponse Object HTTP Response Java Bean Components RMI Server Web Services Database
304
Web Applications Life Cycle of a Web Application:
Develop web component(s) code (i.e servlet code or jsp code). Develop the web application deployment descriptor (i.e. the web.xml file in Tomcat). Compile the web components code. Package the application into a deployable unit (i.e. a WAR file). Deploy the application into the container. Undeploy the application if needed. Access a URL from a client that references the web application.
305
Web Applications Web Resources: Web Module: Web Components.
Static web content files. Web Module: The smallest deployable web resource. Same as a web application. Contains: web resources, java beans, applets other types of files.
306
Web Applications A web module can be packaged into a WAR file web.xml
WAR files are made with the jar utility and they have a .war extension. To deploy a WAR file on an Application Server, the file must have a deployment descriptor (i.e. web.xml for Tomcat or sun-web.xml for Java Server). The deployment descriptor file is placed in the folder: CONTEXT ROOT (ASSEMBLY ROOT) WEB-INF web.xml
307
Web Applications Packaging a Web Application: Use a WAR file or
Use an IDE like NetBeans (possibly a separate download from EE 5) or Use a utility tool called ants (part of EE 5 download).
308
Web Applications Deployment on an Application server:
WAR file can be placed into the <JavaEE_Home>/domains/domain1/autodeploy directory of Java Server (Java Application Server). Or by using the Administrative Console of Java Server. Or by running asadmin or ant command line to deploy the WAR file. Or by using NetBeans. Note: Deploying details are described in your “Java EE 6 Tutorial” text
309
HTTP Protocol Request/ Response packets.
Client initiates a request via a TCP connection to a port (8080 or 80). Server sends a response packet to client Protocol provides methods such as: GET POST PUT DELETE HEAD And others
310
HTTP Protocol If GET is used by client then:
Data can be part of the URL Data is not cached by the browser application. Data is URL encoded i.e. spaces are converted to + signs, nonalphanumeric characters are converted to % signs followed by the two hex digits representing the character etc. Use it when the data is small.
311
HTTP protocol If client uses POST:
The data is part of the body of the HTTP packet. Data is cached. Use it if data is larger and the interaction with the server changes the state of the resource in the server.
312
HTTP Protocol Error messages can be returned by the server in the response packet. Error messages are coded: 400 means bad request. 401 means unauthorized request. 500 Internal server error. Etc.
313
Servlets A servlet is a java program that executes on the server side.
It extends the capabilities of a server. Two types of servlets: Generic type HTTP type Note: nevertheless other protocols can be supported such as FTP, POP, SMTP We will concentrate on HTTP type.
314
Servlets HTTP type servlets
Extend the web server by executing requests received in HTTP (from a client) protocol packets and by returning responses that are translated back to HTTP protocol packets.
315
Servlets Clients to Servlets
Client side programs that sent requests can be: Html files (forms). Applets. JavaScript. XML. Java application programs. Active Server pages (ASP) programs. Other.
316
Servlets Execution environment:
Web Server needs the servlet engine (container). The interface between the servlet engine and the servlet program is defined by the Servlet API.
317
Servlets The servlet container is responsible for:
Creating an instance of the servlet program. Calling the servlet’ s init() method to initialize the servlet. Configures the servlet according to preset properties. Calling the servlet’ s service method. Creating the stream to send to the servlet a request object that encapsulates an y data the client sent as part of the request. Creating the stream to receive the response object from the servlet that encapsulates the data generated by the servlet as a result of the request. Can handle multiple service calls that be made simultineously (multiple requests arriving at the same time). Destroys the servlet by calling destroy() method.
318
Servlets Servlet applications provide:
Processing of a Get or Post type of a request via individual methods that need to be overridden. The servlet engine reads the request type off the arriving HTTP packets, calls the service method of the servlet, the service method will call either a doGet or doPost servlet method. Handle many requests at the same time. Provide session capability with a client so that multiple request/response pairs can be serviced without loosingtrack of the particular client. Can communicate with other servlets forming a chain.
319
Servlets Can generate a response in Html tags. The servelt engine will extract the html code from the java code and form send it to the client. This facilitates the generation of dynamically formed responses based on the request. Can execute JDBC code to connect to a database and retrieve information. The response object will then encapsulate the data. Can act as clients to a Remote Method Invocation Servers in a distributed objects network. Can communicate with Java Beans.
320
Servlets Servlet API javax.servlet javax.servlet.http
Servlet interface Implemented by abstract class Implemented by abstract class GenericServlet HttpServlet
321
Servlets The abstract classes provide default implementation for methods: void init(ServletConfig config) ServletConfig getServletConfig() void service(ServletRequest requ, ServletResponse resp) String getServletInfo() void destroy() In addition, the HttpServlet class has methods: doGet (HTTPServletRequest requ, HttpServletResponse resp) doPost (HTTPServletRequest requ, HttpServletResponse resp) These methods have to be overridden by the servlet class that the developer provides.
322
Servlets ServletResponse ServletRequest interface interface
HttpServletResponse Passes response object from doGet or doPost method to service method Service method passes response object to servlet engine ServletRequest interface HttpServletRequest Passes request object to service method Service method passes request object to servlet ‘s doGet Or doPost method.
323
Servlets Several Listener interfaces are there to provide listeners for various event handlers that: Access information when an event occurs. Must implement one of the interfaces: ServletContextListener: initialization and destruction information ServletContextAttributesListener: web context attribute added, removed, replaced. HttpSessionListener: information on creation, invalidation of a session, activation of a session, timeout of a session. HttpSessionAttributesListener: session attribute has been added, removed or replaced HttpRequestListener and HttpRequestAttributeListener: information on attributes associated with a request.
324
Servlets Example: Client receives an HTML form.
The form in its action tag calls a servlet. The servlet creates html code and sends back to the client for display by the browser.
325
Servlets Example-File helloworld,html (simplified)
<html> <head> <title>Untitled Document</title> </head> <body bgcolor="#FFFFFF"> <p><a href="servlet/HelloWorldExample"></p> </body> </html>
326
Servlets Example – file HelloWorld.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Hello World!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello World!</h1>"); out.println("</body>"); out.println("</html>"); } }
327
Servlets Example – file HelloWorld.java
The Browser receives the html code: <html> <head> <title>Hello World!</title> </head> <body> <h1>Hello World!</h1> </body> </html>
328
Servlets-Another example
<html> <hesd> <body> <Form action= method=“POST”> <table><tr><td> <Input types=“Text” Name=“firstName”></input></td></tr></table> </form> </body> </head> </html>
329
Servlets-Another example TechSupport.java file
import javax.servlet.*; import javax.servlet.http.* import java.io.*; import java.util.*; public class TechSupport extends HttpServlet { protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException { res.setContextType(“text/html”); String myparam=req.getParameter(“firstName”); PrintWriter out = res.getWriter(); out.println(“<HTML>”); out.println(“<HEAD>”); out.println(“<BODY>”);
330
Servlets-Another example
if(myparam.equals(“MyName”)) { out.println(“<p”>); out.println(“You can now login”); out.println(“</p>”); } else { out.println(“<p”>); out.println(“I don’t recognize you”); out.println(“</BODY>”); out.println(“</HEAD>”); out.println(“<HTML>); out.close();
331
Servlets-Another example
The web.xml deployment descriptor file has to be created for the servlet: <web-app> <display-name>Servlet Example</display-name> <description>Simple servlet responding to a form</description> <servlet> <servlet-name>TechSupport</servlet-name> <servlet-class>TechSupport</servlet-class> </servlet> <servlet-mapping> <url-pattern>/TechSupport</url-pattern> </servlet-mapping> </web-app> //where TechSupport.class is the servlet bytecodes file residing in the classes folder of Tomcat.
332
Deployment on Tomcat Web Server
To deploy the web examples discussed you can: Install Tomcat by itself (do not install NetBeans at this time) Create a war file and deploy the war file in Tomcat. Or, install NetBeans. Add Tomcat and GlassFish v2 as active servers in NetBeans. Start Tomcat from NetBeans.
333
Working with servlets outside of EE
The servlet API is only available on EE. Ther you would find the latest version of servlet API. I have,however,retained an independent version of servlet API that can be installed and become part of your standard edition. It is an old API but it would allow us to work with servlets at this level in an easier way.
334
Enabling SE with the servlet API
Download from the examples page of the course the file : SERVLET.ZIP Unzip the file and you will find two jar files inside. Copy the two jar files and paste them in the path of your jdk installation C:\>Program Files\Java\jdk1.6.0_18\jre\lib\ext\ Now you can compile source code files that include servlet (and java server pages ) libraries. Note that this an old API that I copied few years back. This is not available anymore and you can’t compile servelts normally with the standard edition (You need Enterprise Edition).
335
Deployment in Tomcat The servelt compiled code should reside in the WE_INF /classes folder of the Tomcat Root Context structure. ROOT_CONTEXT .html, applet.class files WEB_INFO web.xml CLASSES myservlet.class
336
Study Guide SUN ‘s acquisition by Oracle has been finalized and the web sites for Java Tutorials are beginning to change since February 1st. The Java EE 6 Tutorial has been changed and the organization of the material has changed the last two weeks (after our course started)
337
Study Guide WEB APPLICATIONS WITH SERVLETS WBAD CH8
Servelts are now covered in Part II chapter 10 of “The Java EE 6 Tutorial” text. This change is effective February 2010. See servlet examples on the course ‘s web site.
338
George Koutsogiannakis/ Summer 2011
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 9 George Koutsogiannakis/ Summer 2011
339
Topics Continue with Servlets Content Types HTTP Tunneling.
URL connections. Applet to Servlet communication. Application to Servlet communication. Session object. Servlet to other server side resources communication.
340
Servlets - Definition A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.
341
Servlets - Definition The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines life-cycle methods. When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.
342
Servlet Engine and Servlets
Communication from client is received by the web server in the form of HTTP packets. The web server reads the packets and passes information to the servlet engine (container). The container does the following:
343
Servlet Engine (container) and Servlets
Web Servers get the capability to communicate with servlet programs installed in their environment by having the servlet engine or container as part of their environment. The container: Activates the init and getServletContext methods if this is the first time that the servlet is being called after the web server was activated. Calls the service method. The service method creates the request and response objects.
344
Servlet Engine (container) and Servlets
The service method establishes the streams of communication between the container and the servlet. The service method calls either the doPost or the doGet method implementations in the servlet based on the type of request that was recognized coming from the client.
345
Servlet Context The servlet is responsible for setting the type of context that would be include in the HTTP packets that will be sent back to the client. The kind of content determines the type of streams needed on the client side in order to receive the data sent as part of the response. If the client does not know the type of the context, it can be discovered from the headers of the incoming HTTP packets (received by the client) The various content types are defined in MIME – Multipart Internet Mail Protocol
346
Servlet Context There are many different MIME content types i.e.
text/html : refers to HTML text data text/plain : refers to plain text documents image/gif : refers to the fact that a gif file will be produced and sent application/octet-stream : refers to the fact that the data is in the form of an executable or binary data. application/x-java : java program application/x-csh : UNIX C-shell program Etc. The complete MIME types can be found on the Internet by Googling MIME
347
Getting Info from Request Objects
The Request object contains information extracted from the HTTP packets received from the client by the web server (web container). Such information includes: Parameters that are passed from the client to the servlet. Objects and their attributes. Information about the protocol used to communicate between the client and the server.
348
Getting Info from Request Objects
Information about the client. Information about the server. The type of request (GET or POST). The type of content (MIME) Other
349
Information placed on Response Objects
Content type returned by the response to the client (i.e. content generated by a servlet , sent to the web container, web container extracts the data from the response object and inserts it in the HTTP packets to be sent to the client) The data sent by the server to the client. Status codes that indicate why a request could not be honored. Session id. Cookies (files to be sent to the Browser and reside in local client environment). Information about the client and the server. Other.
350
Filters Programs that are used to:
Authenticate a request Modify a request or a response Block the request and response form going through. A web resource can be filtered by one or more filter programs. Filters are used by using the Filter interface and overriding its doFilter method (javax.servlet package). The web container decides how to use filter programs based on filter mapping tags entered in the deployment descriptor (web.xml).
351
HTTP Tunneling Refers to sending data back in a different protocol than HTTP nevertheless enveloped by HTTP. i.e. the server is sending data back to an applet client program in a binary form or bytes. Or the server contacting another server, such as a RMI server, to send data using the Remote Method Invocation Protocol as the transport protocol (or the RMI over IIOP transport protocol).
352
HTTP Tunneling-Applets to Servlets communication-GET
Example of tunneling is an applet communicating with a servlet via either GET or POST i.e Applet generates data for Web Component using GET / Reading Binary data by an applet: Create a url object that identifies the host url. URL url= new URL(“ Notice that it is assumed that the HTTP method is GET since the data is part of the URL. Notice that the parameter is id but the value of it is held by variable custid.
353
HTTP Tunneling-Applets to Servlets communication-GET
Parameters are separated from the address part of URL by ? Additional parameters are separated by & URL url= new URL(“ The parameters are id and fn and their values are held by variables custid and fn (notice the name/value pair for each parameter) Create a URLConnection object. Calling OpenConnection method returns a URLConnection object that can be used to obtain streams . URLConnection uc=url.openConnection();
354
HTTP Tunneling-GET Instruct the Browser not to cache the data:
uc.setCaches(false); Set other information in HTTP headers uc.setRequestProperty(“header_name”, “value”); Use one of the input streams to read the response back from the servlet. If the data from the servlet , for instance, was text/html (IN OTHER WORDS THE CONTEXT WAS SET FOR text/html BY THE SERVLET)
355
HTTP Tunneling-GET BufferedReader in = new BufferedReader ( new InputStreamReader (uc.getInputStream())); String line; while ( (line=in.readLine()) ! = null ) { read the data and do something } in.close();
356
HTTP Tunneling Other types of context require different type of streams (for instance object streams if the content is set for serializable objects) Note: HTTP packets have a Header part and a Body part. The header contains standard named attributes whose values we can set. The String “header_name” in method setRequestProperty (see previous slide) represents the name of the HTTP header attribute whose value we are setting . The http Header has pre defined fields whose value scan be set programmatically by the applet (or an java application program acting as clients. Or by a Browser).
357
HTTP Tunneling-Serializable Data Received by the Client
What if the data is binary in the form of object’ s data? In other words serializable objects have been created by the servlet and sent over the network to the applet client. Serializable interface creates serializable objects using Java’ s serialization protocol. Serialized objects can be sent to another resource in binary form and deserialized at the destination. To receive (by the Applet client as an example) the serialized data sent by the servlet the code is formed as follows by the client:
358
HTTP Tunneling-Serializable Data Received by the Client
Assume that we have a separate class on the server side, that has a method which gets the data from the data base puts it into a vector and that this class implements the interface Serializable.. This class returns a vector object which is serializable. The serilizable object is sent by the servlet to the client. Create an ObjectInputStream ObjectInputStream in = new ObjectInputStream ( uc.getInputStream()));
359
HTTP Tunneling-Serializable Data Received by the Client
Now read the object. As an example: The servlet got data from a database and place it into a vector. The servlet then serialized the vector and sent it as part of the response. The code: Vector myvector = (Vector)in. readObject(); deserializes the Object received into a Vector data type. The object myvector now has the data sent by the servlet.
360
HTTP Tunneling-Serializable Data Sent by the Servlet
What does the servlet have to do to send the serialized data: Specify that the content is of binary format data. res.setContentType(“application/x-java-serialized-object”); Create an object output stream ObjectOutputStream out = new ObjectOutputStream (res.getOutputStream() ); Write the object into the output stream:
361
HTTP Tunneling-Serializable Data
MyVectorClass mvc= new MyVectorClass(); Vector myvector = mvc.getVector(); out.write(myvector); out.flush(); Where MyVectorClass is the class, on the server side, that serializes the vector that contains the data.
362
Applet sends binary data to Servlet as POST
Create URL object and URLConnection as in slides 5 and 6. The data , however, will not be part of the url this time. Tell system to permit applet to sent data (this is NOT in lieu of the required certificate). uc.setDoOutput(true); Create a ByteArrayOutputStream object ByteArrayOutputStream bytestream= new ByteArrayOutputStream (512); 512 bytes of data to be sent. PrintWriter out =new PrintWriter(bytestream, true); Place data into a buffer: Use either print if data is Strings or writeObject
363
Applet sends binary data to Servlet as POST
Suppose it is a String that represents the data: Need to url encode any parameters: String val1= URLEncode(someval1); String val2= URLEncode (someval2); String data= “param1=“+val1+”param2=“+val2; Write the data into the stream: out.print(data); out.flush(); out.close(); // the data is written into the bytestream object
364
Applet sends binary data to Servlet as POST
Set the Content Length (required for POST) uc.setRequestProperty(“Content-length”, String.valueOf(bytestream.size()); Set the content type: uc.setProperty(“Conetent-type”, “application/x-www-form-urlencoded”); Send the data out: bytestream.writeTo(uc. getOutputStream());
365
Applications to Servlet
If the client is an application program instead of an applet the same procedure is followed to have the application communicate either via GET or via POST with the servlet. The only difference is that no Browser is needed to execute the applet and the code for the application did not come from another server but it resided in the client’ s local system.
366
Sessions Collaborating web resources in a server share information via objects. These objects are maintained as attributes of 4 scope objects. The attributes are accessible via methods like getAttribute or setAttribute. Scope Object Class Accessible From Web context javax.servlet.ServletContext Web components within a web context Session javax.servlet.http.HttpSession Web components handling a request that belongs to a session Request javax.servlet.SerletRequest Web components that handle the request Page javax.servlet.jsp.JspResponse The JSP page that creates the object
367
Session Management Sessions have time out periods if no request is received from a client that has a session established The time out period can be set in the web.xml file that is in the conf directory of the server (not the web.xml for your web application) <session-config> <session-timeout>30</session-timeout> </session-config> Timeout is set to 30 minutes in the above example.
368
Session Management Keeping track of a session via a session object is called server side session tracking. This is different than using cookies which are files that are stored on the client side by the server. The web container associates a session with a client. The web container is responsible for generating a session id. A session identifier is created for each client. The identifier is sent to the client as a cookie and it is included or as an alternative the web component (servlet) can include the session id in every response to the client.
369
Session Management Create a session object in your web component:
HttpSession session = request.getSession(true); Either a new object is created or an existing one is returned to the servlet by the web container each time a request is made. You can store attribute_name/value pairs in the session object. There are pieces of information that you can extract using the session object: session.getID(); returns the session id for the client as a String. session.isNew(); returns true if the client has never seen a session. session,getCreationTime(); returns the time in milliseconds since the session was created. session.getLastAccessedTime(); returns the time in milliseconds since the last request generated a session. session.getMaxInactiveInterval(); returns the time in milliseconds that the session can go without access before it gets invalidated. session.getAttributeName(String name); returns the object bound by the name in the session. session.setAttribute(String name, Object obj); bounds an object obj by the String name. In the session
370
Session Management Example of session management:
HttpSession session= request.getSession(true); session.setAttribute("userName",request.getParameter("myname")); -----We store in the session object, as an object, the name retrieved from parameter myname (assuming that the user has entered a name captured by myname).
371
Session Management -------Later on we check for the session:
session = request.getSession(true); if (session.getAttribute("userName") == null) { session.setAttribute("userName", "Stranger"); } else PrintWriter out = response.getWriter(); out.println("Welcome " + (String) session.getAttribute("userName") + "!");
372
Session Management Another example:
Suppose class ShoppingCart stores selected items in a shopping cart object. HttpSession session = request.getSession(true); ShoppingCart cart = (ShoppingCart)session.getAttribute(session.getId()); // If the user has no cart, create a new one if (cart == null) { cart = new ShoppingCart(); session.setAttribute(session.getId(), cart); } The card object is associated with the particular session id associated with the client.
373
Session Management Because an object can be associated with a session, the Duke's Bookstore example keeps track of the books that a user has ordered within an object. The object is type ShoppingCart and each book that a user orders is stored in the shopping cart as a ShoppingCartItem object. Retrieving the shopping cart from the session in order to add new item in it: HttpSession session = request.getSession(true); ShoppingCart cart = (ShoppingCart)session.getAttribute(session.getId());
374
Servlet calls other resources
RequestDispatcher Object allows another resource to be called: Example of calling an html file from a servlet: getServletContext().getRequestedDispatcher(“examples/applications/bookstore/bookstore.html”); Returns the html page . The resources called can be Another servlet A Java Server Page Html Other
375
Servlet calls other resources
Two types of requests for resources: Forward request Include request. ………………. 2 ………………….. 3 ………………….. 4 ………………….. 5………………….. 6…………………… . Servlet 1 Request object from container Servlet 2 Request/Response objects sent to servllet 2 Response object to container Forward Request
376
Servlet calls other resources
………………. 2 ………………….. 3 ………………….. 4 ………………….. 5………………….. 6…………………… . Servlet 1 Request object from container Servlet 2 Request/Response objects sent to servllet 2. Servlet 2 return s objects to calling servlet. Response object to container Include Request
377
Servlet calls other resources
Forwarding using Dispatcher object: Servlet1: 1. HttpSession session=request.getSession(true); ………..do something with request and response…………. 2. RequestDispatcher dispatcher= getServletContext().getRequestDispatcher(“/AnotherServlet”); dispatcher.forward(request, response); Servlet 2: After execution of line 3 servler AnotherServlet starts execution of its doGet or doPost method. It receives the request and response obejcts with whatever information has been encapsulated, does its tasks and proceeds to write into the proper streams using the response object.
378
Servlet calls other resources
Including using the Dispatcher object: Servlet1: 1. HttpSession session=request.getSession(true); ………..do something with request and response…………. Dispatcher dispatcher= getSevletContext().getRequestDispatcher(“/AnotherServlet”); dispatcher.include(request, response); 4. Other code Servlet 2: Servlet AnotherServlet receives the request and response objects after execution of line 3. Adds information to the response object and finishes its tasks. Servlet 1 captures the request and response objects returned from servlet 2at the eend of line 3 execution. It proceeds with line 4.
379
Servlet calls other resources
Another approach besides the usage of the Dispatcher object is to use the redirect command: response.sendRedirect(String name_of_resource); Sends a temporary redirect response to a client using the resource specified. The String passed in the argument can be a URL. A slash / in the URL means that the resource is relative to the servlet folder root (WEB_INF/classes). The response will be sent to the client by the redirected resource.
380
Servlet calls other resources
A chain of servlets can be formed: Request/ response Request/ response Request/ response response request Servlet 1 Servlet 2 Servlet 3 Servlet 4
381
Servlet calls other resources
Using Scope Objects Collaborating web components share information by means of objects that are maintained as attributes of four scope objects. You access these attributes using the [get|set]Attribute methods of the class representing the scope. Scope Objects Session Request Page
382
POST type of communication between an applet (or an application) and a servlet
Remember that: If POST is to be used then the client (an applet for example) has to place the data in the body of the HTTP packet. That means that the url approach where the parameters and their values are part of the url CAN NOT be used. It also means that the servlet must have implemented the doPost method.
383
Session Tracking with Cookies
Session tracking can be established with cookies. Cookies are files sent by the web server to the client and stored in the client’s system. The server reads the files every time contact is made and extracts information about the client. The Servlets Api can generate cookies via Cookie mycookie=new Cookie(cookiename, value); response.addCookie( mycookie ); Request.getCookies() receives an array of cookie sfrom client.
384
Information on Servlets
Further Information about Java Servlet Technology For more information on Java Servlet technology, see: Java Servlet 3.0 specification: The Java Servlet web site:
385
Study Guide WBAD TEXT: Chapter 8.
Java EE6 Tutorial- Part II Chapter 10. Read examples from course’ s web site and implement them on Tomcat.
386
George Koutsogiannakis/Summer 2011
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 10 George Koutsogiannakis/Summer 2011
387
Topics Java Server Pages. Distributed Objects.
Frameworks for Distributed Objects Architectures. Remote Method Invocation.
388
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.
389
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.
390
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
391
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” %>
392
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]; %>
393
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 %)
394
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.
395
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.
396
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.
397
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 #{ }
398
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>
399
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.
400
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>
401
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.
402
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.
403
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
404
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.
405
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.
406
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.
407
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.
408
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).
409
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
410
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.
411
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
412
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
413
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.
414
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.
415
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
416
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.
417
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 .
418
Remote Method Invocation (RMI)
HOW RMI WORKS Default port 1099 Client Server stub Remote object implementation Object registry Access to remote object requested by name. Reference is returned. Object ‘s method is invoked Remote object registers its name stub Messages Exchanged in RMI
419
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.
420
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.
421
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.
422
RMI Communications Client Server Communication Layers
Client Application Remote Reference (Session Layer) Stub (Presentation layer) RMIP (Transport Layer) Server Application Remote Reference (Session Layer) Stub (Presentation layer) RMIP (Transport Layer) TCP/IP (Network Layer) TCP/IP (Network Layer)
423
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.
424
Remote Method Invocation (RMI)
The following steps are needed in order to implement an RMI distributed application: Write the interface that defines the method(s) that can be invoked by the remote object. Compile it. 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) Write the client program and compile it. Place files as shown in the following diagram.
425
Remote Method Invocation (RMI)
Place files as shown. Client Node Server InterfaceFile.class ServerProgram.class stub ClientProgram.class InterfaceFile.class stub
426
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).
427
Remote Method Invocation (RMI)
SUMMARY OF TEMPERATURESERVER EXAMPLE: Weather forecast site Info from server retrieved whenever client wishes client Remote server Web server internet http rmi Aquire information from weather forecast site and store it Info is stored in an array of objects Info is downloaded when server program starts and gets repeated twice a day. Unicast (point-point) communications between objects via method calls. //host:port/RemoteObjectName
428
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() ; }
429
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.
430
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();)
431
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.
432
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.
433
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
434
Remote Method Invocation (RMI)
CLASSES USED: SERVER CLIENT TemperatureServer.class TemperatureServerImpl.class WeatherInfo.class TemperatureServerImpl_Stub.class TemperatureClient.class TemperatureServer.class TemperatureServerImpl_Stub.class WeatherInfo.class Where TemperatureServer.class is the interface
435
STUDY GUIDE WEB BASED APPLICATION DEVELOPMENT text Chapter 7
Read examples on RMI posted on the course’ s web site.
436
George Koutsogiannakis / Summer 2011
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 11 George Koutsogiannakis / Summer 2011
437
Topics REVIEW OF DEPLOYMENT ON TOMCAT RMI Callback RMI Over IIOP CORBA
JAVA MESSAGING SERVICES
438
REVIEW OF DEPLOYMENT ON TOMCAT
When your web application is ready for deployment, you need to package it for distribution. Archive the web application: jar cvf MyWebSite.war . (go to the directory where your folder MyWebSite exists, assuming that you develop the web site outside of Tomcat-- don't forget the dot at the end!) Deploy from Manager site of Tomcat. At the bottom of the manager site where it says "War File to Deploy" Browse to where your war file is located in your directory structure and then press deploy. A O.K. message and an entry onto thE list of deployed webapps means successful deployment. Test by calling the web application from a Browser instance.
439
RMI Callback In RMI Callback:
The client acts as a client needing the services of an RMI server. It also provides and registers a remote object for a service that it provides to the server (thus acting as a server itself). The server has a remote service registered that the client can invoke. In addition, as part of its response to the client, when its service is invoked, the server can ask the client to invoke the client’s remote service and send a response back to the server.
440
RMI Callback Client with a remote Service node Server node
stub Remote object implementation Object registry Access to remote object requested by name. Reference is returned. Object ‘s method is invoked Object registry stub Remote object implementation Client with a remote Service node Server node
441
RMI Callback -sequence of communications
Server node registers a remote object for its service. Client node registers a remote object for its service. Client contacts registry and asks for server’ s remote object’ s refernce. Registry responds to client with the reference Client sends a message to server invoking the service. Server prepares the message packets with required data from the execution of the service (if any). In addition as part of the response to the client, the server contacts the registry and ask’s for a reference to the remote object that represents the client’ s service. The registry responds with the reference to the server. The server asks the client for the invocation of its service. Therefore both the data from the execution of the server’s service an d the request for the client to execute its service for the server are sent out as part of the response to step 5. The client receives the data that it requested and also executes its service to satisfy the server’s request. The client sends any data to the server in its response to the server’s request.
442
RMI Callback Example code:
Server registers a Payroll service (where Payroll is the name of the interface): String ro = "//localhost/money"; PayrollImpl p = new PayrollImpl(); Naming.rebind(ro, p); Where statement 1 is the name of the object to be registered (money). Statement 2 is the server object. Statement 3 is the registration of the object “money” with the registry.
443
RMI Callback Payroll service has a method called earnings implemented: by the server public double earnings (int id, double hours) This method receives an int and a double data types from the client when it makes a request to the server to invoke earnings. It returns a double as part of the response to the client (the data). Inside the code for earnings method we generate the data to be returned as a double to the client. In addition, the code to invoke the service PayrollMessage (that is the interface on the client side) on the client side is included:
444
RMI Callback PayrollMessage pm = (PayrollMessage) Naming.lookup("rmi://localhost:1099/message"); pm.message("I am ready to sent the payroll amount"); This code is the look up to the registry to create a reference for a remote object called message. The reference is captured with object pm. Therefore we assume that the client has an interface called PayrollMessage and a remote name called “message” registered with the registry. Next the server (from within earnings) invokes the client’s service called message: Message does not return any data to the server (return is void).
445
RMI Callback The client can send a request to invoke the service Payroll (method earnings) as follows: Payroll p = (Payroll)Naming.lookup("rmi://localhost:1099/money"); double m = p.earnings(id,d); where id is an int type In statement 1 the client does a lookup on the registry requesting a reference to remote object money that represents the server’s service. In statement 2 the client uses the reference it received (which is the object p) to invoke the server’ s method called earnings. It passes to the method an int and a double data type. Successful response from the server is captured by the variable m (double type as expected from the method earnings)
446
RMI Callback The client has also implemented the service PayrollMessage that has method : public void message(String str) Notice that message returns void as pointed out in slide 7. A response is sent anyway to the server (verifying that the method was executed) but no data is returned. SEE CALLBACK EXAMPLE ON THE COURSE’ S WEB SITE FOR DETAILED CODE
447
RMI Callback Client Server
Notice that the distribution of the files are shown below: Client Server Client application program Client’ s interface: PayrollMessage Client’s stub Server ‘s stub Server’s interface: Payroll Server application program Server’ s interface: Payroll Server’s stub Client ‘s stub Client’s interface: PayrollMessage
448
RMI Over IIOP The RMI over IIOP Framework allows communication between Java applications and Non Java applications. It generates automatically IDL (Interface Definition Language) code that acts as the intermediary data types between the client and the server applications (even if both are written in Java). It frees the developer from having to know another language (IDL) It is slower, in general, than a similar RMI implementation.
449
RMI Over IIOP RMI Over IIOP IDL usage: Client Client request-
Client application could be Java Java Data Types are converted to IDL data types and sent to server IDL Data Types are converted to server’ s language data types Server executes its service and returns any data Client Server’ s language Data Types are converted to IDL data types IDL Data Types are converted to client ’ s language data types (Java)
450
RMI Over IIOP Sequence of communications remains the same as in RMI over IIOP. The registry, however, is different than the RMI registry and it called name server Start the Name server on a DOS window: > tnameserv –ORBInitialPort It starts on default port 900 (unless we want a different port to be created).
451
Communication Layers Slightly different than RMI’ s since the transport protocol is IIOP. Client Application ORB – Object Request Broker (Session Layer) Stub (Presentation layer) IIOP (Transport Layer) Server Application Tie (Presentation layer) IIOP (Transport Layer) ORB – Object Request Broker (Session Layer) TCP/IP TCP/IP
452
Communication Layers IIOP is part of the GIOP protocol defined in CORBA. GIOP defines various transport protocols working over various network protocols. The ORB is a layer that can be implemented by various vendors. Sun ha sits own implementation in RMI over IIOP. RMI over IIOP is of particular interest to Enterprise Java Beans since the remote object model for EJBs is based on the RMI over IIOP model. The server class has to extend PortableRemoteObject. That inheritance sets up the IIOP protocol as the transport protocol. In IIOP each client request gets its own thread. Notice that a stub and a tie file is produced when the server program is compiled with a special compiler
453
Communication Layers When a client processes a lookup on the name server, it receives from the name server a IOR (Inter Operable Object Reference). The ORB layer receives the IOR adds something called Tagged Profile and sets up the TCP connection with the server. It then marshals the invocation to the server. The ORB is also responsible for generating the Context Information (i.e. the data types to be transformed etc.) The transport protocol creates the IDL.
454
Differences Between RMI and RMI over IIOP
CODING DIFFERENCES: RMI INTERFACE: import java.rmi.Remote; import java.rmi.RemoteException; public interface Payroll extends Remote { public double earnings (int id, double hours) throws RemoteException; } RMI OVER IIOP INTERFACE: THEREFORE NO DIFFRENCE!!
455
Differences Between RMI and RMI over IIOP
RMI SERVER IMPORT STATEMENTS: import java.rmi.*; import java.rmi.server.*; RMI OVER IIOP IMPORT STATEMENTS: import javax.naming.InitialContext; import javax.naming.Context; import javax.naming.NamingException; import javax.rmi.PortableRemoteObject; RMI SERVER: public class PayrollImpl extends UnicastRemoteObject implements Payroll { RMI OVER IIOP SERVER: public class PayrollImpl extends PortableRemoteObject implements Payroll
456
Differences Between RMI and RMI over IIOP
RMI REGISTRATION OF REMOTE OBJECT: String ro = "//localhost/money"; PayrollImpl p = new PayrollImpl(); Naming.rebind(ro, p); RMI OVER IIOP REGISTRATION OF REMOTE OBJECT: String ro = "money"; Context initialNamingContext=new InitialContext(); initialNamingContext.rebind(ro, p); RMI CLIENT IMPORT STATEMENTS: import java.rmi.*; import java.rmi.registry.*;
457
Differences Between RMI and RMI over IIOP
RMI OVER IIOP IMPORT STATEMENTS: import java.rmi.RemoteException; import java.rmi.NotBoundException; import javax.rmi.*; import javax.naming.NamingException; import javax.naming.InitialContext; import javax.naming.Context; RMI CLIENT REGISTRY LOOKUP: Payroll p = (Payroll)Naming.lookup("rmi://localhost:1099/money"); RMI OVER IIOP CLIENT REGISTRY LOOKUP: Context ic = new InitialContext(); Object objref = ic.lookup("money"); Payroll p= (Payroll) PortableRemoteObject.narrow(objref,Payroll.class);
458
Differences Between RMI and RMI over IIOP
RMI CLIENT INVOCATION OF REMOTE SERVICE: double m = p.earnings(id,d); RMI OVER IIOP CLIENT INVOCATION OF REMOTE SERVICE: double m = p.earnings(id,d);
459
Differences Between RMI and RMI over IIOP
COMPILATION RMI COMPILE INTERFACE: >javac Payroll.java RMI OVER IIOP COMPILE INTERFACE: RMI COMPILE SERVER: >javac PayrollImpl.java >rmic –v1.2 PayrollImpl RMI OVER IIOP COMPILE SERVER: >rmic –iiop PayrollImpl RMI COMPILE CLIENT >javac PayrollClient,java RMI OVER IIOP COMPILE CLIENT: >javac PayrollClient
460
Differences Between RMI and RMI over IIOP
EXECUTION DIFFERENCES: RMI START REGISTRY: ON ITS OWN DOS WINDOW: >rmiregistry RMI OVER IIOP REGISTRY: ON ITS OWN DOD WINDOW: >tnameserv –ORBInitialPort RMI START THE SERVER: >java PayrollImpl RMI OVER IIOP START THE SERVER java -Djava.naming.factory.initial = com.sun.jndi.cosnaming.CNCtxFactory Djava.naming.provider.url=iiop://localhost:900 PayrollImpl //Assumes that the naming service was started at default port 900.
461
Differences Between RMI and RMI over IIOP
RMI START CLIENT: >java PayrollClient RMI OVER IIOP START CLIENT: java -Djava.naming.factory.initial = com.sun.jndi.cosnaming.CNCtxFactory -Djava.naming.provider.url=iiop://localhost:900 PayrollClient
462
Placement Of Files IIOP SERVER: Payroll.class ( the interface file)
PayrollImpl.class (the server file) _PayrollImpl_Tie.class (tie file) IIOP CLIENT: PayrollClient.class (client application) Payroll.class ( the interface file) PayrollImpl_stub.class (the stub file).
463
Placement Of Files Notice that in case of Callback from the server to the client additional files are needed: The client acts a server also. Therefore it will have to be compiled with the iiop version of rmic compiler to generate a stub and a tie file for the client as if it were a server. IIOP SERVER: Payroll.class ( the interface file) PayrollImpl.class (the server file) _PayrollImpl_Tie.class (tie file of server) PayrollMessage.class (the interface file of the client) PayrollImplClient_stub.class (the stub class of the client)
464
Placement Of Files IIOP CLIENT:
PayrollClientImpl.class (client application) Payroll.class ( the interface file) PayrollImpl_stub.class (the stub file of the server). PayrollMessage.class (the interface file of the client) PayrollClientImpl_Tie.class (the tie file of the client)
465
Placement Of Files A SIMILAR ARRANGEMENT OF FILES IS REQUIRED IF THE CALLBACK TECHIQUE WAS USED WITH A RMI ARCHITECTURE. THE CLIENT IS ALSO A SERVER AND THEREFORE IT GENERATES ITS OWN STUB AND INTERFACE FILES WHICH HAVE TO BE COPIED ON THE SERVER SIDE.
466
CORBA CORBA is a specification. Vendors can implement it.
CORBA stands for Common Object Request Broker Architecture. It is also used for creating a distribute dsystem of nodes that offer services. Java has an implementation of CORBA as part of the Standard Edition of the jdk (The API is called Java IDL)
467
CORBA Using CORBA is more complex than RMI or RMI over IIOP.
It requires the knowledge of another language called IDL (Interface Definition Language) IDL acts as the intermediary between services in various nodes, written in different languages.
468
COMPARING CORBA TO RMI AND RMI OVER IIOP
Keep in mind that in the case of RMI over IIOP IDL interfaces are generated automatically by the compiler (the programmer does not need IDL to use RMI over IIOP). Also, in both RMI and RMI over IIOP Java’ s serialization protocol is used automatically to serialize objects that need to be part of the request/response packets. Serialization may have to be externalize din CORBA (created).
469
COMPARING CORBA TO RMI AND RMI OVER IIOP
Network connections are done by the RMI or RMI over IIOP Frameworks (run time systems). In CORBA explicit programming for the sockets is needed. The big advantage of CORBA is that CORBA objects can interoperate with objects on other platforms. Thus A Java client can work with a C++ server and vice versa for example.
470
COMPARING CORBA TO RMI AND RMI OVER IIOP
RMI only allows Java to Java communications (both the client and the server have to be written in Java) RMI over IIOP allows interoperability between different languages for the Client and the Server because of the IIOP transport protocol included in RMI over IIOP IIPO stands for Inter Operable Internet Protocol Object
471
CORBA AND IDL The first step in developing a CORBA application is to define the interfaces to the objects required in your distributed system. To define these interfaces, you use CORBA IDL. You can implement IDL interfaces using any programming language for which an IDL mapping is available. Java has specifications that specify a IDL to Java and A Java to IDL data types translation.
472
CORBA AND ORB
473
CORBA and ORB In distributed computing, an object request broker (ORB) is a piece of middleware software that allows programmers to make program calls from one computer to another via a network. ORBs promote interoperability of distributed object systems because they enable users to build systems by piecing together objects- from different vendors- that communicate with each other via the ORB.
474
CORBA and ORB
475
CORBA and ORB Object Services -- These are domain-independent interfaces that are used by many distributed object programs. For example, a service providing for the discovery of other available services is almost always necessary regardless of the application domain.
476
CORBA and ORB Common Facilities -- Like Object Service interfaces, these interfaces are also horizontally-oriented, but unlike Object Services they are oriented towards end-user applications. An example of such a facility is the Distributed Document Component Facility (DDCF), a compound document Common Facility based on OpenDoc. DDCF allows for the presentation and interchange of objects based on a document model, for example, facilitating the linking of a spreadsheet object into a report document.
477
CORBA and ORB Domain Interfaces -- These interfaces fill roles similar to Object Services and Common Facilities but are oriented towards specific application domains. For example, one of the first OMG RFPs issued for Domain Interfaces is for Product Data Management (PDM) Enablers for the manufacturing domain. Other OMG RFPs will soon be issued in the telecommunications, medical, and financial domains.
478
CORBA and ORB Application Interfaces - These are interfaces developed specifically for a given application. Because they are application-specific, and because the OMG does not develop applications (only specifications), these interfaces are not standardized. However, if over time it appears that certain broadly useful services emerge out of a particular application domain, they might become candidates for future OMG standardization.
479
CORBA and ORB
480
Study Guide Read RMI over IIOP examples from the course’s web site.
481
George Koutsogiannakis/ Summer 2011
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 12 George Koutsogiannakis/ Summer 2011
482
Topics Servlets used as RMI Client.
RMI Security needed for Servlet to RMI server Communications.
483
Servlet as RMI client The Servlet will implement the doGet or doPost method as normally. Within the method (doGet or doPost): You need to catch Exceprion (create try/catch) Do a lookup on the registry: ReverseInterface r= (ReverseInterface) Naming.lookup ("//localhost:1099/Reverse");
484
Servlet as RMI client Where we assume that:
The server has registered a remote object for its instance called “Reverse”. The server’s Remote Interface that defines its service is ReverseInterface. The registry is at port 1099. Then go ahead and do the remote invocation and capture the output (still within try block): String str=r.reverseString(qr);
485
Servlet as RMI client Where r is the reference received from the registry The argument in the remote method is the data type that the method accepts (i.e qr is of String data type in the example). The returned value from the server is captured by variable str (assuming that the remote method returns a String data type in this example).
486
Servlet as RMI client Process the captured data by the servlet using the proper stream and the response object: PrintWriter out=response.getWriter(); out.println(str); out.close();
487
RMI server. Create RMI server as it is done normally.
import java.rmi.Remote; import java.rmi.RemoteException; public interface ReverseInterface extends Remote { String reverseString(String originalstring) throws RemoteException; } IN THE SERVER ReserveInterfaceImpl: public static void main(String[] args){ String name="//localhost/Reverse"; try { ReverseInterfaceImpl r= new ReverseInterfaceImpl(); Naming.rebind(name, r); etc……………
488
RMI server. IMPLEMENT THE REMOTE METHOD (SERVICE)
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();
489
SET UP OF THE APPLICATION
Create the applications web site outside of Tomcat (NEVER DEVELOP THE APPLICATION INSIDE TOMCAT). Do NOT Include the required files for the RMI server in the application’s deployment. Place all RMI client related files in the same directory as the servlet. Deploy using a WAR file approach. Remember that with the servlet you will need the stub from the server and a copy of the interface file also.
490
SET UP OF THE APPLICATION
You will need the certificate applied like you did in the assignment 1 with respect to a signed applet We assume that the servlet uses an applet as a client!! You may need a policy file like (optional): grant { permission java.security.AllPermission; };
491
SET UP OF THE APPLICATION
To allow communications between the Web Server (the servlet acting as RMI client) and the RMI Server: Modify the java.policy file in the System’s security directory (jdk installation) as follows: // allows anyone to listen on un-privileged ports permission java.net.SocketPermission "localhost: ", "connect, accept, listen, resolve";
492
Servlet as RMI Over IIOP Client.
In either the doGet or doPost method: We will need a Hashtable structure to place the call to registry as a name/value attributes 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"); We assume that the IIOP Naming Service is listening at port 900.
493
Servlet as RMI Over IIOP Client
In try block contact the Naming Service (IIOP registry): Context initialNamingContext=new InitialContext(env); out.println("obtained InitialContext"); r=(ReverseInterface)PortableRemoteObject.narrow(initialNamingContext.lookup("Reverse"), ReverseInterface.class); Now do the remote invocation using the reference r received from the Naming Service String str=r. reverseString(qr); WHERE reverseString is the remote method defined in the Interface created by the Server.
494
Servlet as RMI Over IIOP Client
Process the data captured by using the proper stream with the response object.
495
RMI Over IIOP Server Need additional import statements:
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;
496
RMI Over IIOP Server Registration in try block in main method:
public class ReverseInterfaceImpl extends PortableRemoteObject implements ReverseInterface Registration in try block in main method: ReverseInterfaceImpl r= new ReverseInterfaceImpl(); //add the follwoing lines Context initialNamingContext=new InitialContext(); System.out.println("Binding server to registry.."); initialNamingContext.rebind("Reverse", r); System.out.println("Object was registered"); Implement the remote method.
497
SET UP OF THE APPLICATION
Set up is similar to RMI description in previous files. Compiling should be as described in the RMI over IIOP presentation (lecture 11).
498
RMI SECURITY RMI has its own Security Manager.
Automatic downloading of stub files and interface file by the client is strictly cntrolled by security. Secured Class Loaded java.policy file java.security file Security Policy controlled by RMISecurityManager object
499
RMI SECURITY RMISecurityManager creates a sandbox similar to what the applets have to encounter. Default RMISecurityManager uses the default java.policy and java.security system files. We can create our own RMISecurityManager and remove some of the restrictions. We can also change for demonstration reasons some of the restrictions by modifying the java.policy and java.security files and let the default RMISecurityManager object operate.
500
Study Guide See examples posted on the course’ s web site
ServletRMI.zip and ServletRMIoverIIOP.zip
501
George Koutsogiannakis/Summer 2011
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 13 George Koutsogiannakis/Summer 2011
502
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
503
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).
504
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.
505
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
506
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 Browser
507
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.
508
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: 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.
509
Example of Applet and Servlet Communications
You can now test it by: Opening a Browser instance and typing:
510
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>
511
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;
512
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); }
513
Example of Applet and Servlet Communications
class MyPanel extends JPanel { public MyPanel() submitbutton=new JButton("Submit"); add(submitbutton); }
514
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(" /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");
515
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");
516
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(); }
517
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.
518
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
519
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.
520
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
521
Example: ServletLoginApplet web application
Next, start an instance of the Browser and type:
522
Example: ServletLoginApplet web application
Applet streams (POST HTTP request) URL url=new URL(" 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.close();
523
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");
524
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);
525
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();
526
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; }
527
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(); }
528
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();
529
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!");
530
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.
531
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.
532
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.
533
Java Beans Bean B Bean A Bean C Bean C combines the functionality of Bean A and Bean B
534
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
535
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.
536
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.
537
Java Beans
538
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
539
Java Beans More information about Java Beans is provided in the Java Beans Specification available at:
540
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.
541
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 Windows platforms).
542
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
543
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: Neither of these tools is suitable for a production environment
544
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.
545
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.
546
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
547
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-tomcat _base\conf\tomcat-users.xml
548
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”.
549
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.
550
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.
551
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.
552
Study Guide Study slides.
Suggest that you experiment with Bean Builder tool. Download and start experimenting with Net Beans
553
George Koutsogiannakis/ Summer 2011
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 14 George Koutsogiannakis/ Summer 2011
554
Topics Enterprise Java Beans (EJB) Definitions. Types of EJBs.
Application Servers/ EJB Servers. EJB Containers. EJB Application Example. Session Beans. Packaging Web Modules. Deploying Web Modules.
555
Enterprise Java Beans Creating a complete enterprise web application using the approach using discreet APIs is difficult (i.e using the servlets API, the RMI API, the JDBC API etc). It requires a lot of work using the fragmented technologies (servlets, RMI etc.) to implement: Session. Security. Administrative versus manager versus user Transaction management (database data). Dynamic content geared to various users.
556
Enterprise Java Beans All of the above issues can be:
Presentation layer components that are different for each user (dynamic presentation layer). Issues with deployment. Issues with distribution. All of the above issues can be: unified under one roof with Enterprise Java Beans bringing all technologies together. Easy implementation of various functionalities using one development environment (such as NetBeans). Easy deployment and distribution. Free developer from creating deployment descriptor file (i.e.web.xml and others needed).
557
Enterprise Java Beans An Enterprise Java Bean (EJB) is a server side component that encapsulates the business logic of an application. Or another definition is: An architecture for the development and deployment of transactional, distributed object applications based on server side software components EJB s run in the EJB container of an application server (such as the Sun Java System Application Server or GlassFish server of NetBeans). Therefore, in that respect, they are different than plain Java Beans. Java Beans can be self sustained components that can be run outside a container. The EJB container provides certain services such as security, transactions and other services. The container therefore is similar to the concept of a container for servlets in a web server. A container is housed inside a Component Transaction Monitor (CMT). CMT is part of the Application Server (i.e. GlassFish).
558
Enterprise Java Beans EJB s are used to create distributed business objects. As such they handle: Persistence (saving of the state of the business object) Security. Concurrency. Transaction Management. EJB s should run on any Operating System (at least theoretically although in practice it may not be 100% correct). EJBs are reusable , scalable, can be deployed on any Application Server. EJBs are part of J2EE and supported by package: javax.ejb
559
Enterprise Java Beans Advantages of EJB s:
Developer can concentrate on solving business problems since a number of the services are offered by the container. The client is independent of the business logic and the developer for the client can concentrate on presentation only. Thinner clients can be developed. A new EJB can be constructed from existing EJBs . They can be distributed amongst a number of machines (locality independent). Thus, scalability can be achieved. Remote clients can locate EJBs ( a similar task that an RMI client has when it does a look up on the Naming Service to get information about a remote object)
560
Enterprise Java Beans Organizations can build their own EJB components or purchase components from a third party. Development of an EJB component is based on a specification. Vendors of EJB servers use a common platform in designing the servers thus ensuring portability amongst different servers.
561
Enterprise Java Beans Types of EJB s are: Entity Beans Session Beans
They model: products, customers, data. They have a persistent state. They have been replaced with the Java Persistence API entities in EE 6 (they exist in previous versions, prior to EE5). Session Beans They model: processes, coordinate the activities of EJBs Do not have a persistent state. Message Driven Beans ( these beans require usage of Java Message Service API – JMS).
562
Enterprise Java Beans Enterprise JavaBeans technology supports both transient and persistent objects. A transient object is called a session bean, and a persistent object is called an entity bean.
563
Enterprise Java Beans A session bean exists NORMALLY only for the duration of a single client/server session. A session bean CAN perform operations such as accessing a database or CAN perform calculations. Session beans can be transactional, but normally are not recoverable following a system crash. Session beans can be stateless, or they can maintain conversational state across methods and transactions. A session bean must manage its own persistent data.
564
Enterprise Java Beans An entity bean is an object representation of persistent data maintained in a permanent data store, such as a database. An entity object can manage its own persistence (called Bean Managed Persistence -BMP) or it can delegate its persistence to its container (called Container Managed Persistence- CMP).
565
Enterprise Java Beans Types of Entity Beans: Entity Beans
Entity Beans that implement container managed persistence Entity Beans that implement bean managed persistence These beans are defined Independent of the database that they use These beans use explicit SQL statements relating to the database they use
566
Enterprise Java Beans Types of session beans: Session Beans
Stateful Session Beans: Specific to a client. Maintain information about the client. Stateless Session Beans: Any client can use them
567
Application Server Services
The Application Server provides (such as GlassFish in NetBeans): Persistence service. Ability to save the data (state) after execution. Transaction processing service. Ability to execute a group of operations atomically. Concurrency Control. Simultaneous execution of a number of requests. Events using Java Message Service API (JMS). Ability to send messages to other components. Naming and Directory service. Security via JCE and JAAS APIs. Deployment of components. Remote Procedure calls using RMI or RMI over IIOP Exposure of business logic components to web services. XML messages over SOAP protocol. A Deployment Descriptor in XML describes the EJBs residing in the server
568
EJB SERVERS AN EJB SERVER (combination of web server and Application Server) USUALLY CONSISTS OF: A WEB CONTAINER: IT HANDLES THE EXECUTION OF SERVLETS AND JSP COMPONENTS (LIKE TOMCAT). EJB CONTAINER (APPLICATION SERVER PART): IT HANDLES THE EXECUTION ENVIRONMENT OF THE EJBS APPLICATION CLIENT CONTAINER: HANDLES THE EXECUTION OF CLIENT COMPONENTS. PROVIDES SERVICES TO A CLIENT APPLICATION: PERSISTENCE SECURITY WEB SERVICES CLIENT SIDE SERVICES APPLET CONTAINER: PROVIDES RUN TIME ENIVIRONMENT FOR APPLETS (BROWSER, JAVA PLUG-IN). DATABASE SERVER: PROVIDES A DATABASE. NOTE THAT THE ABOVE CAN VARY FROM VENDOR TO VENDOR (SOME ARE ALL INCLUSIVE OR PARTS OF THE ABOVE)
569
EJB SERVERS SOME AVAILABLE EJB SERVERS ARE (PURE JAVA SERVERS):
SUN JAVA SYSTEM APPLICATION SERVER PLATFORM EDITION 9 –OPEN SOURCE (SJSAS-9) –NOW CALLED: Sun GlassFish Enterprise Server APATCHE GERONIMO- AN EXTENSION OF APATCHE TOMCAT WEB SERVER TO PROVIDE EJB EXECUTION ENVIRONMENT- OPEN SOURCE JBoss – OPEN SOURCE JFox- OPEN SOURCE EASY BEANS- OPEN SOURCE OpenEJB – OPEN SOURCE WebLogic EJB Server- NOT FREE (VENDOR: ORACLE/BEA) IBM WEBSPHERE – NOT FREE (VENDOR:IBM)
570
EJB SERVERS To choose the EJB application server that is right for your project, you'll need to take a variety of issues into account, such as: Level of support for J2EE technologies (Java JDK, Servlets, JSP, JNDI, and EJB) Support for all (critical) platforms used within your organization Ability to deploy and integrate into your existing technical environment, particularly support for JMX Development tool support Cost, including both initial and ongoing operational and support costs The market share of the vendor The long-term viability of the vendor The long-term viability of the product itself Availability of technical support from the vendor Availability of server source code (open source vs. closed source) Availability of developers (to your organization) experienced with the product Availability of training and mentoring services Availability of books, Internet newsgroups, and so on Consider starting with a free EJB server such as GlassFish.
571
EJB Containers Application Server Instance of container
Containers provide the run time environment for EJBs within the Application Server. They act as an intermediary between the EJB and the Application Server Application Server Instance of container Instance of container EJB #1 EJB #2 EJB #3
572
EJB Containers Services provided by the container are:
Activation and deactivation of EJB. Caching the state of an Entity Bean. Committing and rolling back transactions ( a group of SQL statements). Maintains a pool of EJB instances ready for incoming requests. Ensures that threading conditions within the Bean are satisfied. Synchronizes data between an Entity Bean and persistent storage (the database).
573
EJB Containers CONTAINER EJB CLIENT REQUEST
TRANSACTION MANAGEMENT SERVICES PROVIDED DURING RUNTIME PERSISTENCE SECURITY CLIENT REQUEST EJB CONTEXT BEAN INTERACTIONS WITH THE CONTAINER EJB JNDI CALLBACKS EJB CONTEXT: CAN GET A REFERENCE TO THE CONTAINER METHODS SO THAT THE BEAN CAN INTERACT WITH THE CONTAINER JNDI: ALLOWS ACCESS BY THE BEAN TO OTHER RESOURCES LIKE JDBC CONNECTIONS, OTHER BEANS, PROPERTIES SPECIFIC TO THE BEAN CALLBACKS: THE CONTAINER USES CALLBACKS TO INFORM THE BEAN OF VARIOUS EVENTS.
574
EJB Containers MOST CONTAINERS USE THE RMI OR COBRA OR RMI OVER IIOP PROTOCOLS. THE PREVIOUS SLIDE THEN SHOWS THAT THE EJB CONTAINER PROVIDES: Beginning, committing, and rolling back transactions as necessary. Maintaining pools of enterprise bean instances ready for incoming requests and moving these instances between the inactive pools and an active state, ensuring that threading conditions within the bean are satisfied. Most importantly, automatically synchronizing data in an entity bean's instance variables with corresponding data items stored in persistent storage. Note: Persistent Storage refers to the saving of data in a database
575
EJB Containers For each enterprise bean, the container is responsible for : registering the object, providing a remote interface for the object, creating and destroying object instances, checking security for the object, managing the active state for the object, and coordinating distributed transactions. Optionally, the container can also manage all persistent data within the object.
576
Example EJB Architecture
EIS Tier ------Middle Tier----- DB1 Entity Bean Session Bean Client HTML or Applet Web Server Servlet DB2 Entity Bean JSP Beans are located in Distributed Application Servers Internet Client Tier (Presentation Layer) Web Tier WHERE WEB MODULES ARE DEPLOYED Business Logic Tier Data Tier
577
Deploying The Enterprise Application
The next slide shows how the previous architecture can be deployed. Notice that we have combined and renamed the tiers as: Client tier Middle Tier Enterprise Information System (EIS) tier (it has the existing applications, files, and databases). Notice that the EIS tier can be accessed by a client in a number of different ways!!
578
Deploying The Enterprise Application
579
APIs Supported by the Servers
The following application program interfaces (APIs) are available for J2EE client applications, web servers, and EJB servers: JMS: The Java Message Service is the API for sending and receiving messages via enterprise messaging systems like IBM MQ Series and TIBCO Rendezvous. JAAS: The Java Authentication and Authorization Service is used to authenticate and authorize access controls on users. JAXP: The Java API for XML Parsing provides support for the industry standard SAX and DOM APIs for parsing XML documents, as well as support for XSLT transform engines. JDBC: The JDBC API is for accessing databases from Java using a call-level interface. SQLJ: The SQLJ API is for accessing databases from Java using embedded SQL. JDO: The JDO API is for accessing databases from Java using a transparent persistence interface.
580
APIs Supported by the Servers
The following APIs are not available for J2EE client applications, but are available for J2EE web servers and EJB servers: JTA: The Java Transactions API is the API for managing and coordinating transactions across heterogeneous systems. JavaMail: This is the API for sending and receiving . JAF: JavaMail uses the JavaBeans Activation Framework. Connectors: These connect to non-J2EE system
581
More on Session Beans In a stateful session bean the instance variables values of the object that represents the bean are saved for the duration that the bean is alive (the client’ s session). When client removes the session the state is lost. The client makes invocations on the methods of the bean which can change the state. The new state is saved during the time that the bean is waiting for a new invocation. Another name for the state of a stateful bean is “conversation state”. Dedicated to a specific client A stateless bean does not retain the state. It gives up the state as soon as the method (of the bean) that has been invoked terminates. Can support many clients
582
More on Session Beans Three types of a client access to a session bean: Remote access The session bean offers location transparency to the client. It can be run by the same JVM as the client or by a different JVM. The client can be a servlet ( a web component) or a java application or another EJB. The client accesses the bean via interfaces that define methods that define the client’ s view of the bean. @Remote public interface MyAccount{ public void deposit(double d); public double withdraw(double w); } public class BankAccount implements MyAccount{ ……….. }
583
More on Session Beans Local access:
Client must run in same JVM as the bean. Client can be a web component (i.e. servlet ) or another bean. Location of the bean is not transparent to the client. It is the default access type if the access type is not specified in the interface. @Local public interface MyInterface {…….. } public class MyBean implements MyInterface {…………. }
584
More on Session Beans Web Service access
This kind of access is devoted to clients which are web services. The web services clients do not have to be written in Java. It is beyond the scope of this course!
585
More on Session Beans To Develop a Session Bean the following files are needed: Enterprise Bean class: This is the class that implements the methods of the interface. Business Interface: Defines the business methods that the client can invoke. Helper classes: Any other classes needed by the bean. The files must be packaged in a EJB jar file. Note: An EJB application consists of a number of EJB jar files that are assembled into an EAR (Enterprise Archive) file. THE EAR COMBINES THE EJB JAR FILES AND THE WEB MODULE JAR FILES (WEB TIER FILES LIKE SERVLETS/JSP)
586
Life Cycle of a Session Bean
Stateful Session Bean: Does Not Exist state – Client brings it to Ready state by getting a reference of the bean. Ready State--- Client can invoke its business methods. Passive State---- Container can place the bean in the passive state which means that it transfers the bean to secondary storage. Container can bring the bean back to Ready state if the client invokes one of its methods. Stateless Session Bean: Does Not Exist Ready Message Driven Bean: Similar to Stateless Session Bean states
587
Packaging WEB MODULES A WEB APPLICATION CAN BE BUILT USING AN ENVIRONMENT LIKE NETBEANS OR IT CAN BE DEVELOPED MANUALLY. IT COULD BE DEVELOPED OUTSIDE NETBEANS AND IMPORTED INTO NETBEANS OR IT CAN BE TREATED INDEPENDENT OF NETBEANS A WAR FILE IS NEEDED TO PACKAGE THE WEB APPLICATION (SIMILAR TO THE WAR FILE IN TOMCAT). THE WAR FILE CAN BE CREATED WITH NETBEANS DURING THE BUILD PROCESS OR IT CAN BE CREATED MANUALLY BY USING THE ANT TOOL (PART OF THE SUN JAVA SYSTEM APPLICATION SERVER-9) OR BY MANUALLY USING THE JAR COMMANDS.
588
Deploying WEB MODULES YOU NEED A DEPLOYMENT DESCRIPTOR (SIMILAR TO web.xml in Tomcat) THE DEPLOYMENT DESCRIPTOR IN THE APPLICATION SERVER IS CALLED: sun-web.xml THE DEPLOYMENT DESCRIPTOR CONTAINS CONFIGURATION INFORMATION INCLUDING THE NAME OF THE CONTEXT ROOT OF YOUR APPLICATION. THE FILE sun-web.xml RESIDES IN THE WEB-INF FOLDER OF YOUR ROOT CONTEXT (NOT ANY DIFFERENT THAN TOMCAT) IT CAN BE CREATED AND EDITED IN NETBEANS OR MANUALLY. DEPLOYMENT CAN BE ACCOMPLISHED EITHER VIA NETBEANS OR BY USING THE ADMINISTRATIVE CONSOLE OF THE JAVA APPLICATION SERVER OR BY USING THE ANT TOOL OF THE JAVA APPLICATION SERVER ONCE THE APPLICATION IS DEPLOYED IT CAN BE VIEWED BY A BROWSER (IF THE BEAN HAS A WEB CLIENT).
589
Glass Fish Glass Fish is a combination of web modules environment and application server for EJBs It takes the place of the Java System Application Server Platform 9 (it includes it) now called GlassFish It is part of NetBeans. Provides centralized monitoring and management, Clustering for scalability and availability. It is part of the Sun GlassFish Portfolio open Web application platform that combines open-source software and support in a single package. It includes a web server (DO NOT START TOMCAT IF GLASSFISH IS THE SERVER USED).
590
Glass Fish Both Web Modules and EJB Modules can be developed using NetBeans They get deployed in GlassFish (or earlier versions of it like Java System Application Server Platform 9). You need to register a local instance of GlassFish / Sun Java System Application Server with the NetBeans IDE. The GlassFish application server is bundled with the NetBeans IDE. If you installed the application server as an option when you installed the NetBeans IDE, the server should already be registered with the IDE.
591
Administration of Glass Fish
Sun GlassFish Enterprise Server administration includes many tasks such as deploying applications, creating and configuring domains, server instances and resources, controlling (starting and stopping) domains and server instances, managing profiles and clusters, monitoring and managing performance, and diagnosing and troubleshooting problems.
592
Administration of Glass Fish
Administration of Glass Fish can be accomplished via one of the following methods: Admin Console Command-line Interface (asadmin Utility) JConsole
593
Administration of Glass Fish
Admin Console The Admin Console is a browser-based tool that features an easy-to-navigate interface and online help. The administration server (also called the Domain Administration Server or DAS) must be running to use the Admin Console. To launch the Administration Console, you must know the administration server hostname and port number. When the Enterprise Server was installed, you chose a port number for the server, or used the default port of You also specified a user name and master password. To start the Admin Console, in a web browser type: i.e
594
Administration of Glass Fish
The installation program creates the default administrative domain (named domain1) with the default port number 4848, as well as an instance separate from the domain administration server (DAS). After installation, additional administration domains can be created. Each domain has its own domain administration server, which has a unique port number. When specifying the URL for the Admin Console, be sure to use the port number for the domain to be administered.
595
Administration of Glass Fish
Command-line Interface (asadmin Utility)- Primarily for UNIX/Linux Systems. The asadmin utility is a command-line interface for the Sun GlassFish Enterprise Server. Use the asadmin utility and the commands associated with it to perform the same set of administrative tasks offered by the Admin Console. To start the asadmin utility, go to the as-install/bin directory and enter: $ ./asadmin To list the commands available within asadmin: asadmin> help It is also possible to issue an asadmin command at the shell’s command prompt: $ asadmin help To view a command’s syntax and examples, type help followed by the command name. For example: asadmin> help create-jdbc-resource
596
Administration of Glass Fish
JConsole JConsole is used to monitor the Sun GlassFish Enterprise Server. You can use either the JConsole remote tab, or the advanced tab to connect to the Enterprise Server. Remote Tab: identify the username, password, administration server host, and JMS port number (8686 by default), and select Connect. Advanced Tab: identify the JMXServiceURL as service:jmx:rmi:///jndi/rmi://host:jms-port/jmxrmi and select Connect. The JMXServerURL is printed in the server.log file as well as output in the command window of the domain creation command.
597
Glass Fish Domains The Enterprise Server consists of one or more domains. A domain is an administrative boundary or context. Each domain has an administration server (also called Domain Administration Server or DAS) associated with it and consists of zero or more standalone instances and/or clusters. Each cluster has one or more homogeneous server instances. A server instance is a single Java Virtual Machine (JVM) that runs the Application Server on a single physical machine. Server instances (whether standalone or clustered) in a domain can run on different physical hosts.
598
Glass Fish Domains A domain is a group of instances that are administered together. An application server instance can belong to just one domain. In addition to the administration boundary, a domain provides /facilitates: the basic security structure whereby different administrators can administer specific groups (domains) of application server instances. by grouping the server instances into separate domains, different organizations and administrators can share a single Enterprise Server installation. each domain has its own configuration, log files, and application deployment areas that are independent of other domains. If the configuration is changed for one domain, the configurations of other domains are not affected.
599
Glass Fish Domains The Sun GlassFish Enterprise Server installer creates the default administrative domain (named domain1). It also creates an associated domain administration server (named server). You must provide the administration server port number. The default administration server port is The installer also queries for the administration username and master password. After installation, additional administration domains can be created. Each domain has its own Domain Administration Server (DAS) with a unique port number. The Admin Console communicates with a specific DAS to administer the associated domain. Each Admin Console session allows you to configure and manage the specific domain.
600
Glass Fish Domains The DAS authenticates the administrator,
accepts requests from administration tools, and communicates with server instances in the domain to carry out the requests. The DAS is sometimes referred to as the admin server or default server. It is referred to as the default server because it is the only server instance that gets created on Sun GlassFish Enterprise Server installation and can be used for deployments. The DAS is simply a server instance with additional administration capabilities. Each Admin Console session allows you to configure and manage a single domain. If you created multiple domains, you must start an additional Admin Console session to manage the other domains. When specifying the URL for the Admin Console, be sure to use the port number of the DAS associated with the domain to be administered.
601
Glass Fish Domains Every administrative domain is associated with a usage profile, which identifies the capabilities of that domain. Enterprise Server provides the following profiles: Developer Cluster (A cluster is a named collection of server instances sharing the same set of applications, resources, and configuration information) Enterprise Note: Use Developer or Enterprise for your work in this course. Note: Security settings vary between profiles.
602
Glass Fish Domains In a development environment you can use different application server instances to test different Enterprise Server configurations, or to compare and test different application deployments. Because you can easily add or delete an application server instance, you can use them to create temporary sandbox area for experimentation purposes.
603
Client’s Ports Remote clients of enterprise beans (EJB components) access the beans through the IIOP listener. The IIOP port for the remote clients is : 3700 (default) Secured IIOP post is :3820 HTTP Port is : 8080 (unless there is a conflict) Secured HTTP port is:8181 Java Message Services Port: 7676
604
STUDY GUIDE Review Chapters 1 and 2 of Java EE 6 Tutorial
Java EE 6 Tutorial- chapters 14,15,16
605
George Koutsogiannakis SUMMER 2011
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 15 George Koutsogiannakis SUMMER 2011
606
Topics NetBeans the JDK and other settings.
Instances of the server. Domains. Using NetBeans to create a Session Bean. Opening an existing project. Creating an empty new project. Example of converter project.
607
NetBeans the JDK and other settings
Have uniformity in your installation. Mixing versions of NetBeans / JDK and Other tools can cause problems. Best configuration: JDK 1.6 with EE capability (install before NetBeans). JDK 6 Update 12 or higher with Java EE from Gets installed in C:\Sun\SDK\ It includes all the libraries needed
608
NetBeans the JDK and other settings
NetBeans 6.5 with GlassFish v2 as a minimum. Download All option or as a minimum Java SE Java Web and EE and The bundled Servers.
609
NetBeans the JDK and other settings
You can add or remove packs later using the IDE's Plugin Manager (Tools | Plugins). Java 6 or Java 5 is required for installing and running the PHP, Ruby and C/C++ NetBeans Bundles. You can download the latest Java at java.com. JDK 6 or JDK 5 is required for installing and running the Java SE, JavaFX, Java and All NetBeans Bundles. You can download standalone JDK or download the latest JDK with NetBeans IDE Java SE bundle.
610
NetBeans the JDK and other settings
After download and during installation: Direct NetBeans to use \Sun\SDK\jdk as the default jdk (JDK 6 with update 12 and higher). Other JDK platforms can also be added if you wish, as additions to default jdk. Make sure that in the Services window of NetBeans you add the servers: GlassFish V2 or and V3 Tomcat 6.x You can start the servers from there by right clicking on the server ‘s name.
611
NetBeans and the JDK and other settings
Install Tomcat 6.x and add it as a server under services in NetBeans. Servers that exist can be added from Tools-> server and click on Add Server in the open Dialog. Make sure that servers do not have conflicting ports. Most likely you would have to change Tomcat ‘s default port from 8080 to another port like The shut down port for Tomcat would also need to be changed: Services Highlight the server ‘s name. Right click and click on Properties. Change the port numbers on the opened dialog pane.
612
NetBeans and the JDK and other settings
Avoid activating GlassFish V3 which an application server associated with a new OOP Language called JRuby. Another configuration is: Download the All choice which does not include the JDK. Use the JDK installation from previous configuration.
613
NetBeans and the JDK and other settings
Every project created in NetBeans must have an instance of the application server GlassFish registered. When you open an existing project a message comes up warning you that an instance of the server needs to be registered (if one does not exist). You can right click on the projects name and choose: “Resolve Missing Server Problem” Notice that in this case you will have to be aware of the path in your System where the application server is located. Note that in most cases the registration of an instance will be done automatically and you will not have to do the above. A default instance is created under Domain “domain1”.
614
NetBeans and the JDK and other settings
Another approach is to start the proper server after activating NetBeans. Under Services right click on the server name and click start. Wait few seconds until the server is up and running. Verify that the server is running : If the server is not running there will be a message at the bottom pane of the screen. If the server is running the stop and restart menu option will be active and the start option inactive.
615
NetBeans Domains. A Domain is a process that encompasses a unique application’s modules. It is an instance of the application server. It isolates one application from another. No direct communication is allowed between domains without marshalling a remote object. Each domain has the port number of the server The port number of the administration server including User Name and password for administering the server. Security settings.
616
Server’s log You can get some idea of cause of failures that result in the server not starting by examining the log file of the server under <server installation>domains/domain1/logs/server file. Log files are also accessible for the administrative console of the server. To access the administrative console as a web application Right click on the server name and choose View Admin Console A password for the domain you established during installation, is required.
617
NetBeans and the JDK and other settings
The next slide shows the NetBeans window with On the left : the 2 basic windows Projects and Services . Other windows can be added (or closed) from the Windows menu on top. In the center usually we have the editor window where the code of a module will appear. On right we have the Properties window which displays properties of the focused module.
618
NetBeans and the JDK and other settings
On the bottom we have the output window which will display: Information on the building process Information on the deployment process Any output when you run the deployed project
621
Session Beans Session Bean can be called by:
Remote Application Client or By Web Client (JSP , Servlet). By another Bean component.
622
Session Beans Basic steps: Develop the code for the Bean
Interface with business methods definitions Class that implements the interface. Develop code for the Client Application (if there is one) Develop code for a web client (if there is one).
623
Session Beans-Open an existing Project
Save your files in some path of your choice within your system. From the File menu of NetBeans use Open Project to bring the files in (this is provided that your files were configured as a project). The symbol for the overall project is a blue triangle. You need to notify NetBeans that this project is the main project under focus right now (because multiple projects can be there). The main project is the project that contains the application’ s main class. Go to the menu “Run” and select “Set Main Project”-> choose your project’s name.
624
Session Beans-Open an existing Project
Compile the files by right clicking on the name of each module and choosing build. Using NetBeans or ant tool build the application client files (if there is an application client) into a jar file. Using NetBeans or ant tool build the web client (if there is a web client) into a war file. Using NetBeans or ant tool build the ejb into a jar file.
625
Session Beans-Open an existing Project
Instead of the individual builds listed above , you can build the entire project by right clicking on the project’ s name and choosing the build option. If you do that do not build each application separately again. That will cause you a problem.
626
Session Beans Once the project has been built, it needs to be deployed. Make sure that Tomcat is running (if it is only a web project) or if you are using GlassFish: You can start GlassFish v2 manually or it should start automatically as part of the deployment. Notice that the building process can fail for various reasons as well as deployment. Failure to deploy could be because of a number of reasons including:
627
Session Beans Port conflicts between the various servers.
Incorrect server configuration. Invalid JDK libraries (libraries that are needed but don’t exist because of incorrect jdk libraries being used by NetBeans. This can be corrected by changing the default jdk libraries for the project. Right click on the name of the project and choose Properties. In the opened dialog pane highlight “libraries” and then find the path to the proper jdk libraries. From the combo box choose the proper java platform. Other reasons –check NetBeans documentation or help menu.
629
Create a New Project Before we provide any coding (either manually or by having NetBeans produce the code) we need to create a project: Choose File-> New Project from Menu Bar Select Enterprise Application from Java EE category , click Next. Type a name for your project. Deselect Use Dedicated Folder option if selected. Click Next
630
Create a New Project Set the server to GlassFish and set Java EE version to EE5 or EE6. Select Create EJB Module and Create Application Client Module (if we are creating an application module). Click Finish
631
Creating a Session Bean
We can create a session bean by using NetBean utilities or by writing the code ourselves or by a combination of the two. Example of a Session Bean projects are part of NetBeans IDE. Let us look at the converter project example from the JAVA EE 6 TUTORIAL text. This ejb application of the converter project provides the services for the conversion of dollars to to yen and yento Euro It has a client application that communicates with the ejb. It also has a web application that communicates with the ejb in the form of jsp code. What is needed programmatically is:
632
Creating a Session Bean
The interface that defines the methods to be implemented by the ejb. The class that implements the methods of the interface. The client application that can invoke directly the methods of the ejb (dollar to yen and yen to Euro conversions). The web application that can invoke the methods of the ejb via the web from a browser. A jsp file resides in a web server. The file creates an html form that gets transferred to a browser instance. The user can enter amounts that can be converted. Note : the client application and the web aplication are independent of each other.
633
Converter Bean Example
Client Java Application for ConverterBean ConverterBean runs on the Application Server part of GlassFish Html generated by Web Client Runs on Browser Web Client for ConverterBean runs on Web Server part of GlassFish
634
Client Application package converter.client;
import converter.ejb.Converter; import java.math.BigDecimal; import javax.ejb.EJB; public class ConverterClient { @EJB // ANNOTATION private static Converter converter; /** Creates a new instance of Client */ public ConverterClient(String[] args) { } /** args the command line arguments */ public static void main(String[] args) { ConverterClient client = new ConverterClient(args); client.doConversion();
635
Client Application public void doConversion() { try {
BigDecimal param = new BigDecimal("100.00"); BigDecimal yenAmount = converter.dollarToYen(param); // Above line is the invocation of the remote method implemented by the // //ejb component. The variable yenAmount captures the returned value of // the remote invocation System.out.println("$" + param + " is " + yenAmount + " Yen."); BigDecimal euroAmount = converter.yenToEuro(yenAmount); //another invocation involving the second remote method of the ejb System.out.println(yenAmount + " Yen is " + euroAmount + " Euro."); System.exit(0); } catch (Exception ex) { System.err.println("Caught an unexpected exception!"); ex.printStackTrace(); }
636
Remote Interface for the Session Bean
package converter.ejb; import java.math.BigDecimal; import javax.ejb.Remote; @Remote // ANNOTATION public interface Converter { public BigDecimal dollarToYen(BigDecimal dollars); public BigDecimal yenToEuro(BigDecimal yen); }
637
Session EJB Code package converter.ejb; import java.math.BigDecimal;
import javax.ejb.Stateless; @Stateless //ANNOTATION public class ConverterBean implements converter.ejb.Converter { private BigDecimal euroRate = new BigDecimal("0.0070"); private BigDecimal yenRate = new BigDecimal("112.58"); public BigDecimal dollarToYen(BigDecimal dollars) { BigDecimal result = dollars.multiply(yenRate); return result.setScale(2, BigDecimal.ROUND_UP); } public BigDecimal yenToEuro(BigDecimal yen) { BigDecimal result = yen.multiply(euroRate);
638
Web Client-JSP page import="converter.ejb.Converter, java.math.*, javax.naming.*"%> //directive tag <%! private Converter converter = null; public void jspInit() { try { InitialContext ic = new InitialContext(); //lookup converter = (Converter) ic.lookup(Converter.class.getName()); //lookup } catch (Exception ex) { System.out.println("Couldn't create converter bean."+ ex.getMessage()); } public void jspDestroy() { converter = null; %>
639
Web Client -JSP <html> <head>
<title>Converter</title> </head> <body bgcolor="white"> <h1>Converter</h1> <hr> <p>Enter an amount to convert:</p> <form method="get"> <input type="text" name="amount" size="25"> <br> <p> <input type="submit" value="Submit"> <input type="reset" value="Reset"> </form>
640
Web Client -JSP <% String amount = request.getParameter("amount");
if ( amount != null && amount.length() > 0 ) { BigDecimal d = new BigDecimal(amount); BigDecimal yenAmount = converter.dollarToYen(d); //invocation %> <p> <%= amount %> dollars are <%= yenAmount %> Yen. BigDecimal euroAmount = converter.yenToEuro(yenAmount); //invocation <%= yenAmount %> Yen are <%= euroAmount %> Euro. } </body> </html>
641
Session EJB You can import the files for the example projects from the CD In that cased use Open Project in NetBeans. Or you can create your own files and create a new project by following the previous instructions. Start the Server (i.e. GlassFish) Build the project. Deploy the project. Make sure that Tomcat and GlassFish v2 are running (without conflicts). Run the project.
643
Deployment Once a project is deployed:
Do not deploy again every time you activate NetBeans. It is deployed once and stays deployed even if you exit NetBeans and you open NetBeans later on. Once the project is deployed, to run the client application: Right click on the project name and choose run (as main project). The client output (if any) will appear at the bottom of the NetBeans console (under Output).
644
Convert Client Application Output
645
Converter project Web Application
To run the Web Application (Web Client for ejb): Open an instance of the browser and in the address field type: And press enter Notice that 8090 is an example port for the web server part of GlassFish. You must know the web server port for your installation of GlassFish.
646
Web Client for converter ejb
647
Deployment Issues If for some reason the deployment was unsuccessful you can try redeploying First undeploy any parts of the application that were deployed. Follow this procedure also if you want to make changes to the code and need to rebuild and redeploy Go to the GlassFish Administrative Console an log in.
648
Deployment Issues In the left side of the console click on Enterprise applications. In the screen that comes up choose the converter application and then click on undeploy button. Repeat the same for other parts of the application Web Application EJB Modules Application Client Modules.
649
NetBeans and support for Applets
NetBeans supports development of Applets. Create the Java project from scratch or from existing sources Choose File > New Project (Ctrl-Shift-N). Under Categories, select Java. Choose one of the following: If you are creating a new applet source file, select Java Class Library under Projects. Click Next. If you want to import an applet source file, select Java Project with Existing Sources. Click Next. Specify the file's location in the Source Packages Folder text box. Under Project Name, type HelloApplet. Change the Project Location to any folder on your computer. Click Finish. If you imported an applet source file, run it.
650
NetBeans and support for Applets
Create the applet source file Right-click the HelloApplet project node in the Projects window and select New > Other (Ctrl-N). Under Categories, select Java. Under File Types, select Applet. Alternatively, if you want to visually design your applet, select Swing GUI Forms > JApplet Form. If you want to import an applet source file, select Java Project with Existing Sources. Click Next. Specify the file's location in the Source Packages Folder text box.
651
NetBeans and support for Applets
Click Next. Under Class Name, type MyApplet. Under Package, type org.me.hello. Click Finish. The IDE creates the applet source file in the specified package. The applet source file opens in the Source editor. Define your applet class by copying and pasting the following code over the existing default code:
652
NetBeans and support for Applets
The IDE creates the basic applet code: public class HelloApplet extends JApplet { public static int() { } You can add methods and code as needed
653
NetBeans and support for Applets
The applet that you created can be run from the IDE. Right-click the HelloApplet project node in the Projects window and choose Build from the contextual menu. The HelloApplet.jar file is created in the dist folder, which you can see if you switch to the Files window . Right-click the applet class node (i.e., right-click "MyApplet.java" not the "HelloApplet" project) in the Projects window and choose Run File from the contextual menu. The MyApplet.html launcher file, with the applet embedded, is created in the build folder, which you can see if you switch to the Files window (Ctrl-2):
654
NetBeans and support for Applets
Your applet is complete. Now you need to make it available to the user by deploying it as a web application. To do so, you create a web application, put the applet JAR on its classpath, and then add an applet tag to the web application's HTML file. Create the web project Choose File > New Project. Under Categories, select Web. Under Projects, select Web Application. Click Next. Under Project Name, type HelloWebApplet. Change the Project Location to any folder on your computer. Click Next, select your server, and click Finish.
655
NetBeans and support for Applets
Add the applet JAR file to the web project When you want to include an applet JAR file in a web project, you can do so by adding the Java project that contains the JAR file, or by adding the JAR file itself. Although the choice is yours, note that when you add the Java project to the web project, you enable the IDE to build the applet whenever you build the web application. Therefore, when you modify the applet in the Java project, the IDE builds a new version of the applet whenever the web project is built. On the other hand, if the applet JAR file is not in a NetBeans IDE project, the applet source file is not rebuilt when you build the web project.
656
NetBeans and support for Applets
TO ADD THE APPLET PROJECT TO THE WEB APPLICATION: In the Projects window, right-click the HelloWebApplet project node and select Properties from the contextual menu. Choose one of the following: If the applet JAR file is in a Java project, click Packaging, and then click Add Project. Browse to and select the folder that contains the Java project. Note that IDE projects are marked by the NetBeans IDE project icon. If the applet JAR file is not in a IDE project, click Packaging, and then click Add JAR/Folder. Browse to and select the folder that contains the JAR file. The JAR file containing the applet source file is listed in a table at the bottom of the Project Properties dialog box.
657
NetBeans and support for Applets
Optionally, you can type a location for the applet in the table's Path in WAR column (in the Properties dialog box). By default, the applet JAR file will be copied to the web application's document root, which is the build/web folder (the highest level of the web application's file structure). Click OK. When you build the project, the applet's JAR file is packaged in the project's WAR file in the dist folder. It is also added to the build/web folder.
658
NetBeans and support for Applets
Create and run the JSP file or HTML file Choose one of the following: If you want to embed the applet in a JSP file, double-click the default index.jsp file in the Projects window. This file is created by the IDE when you create a web project. It opens in the Source Editor. If you want to embed the applet in an HTML file, right-click the HelloWebApplet project node, and choose New > Other from the contextual menu. Under Categories, select Web. Under File Types, select HTML. Click Next. Give your HTML file a name and click Finish. Embed the applet in the file by adding the following applet tag anywhere between the file's <body></body> tags: <applet code="org.me.hello.MyApplet" archive="HelloApplet.jar"/> org.me.hello.MyApplet is the full classname to your applet HelloApplet.jar is the JAR file that contains the applet
659
NetBeans and support for Applets
660
NetBeans and support for Applets
TO RUN THE WEB APPLICATION: Right-click the JSP node or HTML node in the Projects window and choose Run File from the contextual menu. The server deploys the JSP file or HTML file in the IDE's default browser.
661
Applet Servlet Web Application
Create the web application with the servlet first. Add the applet project to the web application’s project that contains the servlet by following the procedure outlined in previous slides.
662
Study Guide Chapters 14, 15, 16 of EE 6 Tutorial.
NetBeans documentation.
663
George Koutsogiannakis/SUMMER 2011
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 16 George Koutsogiannakis/SUMMER 2011
664
Topics Running an Applet in NetBeans
Implementing the LoginAppletNORMI example. A session EJB client with annotations. Annotations. Deployment Descriptors. A session EJB client that does lookup Lookup when the application has a single remote interface Lookup when multiple interfaces exist in the application. Rules for Multiple Interfaces.
665
Running an Applet in NetBeans
Let us create a project for the applet class which is part of the LoginAppletNORMI web application example posted on the course’ s web site. Create a project called Applet and browse to where the LoginApplet.java file is located to be included in the project.
666
Running an Applet in NetBeans
The IDE will automatically generate the LoginApplet.html file needed to launch the applet. To exclude the LoginApplet.html launcher file from the JAR file, right-click the project, choosing Properties, clicking Packaging, and adding an expression to exclude them.
667
Running an Applet in NetBeans
An applet can be tested by using the appletviewer from NetBeans. To run the applet with the appletviewer: Select the applet class file and right click. Choose Run File The file LoginApplet.html is created in the build folder and the appletviewer is launched. The LoginApplet screen appears. Notice that the exit button works. That is because a default policy file is created for the applet that gives it AllPermissions.
668
Running an Applet in NetBeans
Notice that the LoginApplet.html was created automatically when you Run the applet. You can view the files generated if you switch from the Projects window to Files Window. In the Files window you can also verify that the .jar file that contains the applet was generated under the dist folder The next slide shows the Files window with the Applet project expanded. You can edit the source code for the applet LoginApplet.java to make sure that the url contains the correct port for the server that you are going to use for the web application (either Tomcat or GlassFish).
670
Result of testing LoginApplet example
with “Run File” command.
671
Registering A Browser with NetBeans
By default, the IDE opens your system's default web browser. If necessary, you can specify a different browser in the Options window. To launch the web browser. Choose View > Web Browser from the main menu.
672
Setting Permissions for an Applet
By default, applets do not have access to resources on a client's computer, such as threads and disk operations. An applet's permissions are defined in its applet.policy file. If you have an applet policy file, you can specify its location in the IDE. Then, when you run the application, the IDE uses the applet policy file that you specified. If you do not specify an applet policy file, the IDE generates one for you when you run the applet. The applet policy file that the IDE generates for you grants all permissions to the applet. You can use the Source Editor to modify the policy file, so that appropriate security checks are done.
673
Setting Permissions for an Applet
You can view the policy file in the Files window by expanding the nbproject node. The default policy file has the name of the project i.e Applet.policy in our example. grant { permission java.security.AllPermission; }; You can edit the policy file to change the permissions to your desired permissions.
674
Creating the Web Application
If you create an applet as part of a Java WebStart-enabled project, you can run the applet by running the project. If your applet is not part of a WebStart-enabled project, the applet is not run as part of the project. To complete the LoginApplet example we need to: Create a web application that includes the servlet TestLoginServlet.java and Bring the Applet project that we created into the web application. We can then deploy the web application into either Tomcat or GlassFish as a web application.
675
Creating a Web Application Project
In the IDE, you create applications and modules in projects. The web application project is the project that you use to create web applications and web application modules (servlets and jsp source code files). To create a web application project: Choose File > New Project (Ctrl-Shift-N). From the Java Web category, select one of the following project templates:
676
Creating the Web Application
Creating the Web Application in a standard project or Web Application with Existing Sources. Imports an existing web application into a standard project. standard project A project that uses an IDE-generated Ant script to compile, run, and debug your application. The IDE comes with the following standard project templates: Java SE: Java Application, Java Class Library, Java Project with Existing Sources, Java Desktop Application Web: Web Application, Web Application with Existing Sources Java EE: Enterprise Application, Enterprise Application with Existing Sources Enterprise JavaBeans Modules: EJB Module, EJB Module with Existing Sources
677
Creating the Web Application
Web Application with Existing Sources. Imports an existing web application into a standard project. free-form project A project that uses an existing Ant script to compile, run, and debug your application. The IDE comes with the following free-form project templates: Java Free-Form Project Web Free-Form Project
678
Creating the Web Application
For our example we want to choose Web Application with Existing Sources because we have the source file for the servlet (from our LoginAppletNORMI example). Make sure that in your directory you have a folder named LoginAppletNORMI that contains the source code for the servlet. That is because you want your project to have the name of the web application as it appears in the url imbedded in the LoginApplet code.
680
Creating the Web Application
Next choose the server that the web application will be associated with. For example I chose the GlassFish server because I have already deployed the same application LoginApplet on Tomcat. In the Existing Sources and Libraries page, you specify the following properties: Web Pages Folder. Specifies the location of your web pages. You must have at least a valid web.xml deployment descriptor in the web pages folder to complete the wizard. The IDE does not convert deployment descriptors for unsupported application servers to the Glassfish application server deployment descriptors. There are external tools you can use for this purpose.
681
Creating the Web Application
WEB-INF Content. Specifies the location of the application's WEB-INF content. Libraries Folder. Specifies the location of the class libraries that the web application depends on. All JAR files in this folder are added to the web application project's classpath and packaged with the application for deployment. Make sure that the jdk assigne dto this project is not the defualt SE version but the SUN/jdk that includes EE (because servelts are not part of the SE). Next import trhe Applet project into the project LoginAppletNORMI. Deploy and run.
682
Clients/EJB Architecture
683
Summary Of Session Bean’s Functionality (from “Help Menu” of NetBeans)
A business method is a method inside an enterprise bean that performs some function and can be called from outside the bean. Business methods are written in the bean class and exposed through local or remote interfaces. If a business method is meant to be called by beans and clients that are running in the same JVM (on the same server), they are registered in the bean's local interface. If the method is meant to be called from a remote client, it is registered in the bean's remote interface. (Remember that if the bean client is a web application or an application client the bean’s interface is defined as remote, otherwise it is local).
684
Summary Of Session Bean’s Functionality
A session bean's business methods typically define tasks that the bean performs for clients. They are not necessarily associated with data in a database (Entities handle database access) .
685
Using an annotation in the Client.
In NetBeans Create a new project called EnterpriseAppEE5 Select Enterprise Java Application from the Java EE category and click Next. Set the server to GlasFish v2 Set the Java EE version to EE5 Select Create EJB Module Select Create Application Client Module Click Finish.
686
Using an annotation in the Client
Create the session bean: Expand the project on the Projects Window and right click on the folder EnterpriseAppEE5-ejb Choose New->Other In the opened wizard: From the Java EE category, select Session Bean and click Next. Type Session as the name Select Remote for the type of interface . Click finish You now have the source editor opened in the middle of your screen showing which shows the skeleton code for the class SessionBean
687
Using an annotation in the Client
Right click in the text editor by the name of the class and choose InsertCode-> Add Business Method In the Add Business Method diaolog box type getResult for the name of the method and set the return type to be a String. Also select Remote. Interface box. Click OK. In the text editor modify the returned String to return “This is a Session Bean” ; Save it. Under EnterpriseAppEE5-ejb you should be able to expand the folder Source Packages-ejb and see the files: SessionBean.java SessionRemote.java SessionLocal.java
688
Using an annotation in the Client
The first file is the session bean class that was just created . The other two files are the two type s of interfaces automatically created. Only the Remote type has a method (because we asked so) the other is empty. package ejb; import javax.ejb.Remote; /** * George */ @Remote public interface SessionRemote {String getResult(); }
689
Using an annotation in the Client
The code for the SessionBean class looks now like: package ejb; import javax.ejb.Stateless; /** * George */ @Stateless public class SessionBean implements SessionRemote, SessionLocal { public String getResult() { return "This is a session EJB "; }
690
Using an annotation in the Client
Now we can create the code for the client. In the Projects window expand EnterpiseAppEE5-app-client->Source Packages->enterpriseaappee5 The file Main.java appears in the text editor pane. In the text editor right click on the code and choose: Insert Code->Call Enterprise Bean In the dialog box that appers expand EnterpriseAppEE5-ejb node and select SessionBean (as the bean that you want to call from this client) Select Remote as the reference interface. Click OK. The following annotation is added to Main.java file; @EJB Private static SessionRemote sessionBean; Modify the main method manually to include the invocation of the bean: System.out.println(‘result of remote invocation=“+ sessionBean.getResult());
691
Using an annotation in the Client
@EJB is called an annotation. The symbol for annotation There are many types of annotations used in Java EE Annotations Replace descriptors for most purposes. Remove the need for marker interfaces (like java.rmi.Remote) Allow application settings to be visible in the component they affect. The Java EE 5 (and up) platform simplifies deployment by removing the need for explicit creation of deployment descriptors by the developer.
692
Using an annotation in the Client
In summary, the Java EE 5 (and up) platform provides annotations for the following tasks, among others: Defining and using web services Developing EJB software applications Mapping Java technology classes to XML Mapping Java technology classes to databases Mapping methods to operations Specifying external dependencies Specifying deployment information, including security attributes
693
Using an annotation in the Client
Therefore in this example we used an annotation to link the EJB to the client. We specified that the client is to connect to the specific bean. Notice also that this example was a single application that included the client and the bean together in the same project.
694
Running the Enterprise Application
Right click on the name of the application in the Projects window and choose Run. The IDE should build and deploy the project. On the output pane you should see: result=This is a session EJB
695
Annotations Annotations used in EE5 and up are described in package:
javax.annotation Annotation Types Summary : Generated:The Generated annotation is used to mark source code that has been generated. PostConstruct: The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. PreDestroy: The PreDestroy annotation is used on methods as a callback notification to signal that the instance is in the process of being removed by the container. Resource:The Resource annotation marks a resource that is needed by the application. Resources:This class is used to allow multiple resources declarations.
696
Deployment Descriptors- Help Menu of NetBeans
Deployment descriptors are XML-based text files whose elements describe how to assemble and deploy a module to a specific environment. The elements also contain behavioral information about components not included directly in code. Deployment descriptors specify two kinds of information: Structural information describes the different components of the JAR (or EAR) file, their relationship with each other, and their external dependencies. Environment entries and resource requirements are part of the structural information. Assembly information describes how contents of a JAR (or EAR) file can be composed into a deployable unit.
697
Deployment Descriptors- Help Menu of NetBeans
There are different types of deployment descriptors: EJB deployment descriptors described in the Enterprise JavaBeans specification, web deployment descriptors described in the Servlet specification, and application and application client deployment descriptors described in the Java EE specification. For each type of module or application, there are two deployment descriptors:
698
Deployment Descriptors- Help Menu of NetBeans
A general deployment descriptor that configures deployment settings on any Java EE-compliant implementation. The general deployment descriptor is named moduleType.xml (for example, ejb-jar.xml for EJB modules and web.xml for web application modules.) A server-specific deployment descriptor that configures deployment settings for a specific server implementation. For example, the deployment descriptors for the Sun Java System Application Server/GlassFish are named sun-moduleType.xml. The deployment descriptor for the Tomcat Web Server is named context.xml.
699
Deployment Descriptors- Help Menu of NetBeans
The IDE generates a deployment descriptor from the settings for EJB modules, web application modules, and enterprise applications, when you create an empty enterprise project. It also reads your existing deployment descriptors when you import existing enterprise beans, enterprise applications, and web applications into the IDE. The deployment descriptors are located in the conf folder of your project directory, and are displayed under the Configuration Files node in the Projects window.
700
Using Lookup Normally the client needs to do a lookup in the naming service to find the bean. In the next example we would create an application where the client uses lookup instead of annotation. The next example also uses two projects, one for the bean and one for the client (in the previous example both client and bean were part of the same project).
701
Create the EJB Module First create a new project and name it EJBModule30 This time the EJB module will not be part of an enterprise application, therefore select JavaEE and then EJB Module as the Java EE category when you create the project (in the previous project we selected Enterprise Application).
704
Create the Session Bean
We will create the Session Bean in the EJB Module. In the Projects window right click the EJB Module and choose New->Other Select Session Bean from the Enterprise Category. Click Next In the wizard that was opened type: EJB Name: Bean30, package: ejb, Session Type:Stateless Select Remote (the type of interface) Click Finish
706
Create the Session Bean
In the source editor: Right click and choose insert->Add Business Method In the Add Business Method dialog box type getResult for the name of the method Set the retuned type to String Select the Remote Interface box and click OK. Modify the code manually: public String getResult() { return “This is EJB 3.0 Bean”; } Modify annotation @Stateless(mappedName=“Bean30”) public class Bean30Bean implements Bean30Remote { The client will use Bean30 to look up for the Bean. This is similar to registering a name for a remote object in RMI.
707
Create the Session Bean
package ejb; import javax.ejb.Stateless; /** * George */ @Stateless(mappedName="Bean30") public class Bean30Bean implements Bean30Remote { public String getResult() { return "This is EJB 3.0"; } // Add business logic below. (Right-click in editor and choose // "Insert Code > Add Business Method" or "Web Service > Add Operation")
708
Create the Session Bean
Notice that the interface with the business rule (aka service or method) is automatically created by the tool and annotated as remote interface: package ejb; import javax.ejb.Remote @Remote public interface Bean30Remote { String getResult(); } The code for the interface can be found under the folder EJBModule30->Source Packages->ejb
709
Create Application Client
We now create a new project for the Application Client: This time select Enetrprise Application Client from the Enterprise category and name the project: ApplicationClientForTest We now want to add the EJBModule30 project to ApplicationCleintForTest project as a library and add the code to access Bean30(alias for our bean).
710
Adding Application Client Project to the Bean project
Expand ApplicationClientForTest project node (in Projects window). Right Click on Libraries node and select Add Project In the dialog box select EJBModule30 project and click Add Project Jar Files. You should be able to see now the EJBModule30.jar file as part of the Libraries for ApplicationClientForTest project. In the text editor open the Main.java. And add the code for lookup manually. Then click ctrl-shft-I and the proper import statements will be added.
711
Calling EJB from Client
package applicationclientfortest; import ejb.Bean30Remote; import javax.naming.InitialContext; public class Main { args the command line arguments */ public static void main(String[] args) throws NameingException { // TODO code application logic here try { IntialContext ctx=new InitialContext(); Bean30Remote br=(Bean30Remote)ctx.lookup("Bean30"); System.err.println("EJB message is:"+br.getResult()); } catch(NamingException ne){}
712
Build the applications
Build and deploy each of the projects: EJBModule30 ApplicationClientForTest Run the ApplicationClientForTest
713
JNDI JNDI (Java Naming Directory Interface) API provides a variety of services to Java Applications: Naming Service: The means by which names are associated with objects. Binding: The actual association of a name with an object. A pointer or a reference to the object is stored inside the Naming Service. A reference is information about how to access the remote object. Context: A set of name/object bindings. A context provides a lookup, otherwise known as “Resolution” , operation. The operation returns the information about the object. Context may also provide other operations for binding, unbinding, listing of stored names/objects bindings.
714
JNDI A hierarchical tree of bindings can be formed where one binding is bound to another binding and so on . The application component's naming environment is a mechanism that allows customization of the application component's business logic during deployment or assembly. Use of the application component's environment allows the application component to be customized without the need to access or change the application component's source code. A Java EE container implements the application component's environment, and provides it to the application component instance as a JNDI naming context.
715
JNDI Each application component defines its own set of environment entries. All instances of an application component within the same container share the same environment entries. Application component instances are not allowed to modify the environment at runtime. A resource reference is an element in a deployment descriptor that identifies the component’s coded name for the resource. In the previous example the EJB was identified by the name: “Bean30”. Environment settings appear in the descriptor files.
716
Multiple Interfaces Suppose that in the previous example we had a second interface like: @Remote public interface Bean30Remote2 { String getResult2(); }
717
Multiple Interface In the Bean30Bean.java we would need to implement both interfaces:
719
Multiple Interfaces-Modify Client
The client will need to be modified also: Double-click the main.java class of ApplicationClientForTest in the Projects window to open the class in the Source Editor. Modify the code in the main method to look up the second interface. In this case, when there is more than one remote interface, we have to use the full name for each of the interfaces in the lookup:
720
public static void main(String[] args) throws NamingException
{ InitialContext ctx = new InitialContext(); Bean30Remote br = (Bean30Remote) ctx.lookup("Bean30#ejb.Bean30Remote"); System.err.println("EJB message is:" + br.getResult()); Bean30Remote2 br2 = (Bean30Remote2) ctx.lookup("Bean30#ejb.Bean30Remote2"); System.err.println("EJB message 2 is:" + br2.getResult2()); } Fix the imports to add an import statement for ejb.Bean30Remote2. Save your changes. Build, Deploy and Run.
721
Rules for Multiple Interfaces
In case of Multiple interfaces the Interfaces must explicitly be annotated as Remote or Local (with a single interface we can omit the annotation and it will be assumed as Local).
722
Servlets NetBeans has some servlet applications examples that can be run. Choose New Project->Samples->Java Web->ServletExamples. Assign Tomcat as the server. Build, Deploy, Run
723
Cart Example The cart example in the text EE5 Tutorial (Chapter 22) is of significance for the following concepts: A Stateless bean can implement: The business methods defined in the interface. Additional Business Methods annotated (not listed in the interface). Optional Life Cycle Callback Methods. Additional Helper Classes implemented.
724
Study Guide Chapter 3 of Java EE 6 Tutorial.
Chapters 14,15,16 of Java EE Tutorial. Do examples under samples in new projects of NetBeans IDE.
725
George Koutsogiannakis/SUMMER 2011
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 17 George Koutsogiannakis/SUMMER 2011
726
Topics Persistence API for JAVA EE5 Java Transaction API Entity class.
Entity Relationships. Annotating Persistence. Persistent Fields. Persistent Properties. Primary Keys Customer example Composite Keys
727
EJBs Session Beans act as the intermediary between the client requests and the complexity of storing data or accessing data from a database. The storing and retrieval of data is handles by code attributed to the Java Persistence API (JPA). Up toEE5 there was another category of beans called: Entity Beans. Comparing EE concepts with the following discreet APIs architecture:
728
PRESENTATION TIER WEB TIER AND BUSINESS RULES TIER BROWSER
INTERNET CLIENT GUI BROWSER WEB SERVER Customer Accounts Servlet, Users Servlet, Updated Selections Servlet e.t.c, Applet, html files, images RMI SERVER /JDBC / JDBC DATA BASE PRESENTATION TIER WEB TIER AND BUSINESS RULES TIER DATA TIER
729
Architecture Using EE Client can stay the same.
Remove some of the functionality from servlets and incorporate it in a session bean. Session bean can handle all the invocations. Session bean receive the data from the JPA code and process it to the servlet(s). The RMI server code can be absorbed by the JPA code. The project can be build using NetBeans and be deployed on Tomcat and GlassFish v2. We will have a web client for the session bean EJB Session Bean code JPA code Database
730
Persistence API The Java Persistence API (JPA) was introduced as part of the Java EE 5 platform. Its goal is to facilitate data acquisition from relational databases without the complexity of numerous sql statements. The idea is to use an object oriented approach to data storage. Data is handled without the need to create deployment descriptors. Instead annotations are used which are read by the container.
731
Persistence API- Alternative implementations of JPA
An implementor of the JPA is called : Persistence Provider (i.e. NetBeansGlassFish). Some Concepts are explained and demonstrated using OpenJPA, an open source JPA implementation from Apache. OpenJPA has been integrated with the Weblogic, WebSphere, and Geronimo application servers. The current version of OpenJPA at the time of writing is 1.0.1 If you're going to use a different setup, obviously you'll need to check out the documentation first (although the approach is mostly the same in most servers). Note: Kodo was originally developed by SolarMetric, Inc in BEA Systems acquired SolarMetric in 2005, where Kodo was expanded to be an implementation of JPA (JSR 220)[2] specification. In 2006, BEA donated a large part of the Kodo source code to the Apache Software Foundation under the name OpenJPA.
732
Java Transaction API-JTA
The Java Transaction API (JTA) is part of the J2EE platform. The API gives you the ability to perform distributed transactions, that is, an application can use the API to perform transactions on more than one data store in the network at the same time. But to do this efficiently, it helps to have another component operating in the application server: a J2EE transaction manager. A transaction manager helps to efficiently schedule and execute the potentially large number of transactions coming in through the application server.
734
Java Transaction API The data source must be registered on the server and is specified using the JNDI name. Transactions can be: Container Managed Application Managed. If the transactions are container-managed JTA transactions, the data source must be a JTA data source. This is the preferred way! It must be specified in the decsriptor file persistence.xml
735
Java Transaction API If the transactions are application-managed, the data source is specified according to the JDBC database connection registered with the IDE . You use this approach if you are not deploying in a EE container (like GlassFish).
736
Persistence API-Entities
Entity A table in a database. An Entity is represented by a class Instance of entity corresponds to a row in the database. A number of rules cover the implementation of an entity class. Note: The database is sometimes referred as: Data Source or Data Store
737
Persistence API-Entity Relationships
Relationships are the same as relationships between tables in a database: One-To-One: Each instance of the entity (row) is related to single instance of another entity (to a single row of another table). One-To-Many: An entity instance can be related to more than one instance of another entity. But an instance of the other Entity can only relate to one instance of the first.
738
Persistence API-Entity Relationships
Many-To-One: Multiple instances (rows) of an Entity can be related to one instance of another Entity. But an instance of the other Entity can relate to only one instance of the first Entity. Many-To-Many: An instance of one Entity relates to many instances of another Entity and vice versa. For every relationship there is an owning side and inverse side. The relationship can be unidirectional –it has only an owning side. Or, bidirectional – it ha s both an owning side and an inverse side.
739
Example Relationships
Owner Authors Titles Inverse Many To Many bidirectional Inverse Owner Inverse One-To-Many Bidirectional One-To-Many Bidirectional Owner Publishers
740
Persistence API-Entity Class
The class has instance variables The class has accessor and mutator methods that follow the Java Beans convention for naming the methods. The persistent state can be accessed either through the instance variables or through the getter methods (accessors). Persistent Fields (if fields are mapped with annotations) Persistent Properties (if getter methods are mapped with annotations) This is done through annotations to one or the other but not both in a class.
741
Persistence API-Entity Class
The annotations are defined in javax.persistence, so you'll need to import that package. Annotations are handled by package javax.persistence Fields annotated with Transient are not persisted (saved). Annotations apply to other parts of the program i.e. The class needs to be annotated with annotation. The type of relationship needs to be annotated for example. Other annotations apply to different parts of the class.
742
Persistence API-Entity Class
Every Entity must have a unique primary key field that enables clients to locate instances (rows) of an Entit. Primary Keys can be: simple (consisting of a single field) or Composite (consting of one or moret persistent field)s and or properties) Composite primary keys are represented by a primary key class.
743
Persistence API-Entity Class
Entities support: Inheritance. An Entity class can inherit a non Entity class and a non Entity class can inherit an Entity class. The non Entity classes can have persistent states information (annotations on their fields or properties). If , however, the non Entity class is a super class, it has no persistent state as such. Polymorphism. You can have an abstract Entity class and subclasses of the abstract Entity class that implement parts of the abstract class in different ways each. Association (using another class by instantiating an object of that class).
744
Persistence API-Entity Inheritance Strategies
Single Table of the database per class hierarchical inheritance. A Table of the database per concrete Entity class. A “Join” strategy Fields/properties of a subclass are mapped to a different table than the super class.
745
Persistence API-Entity Management
There is an Entity Manager object represented by an instance of: javax.persistence.EntityManager Each manager object is associated with a persistent context (scope). Each manager object: Removes persistent entity instances. Finds Entities by using the primary key. Allows queries to be run on Entities.
746
Persistence API-Entity Management
An Entity Manager can be: Container-managed in which case it (persistence) propagates to all application components (EJBs) with a single Java Transaction Architecture (JTA) transaction via a special annotation. Application-managed in which case the persistence does not propagate to other applications (EJBs).
747
Persistence API-Persistence Units
Persistence Unit defines all Entity classes that are managed by EntityManager instances within an application. A name should be provided to describe the Persistence Unit in your application. A Persistence Unit is defined in the persistence.xml configuration file. Location of the file within the application in the server varies depending dependent on if the client is a client application or a web application. The IDE will place it in the proper directory.
748
Persistence API-Entity Class
Assume you have a CUSTOMER table, whose schema is represented by the table in the next slide.
749
Customer Table Example
NAME PK? TYPE NULL? CUST_ID Y INTEGER NOT NULL FIRST_NAME VARCHAR(50) LAST_NAME STREET APPT VARCHAR(20) CITY VARCHAR(25) ZIP_CODE VARCHAR(10) CUST_TYPE LAST_UPDATED_TIME TIMESTAMP
750
Customer Entity Class import javax.persistence.*;
import java.io.Serializable; import java.util.Date; @Entity(name = "CUSTOMER") //Name of the entity if name is different than the class ‘ name then us annotation. public class Customer implements Serializable { private long custId; private String firstName; private String lastName; private String street; private String appt; private String city; private String zipCode; private String custType; private Date updatedTime; // Getters and setters go here }
751
Customer Entity Class The Customer entity needs to know how to map the attributes (or properties) to the CUSTOMER table. Through JPA annotations. Let us use Field persistence:
752
Customer Entity Class import javax.persistence.*;
import java.io.Serializable; import java.util.Date; @Entity(name = "CUSTOMER") //Name of the entity public class Customer implements Serializable { @Id //signifies the primary key @Column(name = "CUST_ID", nullable = false) @GeneratedValue(strategy = GenerationType.AUTO) private long custId; // 3 annotations define the field custId as a primary key. signifies a strategy to assign a unique value to your identity fields automatically. //The types of strategies available are IDENTITY, SEQUENCE, TABLE, and AUTO.
753
Customer Entity Class @Column(name = "FIRST_NAME", nullable = false,length = 50) private String = "LAST_NAME", length = 50) private String lastName; // By default column name is same as attribute name private String = "APPT",nullable = false) private String appt; private String = "ZIP_CODE",nullable = false) // Name of the corresponding database column private String zipCode;
754
Customer Entity Class @Column(name = "CUST_TYPE", length = 10)
private String custType; @Version @Column(name = "LAST_UPDATED_TIME") private Date updatedTime; signifies a version field in an entity. JPA uses a version field to detect concurrent modifications to a data store record. When the JPA runtime detects multiple attempts to concurrently modify the same record, it throws an exception to the transaction attempting to commit last. This prevents you from overwriting the previous commit with stale data. // Getters and setters go here }
755
Customer Entity Class-xml file
An descriptor file called persistence.xml is needed to describe the persistence unit (database). <?xml version="1.0"?> <persistence> <persistence-unit name="testjpa" transaction- type="RESOURCE_LOCAL"> <provider> org.apache.openjpa.persistence.PersistenceProviderImpl </provider> <class>entity.Customer </class> <properties> <property name="openjpa.ConnectionURL" value="jdbc:derby://localhost:1527/D:\OpenJPA\Derby\MyCustomer;create=true"/>
756
Customer Entity Class-xml file
<property name="openjpa.ConnectionDriverName" value="org.apache.derby.jdbc.ClientDriver"/> <property name="openjpa.ConnectionUserName" value="admin"/> <property name="openjpa.ConnectionPassword" value="admin"/> <property name="openjpa.Log" value="SQL=TRACE"/> </properties> </persistence-unit> </persistence> Note: openjpa is proprietary to openSource version.
757
Customer Entity Class-xml file
Another version of the .xml file that will apply to GlassFish is: <persistence> <persistence-unit name= "testjpa“> <jta-data-source>jdbc/MyCustomer</jta-data-source> <jar-file>NameofJar.jar<jar-file> <class>path1.path2.Customer</class> </persistence-unit> The data source (data base uses JTA – Java Transaction API) Class describes the entity class (or classes if more than one)
758
Customer Entity Class-xml file
Notice that: persistence.xml can have multiple persistence units. Each unit can be used by different JPA vendor or can be used to persist to different databases. The vendor-specific persistence provider name is specified in the <provider> tag. The persistence provider for OpenJPA is org.apache.openjpa.persistence.PersistenceProviderImpl. The entity class names are specified in the <class> tag. The database connection properties can be specified within the <properties> tag. Note that the property name will differ for each vendor.
759
Customer Entity Class-xml file
In the openSource version of the persistence.xml the transaction was defined as an application managed transaction via : transaction-type="RESOURCE_LOCAL“ You can do the same in NetBeans if you want the application to manage the transaction. In the NetBeans version we indicated that the transaction was container managed. jdbc/MyCustomer was the name of the JTA data source (same name was used in the openSource version).
760
Customer Entity Class-A class that inserts a record
public static void main(String[] args) { EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("testjpa"); EntityManager em = entityManagerFactory.createEntityManager(); EntityTransaction userTransaction = em.getTransaction(); userTransaction.begin(); Customer customer = new Customer(); customer.setFirstName("Charles"); customer.setLastName("Dickens"); customer.setCustType("RETAIL");
761
Customer Entity Class-A class that inserts a record
customer.setStreet("10 Downing Street"); customer.setAppt("1"); customer.setCity("NewYork"); customer.setZipCode("12345"); em.persist(customer); userTransaction.commit(); em.close(); entityManagerFactory.close(); }
762
Customer Entity Class-A class that inserts a record
The work of the Persistence class is pretty simple: Persistence is a bootstrap class that is used to obtain an EntityManagerFactory In the classpath resources, the Persistence class searches for javax.persistence.spi.PersistenceProvider files in META-INF/services/directory. It reads the PersistenceProvider implementation class names from each file. It then calls createEntityManagerFactory() on each PersistenceProvider with the persistenceUnitName until it gets an EntityManagerFactory back that isn't null. The provider name for OpenJPA is org.apache.openjpa.persistence.PersistenceProviderImpl.
763
Customer Entity Class-A class that inserts a record
EntityManagerFactory is a factory for creating an EntityManager. EntityManagerFactory should be cached and should ideally be called once for each persistence unit name in the whole application. EntityManager manages entities; it is responsible for their addition, updating, and deletion. The transaction is committed when the transaction object userTransaction invokes comit.
764
Customer Entity Class-finding a record
Finding a record with a primary key is as simple as OpenJPAEntityManager oem = OpenJPAPersistence.cast(em); Object objId = oem.getObjectId(customer); Customer cust = em.find(Customer.class, objId); //where em is the EnityManager object //customer is the Customer object //Because the primary key is unknown up front, the application must cast EntityManager to OpenJPAEntityManager to get the primary key object by passing the customer object that was persisted earlier. This logic might differ for other vendors.
765
Customer Entity Class-finding a record
A more generic approach that can relate to GlassFish better is : @PersistenceContext EntityManager em; //instead of OpenJPAEntityManager public void findCustomer(int custID) { Customer cust=em.find(Customer.class, custID); …………………………
766
Customer Entity Class-A Composite Primary Key
Assume that the CUSTOMER table doesn't have a CUST_ID field, but that FIRST_NAME and LAST_NAME together make up the primary key. You need to create a separate class, generally called an identity class, with attributes the same as the IDs; then you reference the identity class in the entity class.
767
Customer Entity Class-A Composite Primary Key
public final class CustomerId implements serializable{ public String firstName; public String lastName; //default constructor //accessor/mutator methods // override equal() method //override hascode() method } The identity class can be a separate class or an inner class. If the class is an inner class, it must be static and should be referenced in the entity class.
768
Customer Entity Class-A Composite Primary Key
@IdClass(Customer.CustomerId.class) public class Customer implements Serializable{ @Id @Column(name = "FIRST_NAME", nullable = false, length = 50) private String firstName; @Column(name = "LAST_NAME", length = 50) private String lastName; private String lastName; @Column(name = "APPT",nullable = false) private String appt;
769
Customer Entity Class-A Composite Primary Key
The entity class is annotated with the annotation: @IdClass to specify the primary key class (identity class) in the entity class Another possible annotations is: @Embeddable Which will be used on the identity class.
770
Difference Between @IdClass and @Embeddable Annotations
Notice that when annotations is used the fields in the identity class match the fields in the entity class. is used as the annotation in the identity class class we have : @Embeddable public final class CustomerId implements serializable{ public String firstName; public String lastName; //accessor/mutator methods // override equal() method //override hascode() method }
771
Difference Between @IdClass and @Embeddable Annotations
The entity class does not have to be annotated instead: @Entity public class Customer implements Serializable{ CustomerId primaryKey; public Customer() {..} @EmbeddedId public CustomerId getPrimaryKey() { return primaryKey; } public void setPrimaryKey(CustomerId pk) { primaryKey = pk; …………………………………………………………… }
772
Study Guide Chapters 19, 20 of EE6 Tutorial.
773
George Koutsogiannakis/Spring 2011
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 18 George Koutsogiannakis/Spring 2011
774
Topics Registering a database with the IDE.
Creating a Derby Data Source. Create Tables with SQL scripting. Create Tables using a Dialog Box. Building a Persistence Unit with NetBeans. Web Tier Persistence. EJB Tier Persistence.
775
Databases NetBeans comes with Derby database (visible in the services window). New databases ( i.e. MySQL, Oracle etc) can be added but they need to register with the IDE. Once a database is registered, a data source or connection can be created or a connection to an existing data source can be opened. Once the data source is created a Persistence Unit can be created.
776
Java DB (Derby) The Java DB database is Sun's supported distribution of the open source Apache Derby database. Java DB is a fully transactional, secure, standards-based database server, written fully in the Java programming language, and fully supports SQL, JDBC API, and Java EE technology.
777
Java DB (Derby) The Java DB database server is bundled with the Sun Java System Application Server/Glassfish. If you install the Sun Java Application Server/GlassFish during the IDE installation, the Java DB database server is automatically registered in the IDE.
778
Registering A Data Source
First make sure that the proper drivers are registered with the IDE. In services window expand the database node and then expand the drivers node. Next, you need to register a connection to your data source:
779
Drivers
780
Sample databases Under Services you will see the Java DB node
You can right click on the name and choose start server to start the database server. Example of using Derby can be found in
781
Sample databases At least two sample databases are available
You can click on the node of the sample database:jdbc:derby//localhost:1527/sample[app on API] and expand it to see the tables of the database and their fields : Right click on the node and click on connect Then right click on a table’ s name and choose view data
782
Customer Table Fields Table Customer data Query
783
Registering A Data Source-Creating a connection
Right-click the Databases node and choose New Connection. Alternatively, expand the Drivers node, right-click your driver's instance node and choose Connect Using. Provide the JDBC database URL for the database connection in the Database URL field. This URL typically begins with jdbc:and a short code name for the driver, followed by another colon. The rest of the URL depends on the type of driver you are using. For example, you might need to specify a host and port; alternatively, the name of a database file might suffice, or an ODBC DSN. For MySQL, the Database URL might look as follows: jdbc:mysql://localhost:3306/mydatabase
784
Registering A Data Source-Creating a connection
Provide the user name and password, if required by your database configuration. Click OK to create the database connection and connect to the database from the IDE. To disconnect from the database: Right-click the database connection node and choose Disconnect.
785
Connecting to a database
After you create the database connection you can do the following: Disconnect and reconnect to the database Browse the database structure View data contained in a table in the database
786
Creating A Data Source A database needs to be registered with NetBeans. Notice that a number of data sources can be part of the domain of the application. Each database needs to be registered with a separate JNDI name. For example, a database name MyDatabase, specify jdbc/MyDatabase as the JNDI name.
787
Creating A Data Source Specify a table generation strategy for your database. Click Finish. When you click Finish, the file persistence.xml opens in the Source Editor. In the IDE, you can find persistence.xml in the Projects window under the Configuration Files node. In the Files window, persistence.xml is located in the src/conf directory. When packaged, persistence.xml is located in the META-INF directory of an EJB JAR file or the WEB-INF/classes directory of a WAR file
788
Creating A Derby Data Source
First of course the database needs to be created outside the IDE. In services window right click on databases and choose create database In the Create Java DB Database Window: Type a name for the database i.e MyTestDB Type a User Name i.e george Type a Password i.e george Click O.K. Two things will take place The DB server for Derby should be activated The new database name should appear under databases node in services window
790
Creating A Derby Data Source
Right-click the MyTestDB node and choose Connect. If the Connect dialog box appears, type the password that you have set for the database server. If the Advanced tab of the dialog box opens, click OK to close the dialog box. --> Scroll down to the node for connection that you have just created. The node should have the icon. Right-click the connection node and choose Execute Command. In the editor part of the IDE type the SQL script to create the tables of the database : A sample script is given on the next slides:
791
Creating A Derby Data Source
CREATE TABLE WEB_BOOKSTORE_BOOKS (bookId VARCHAR(8), surname VARCHAR(24), firstName VARCHAR(24), title VARCHAR(96), price FLOAT, onSale SMALLINT, calendar_year INT, description VARCHAR(30), inventory INT) PRIMARY KEY (bookId) );
792
Creating A Derby Data Source
INSERT INTO WEB_BOOKSTORE_BOOKS VALUES('201', 'Duke', '', 'My Early Years: Growing up on *7', 30.75, 0, 1995, 'What a cool book.', 20); INSERT INTO WEB_BOOKSTORE_BOOKS VALUES('202', 'Jeeves', '', 'Web Servers for Fun and Profit', 40.75, 1, 2000, 'What a cool book.', 20); INSERT INTO WEB_BOOKSTORE_BOOKS VALUES('203', 'Masterson', 'Webster', 'Web Components for Web Developers', 27.75, 0, 2000, 'What a cool book.', 20);
793
Creating A Derby Data Source
INSERT INTO WEB_BOOKSTORE_BOOKS VALUES('205', 'Novation', 'Kevin', 'From Oak to Java: The Revolution of a Language', 10.75, 1, 1998, 'What a cool book.', 20); INSERT INTO WEB_BOOKSTORE_BOOKS VALUES('206', 'Gosling', 'James', 'Java Intermediate Bytecodes', 30.95, 1, 2000, 'What a cool book.', 20); INSERT INTO WEB_BOOKSTORE_BOOKS VALUES('207', 'Thrilled', 'Ben', 'The Green Project: Programming for Consumer Devices', 30.00, 1, 1998, 'What a cool book', 20);
794
Creating A Derby Data Source
INSERT INTO WEB_BOOKSTORE_BOOKS VALUES('208', 'Tru', 'Itzal', 'Duke: A Biography of the Java Evangelist', 45.00, 0, 2001, 'What a cool book.', 20);
796
Creating A Derby Data Source
Next we need to run the script: Click the Run SQL button () in the toolbar of the Source Editor to run the script. Output of the script should appear in the Output window. Right-click the connection node of the database and choose refresh. Expand the node, and expand its Tables subnode. You should see the database tables created. In the properties window you should have a view of the properties of the table.
798
Creating A Derby Data Source
The data sources are located in C:\Documents and Settings\George\.netbeans-derby on my machine. You can discover the location of your Derby data sources by right clicking on JavaDB (services window) and choosing properties. By default, the IDE creates the database in the .netbeans-derby folder of your home directory. To change the default location, click Properties in the Create Java DB Database dialog box, or in the Services window, right-click the Java DB node and choose Properties. Type the new database location in the appropriate field.
799
View Table Data To view Table data expand the Data Source node
Expand the Tables node Right click on the name of the Table and choose view data. The Table data can be viewed as in the next slide:
801
Using the Create Table Dialog
We can create a Table via a dialog box without having to write the SQL statements: This dialog box appears when you right-click a database's Tables node in the Services window and choose Create Table. Using this dialog box, you can create a table, add columns, specify parameters for columns, and select an owner for the table. The Create Table dialog opens. In the Table name text field, type the name of the Table In the first row displayed, select the Key check box. You are specifying the primary key for your table. All tables found in relational databases must contain a primary key.
802
Using the Create Table Dialog
Note that when you select the Key check box, the Index and Unique check boxes are also automatically selected and the Null check box is deselected. This is because primary keys are used to identify a unique row in the database, and by default form the table index. Because all rows need to be identified, primary keys cannot contain a Null value. For Column Name, enter id for example. For Data Type, choose SMALLINT for example from the drop-down list, then click the Add Column button. Keep repeating the procedure adding columns and their data types. Check. When the check box is selected, the IDE performs a check of the column to determine if it meets the required criteria.
803
Web Client for a Data Source
We can create a simple web client that communicates with The Database Server where the Data Source is deployed (Derby) .
804
Web Client for a Data Source
Data that is shared between web components and is persistent between invocations of a web application is usually maintained by a database. Web components use the Java Persistence API (JPA) to access relational databases.
805
Persistence Unit A Persistence Unit is a collection of entities (data tables) that are managed together. A Persistence Unit specifies some or all of: Persistence provider name i.e. xmlsn=“ Persistence Unit name i.e. name=OnlineStore Entity class names i.e. org.com.Orders Database connection URL Driver User and password The type of Entity Manager Object Other properties of a data source.
806
Persistence Unit The information about the Persistence Unit is kept in the descriptor file persistence.xml An Entity Manager object needs to be created that will manage the persistence unit created.
807
Persistence.xml <persistence> <persistence-unit name="OrderManagement"> <description>This unit manages orders and customers. It does not rely on any vendor-specific features and can therefore be deployed to any persistence provider. </description> <jta-data-source>jdbc/MyOrderDB</jta-data-source> <jar-file>MyOrderApp.jar</jar-file> <class>com.widgets.Order</class> <class>com.widgets.Customer</class> </persistence-unit> </persistence>
808
Building a Persistence Unit with NetBeans
Let us create a new project in NetBeans. Under categories choose Enterprise Application. Allow for ejb and web applications inside the Enterprise Application. Let us name the project ExampleEnterpiseApplication Follow the steps in the next slide to create a persistence unit within either the web application or the ejb application of the Enterprise Application project.
809
Building a Persistence Unit with NetBeans
To create a persistence unit (from NetBeans IDE): In the Projects window, right-click a web or EJB module project node and choose New > Other. Select Persistence Unit in the Persistence category and click Next. Specify a unique Persistence Unit Name. In most cases you can keep the default name suggested by the IDE. Select a persistence provider or library from the drop-down menu, or add a new library by choosing New Persistence Library. Notice that a number of choice providers are shown including CODO (openSource JPA).
810
Building a Persistence Unit with NetBeans
Select a data source from the drop-down menu. The data source can be a JDBC connection or a database connection. To appear in the list, the data source needs to be registered with the IDE. Select Use Java Transaction APIs if you want the container to manage the entities. Java Transaction APIs are only available if you are deploying to a Java EE 5 or EE6 container. If you are not deploying to a Java EE 5 or EE6 container, the transaction needs to be managed by the application. For more, see Transaction Types.
812
Sample data source is chosen for the
example Ejb module of the example project
813
Building a Persistence Unit with NetBeans
When we click finish the persistence.xml file is added to the ejb module part of the project. Right clicking and choosing edit displays the contents of the file on the editor section of NetBeans
814
Persistence Unit name and
Other information Persistence.xml
816
Double clicking on the persistence.xml file can allow us to view
properties of the file in a graphical type of a presentation. You can change data source, add/delete entity classes etc.
817
Web Tier Management of JPA
Data shared between web components that needs to be persistent, between invocations by the client, needs to be stored in a data source. In Web Tier management we will use the JPA from the web tier (the web server) Suppose we have a data source created named Books with a single Table named WEB_BOOKSTORE_BOOKS already populated (from Java EE5 Tutorial).
818
Web Tier Management of JPA
We need to create a Persistence Unit. It identifies the schema The name of the Persistence Unit and the transaction type A jta-data-source element to indicate JTA transactions container managed. We need to create an entity class to represent eachTable in the database.
819
Web Tier Management of JPA
Entity classes. Entity classes are used to represent tables in a database. The Java Persistence API enables you to use entity classes directly in your web application. Entity Manager. An entity manager manages the entities and performs database functions. Persistence Unit. A persistence unit specifies the data source and which entities are managed by the entity manager.
820
Web Tier Management of JPA
About Entity Classes Each entity class usually represents a table in a relational database. Each instance of an entity corresponds to a row in a table. Persistent fields or properties correspond to columns in a table. Unlike entity beans, entity classes are not restricted to EJB modules in enterprise applications. Entity classes can be located in an EJB module or a web module.
821
Web Tier Management of JPA
@Entity @Table(name = "WEB_BOOKSTORE_BOOKS") public class Book implements Serializable { @Id private String bookId; private String description; private String firstName; private String surname; private String title; private boolean onSale; …………………………………………. …………………………………………… //constructors and accessor/mutator methods
822
Web Tier Management of JPA
A class BookDB has set and get methods that allow access to Books. An Application Object of BookDB needs to have access to an Entity Manager object. The only way to do that is to have a ServletContextListener subclass create the EntityManagerFactory object and pass it to BookDBAO object. This is called resource injection. Its intend is to have the web container manage the entity bean (which normally is done by the applications server’s container) .
823
EJB Tier Management of JPA
In this case we will have: A client application (a web application) that communicates with a Session Bean. The Session Bean carries the Business logic and communicates with the entities. The entities that persist the data. Data source.
824
EJB Tier Management of JPA
We can create two applications: One that holds the session bean and the entities. One that holds the client application. It populates the entities with data, retrieves data and displays it. Opening the Order project (available on the EE5 Tutorial text CD or the course’s web site javaeetutorial5.zip ) and expanding it we get:
825
General Project Files Client Related Files Remote Interface for Session Bean Entity Source files Session Bean Files
826
Client Client is annotated to work with the Session Bean:
public class OrderClient { @EJB The client creates data and then displays it by getting it back from the data source: public static void main(String[] args) { OrderClient client = new OrderClient(args); try { client.createData(); client.printData(); } catch (Exception ex) {……….} }
827
Client For example, method createData in Client does operations to populate the data source tables i.e. : private static void createData() { try { request.createPart( " ", 1, "ABC PART", new java.util.Date(), "PARTQWERTYUIOPASXDCFVGBHNJMKL", null); Where request is a reference of the interface Request and createPart is one of the methods implemented by the Session Bean: RequestBean
828
Session Bean The Session Bean implements the method createPart:
@Stateful public class RequestBean implements Request { @PersistenceContext private EntityManager em; public void createPart( String partNumber, int revision, String description, java.util.Date revisionDate, String specification, Serializable drawing) {
829
Session Bean try { Part part = new Part( partNumber, revision, description, revisionDate, specification, drawing); em.persist(part); ……………………………….. Where Part is one of the entities and em is the Entity Manager object.
830
Entity Part = = "EJB_ORDER_PART_DETAIL", pkJoinColumns = = "PARTNUMBER", referencedColumnName = "PARTNUMBER") = "REVISION", referencedColumnName = "REVISION") } )
831
Summary Create Persistence Unit
Create the Entity Classes defined in the persistence unit’ s descriptor file persistence.xml Obtain access to an Entity Manager object Access data in database by writing the proper SQL queries in client units to the database.
832
Creating Entity Classes from an Existing Data Source
In addition to writing entity classes from scratch, you can also generate a set of persistent entity classes for an existing database. You can use the New Entity Classes from Database wizard to generate the entity classes from a connected database or from a database schema.
833
Creating Entity Classes from an Existing Data Source
To generate entity classes from a database: Right-click the module project node in the Projects window and choose New > Other. In the New File wizard, select Entity Classes from Database from the Persistence category. Select the source database that contains the tables that you want to use to generate the entity classes:
834
Creating Entity Classes from an Existing Data Source
To create from a connected data source Data Source. Choose a data source from the drop-down menu. Alternately, you can choose Add Data Source to create a new data source. The database must be running to choose this option. When choosing a data source, the server must be running and the data source must be registered with the server. After you select the source database, the tables in that database are listed in the Available Tables pane.
835
Creating Entity Classes from an Existing Data Source
Select any tables in the left pane and click the Add button. Any tables related to the tables you select are automatically added to the list in the right pane. The IDE will generate entity classes for each table listed in the right pane. Deselect Include Related Tables if you do not want entity classes created for related tables. Click Next. Confirm the name of the classes that will be generated for each table listed. Select the location where you want to save the entity classes. Select an existing package from the Package drop-down menu or type the name of a new package.
836
Creating Entity Classes from an Existing Data Source
Confirm that you want the IDE to generate named query annotations in the entity classes. If you do not want the IDE to generate the annotations, deselect Generate Named Query Annotations for Persistent Fields. Click Finish. When you click Finish, the IDE creates entity classes for each of the tables you specified in the wizard. The package containing the generated entity classes is selected in the Projects window.
837
Study Guide Read Chapter 25 of EE5 Tutorial.
Set up and run the bookstore example from the CD Read Chapter 26 of EE5 Tutorial. Set up and run the Order and Roster examples from the CD.
838
George Koutsogiannakis/Summer 2011
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 19 George Koutsogiannakis/Summer 2011
839
Topics Java Persistence Query Language (JPQL) Security in Java EE.
Security Roles. Web Security.
840
JPQL Allows writing of queries that are portable across data stores (databases). The Java Persistence Query Language (JPQL) is a platform-independent object-oriented query language defined as part of the Java Persistence API specification. JPQL is used to make queries against entities stored in a relational database.
841
JPQL It is heavily inspired by SQL, and its queries resemble SQL queries in syntax, but operate against JPA entity objects rather than directly with database tables. In addition to retrieving objects (SELECT queries), JPQL supports bulk UPDATE and DELETE queries.
842
JPQL JPQL looks like SQL but it has some differences and enhancements over SQL: Like relational tables, entities are typically related to each other with relationships such as one-to-one, one-to-many, many-to-one, or many-to-many. Java applications dealing with entities require a standard mechanism to access and navigate entity instances. The Java Persistence Query Language (JPQL) is specifically designed for this purpose.
843
JPQL The main difference between JPQL and SQL lies in that the former deals with JPA entities, while the latter deals directly with relational data. JPQL eliminates the need for you to use JDBC API from your Java code—the container does all this work for you behind the scenes. JPQL lets you define queries using one of the following three statements: SELECT, UPDATE, or DELETE.
844
JPQL and JPA The EntityManager API interface offers methods that can also be used to perform retrieve, update and delete operations over entities. In particular, these are find, merge, and remove methods. The use of those methods, however, is typically limited to a single entity instance (that is a single row of data).
845
JPQL and JPA JPQL statements do not have such a limitation—you can define bulk update and delete operations over sets of entities (many rows), and define queries returning sets of entity instances. To issue a JPQL query from within your Java code, you have to utilize appropriate methods of the EntityManager API and Query API, performing the following general steps:
846
JPQL and JPA Obtain an instance of EntityManager, using injection or explicitly through an EntityManagerFactory instance. Create an instance of Query by invoking an appropriate EntityManager's method, such as createQuery. Set a query parameter or parameters, if any, using an appropriate Query's setParameter method.
847
JPQL and JPA If needed, set the maximum number of instances to retrieve and/or specify the position of the first instance to retrieve, using the setMaxResults and/or setFirstResult Query's methods. If needed, set a vendor-specific hint, using the setHint Query's method.
848
JPQL and JPA If needed, set the flush mode for the query execution with the setFlushMode Query's method, overriding the entity manager's flush mode. Execute the query using an appropriate Query's method: getSingleResult or getResultList. In the case of an update or delete operation, though, you must use the executeUpdate method, which returns the number of entity instances updated or deleted.
849
JPQL and JPA The following code fragment is taken from a servlet's doGet method that uses a JPQL query to obtain information about all the customers stored in the underlying relational table associated with the Customer entity specified in the query. @PersistenceUnit private EntityManagerFactory emf; public void doGet( EntityManager em = emf.createEntityManager(); PrintWriter out=response.getWriter(); List<Customer> arr_cust = (List<Customer>)em.createQuery( "SELECT c FROM Customer c") .getResultList(); out.println("List of all customers: "+“</br>");
850
JPQL and JPA Iterator i = arr_cust.iterator(); Customer cust; while (i.hasNext()) { cust = (Customer) i.next(); out.println(cust.getCust_id()+"<br/>"); out.println(cust.getCust_name()+"<br/>"); out.println(cust.get ()+"<br/>"); out.println(cust.getPhone()+"<br/>"); out.println(" " + "<br/>"); }
851
JPQL and JPA Of special interest here are:
the createQuery method of the EntityManager instance and t he getResultList method of the Query instance. The EntityManager's createQuery is used to create the Query instance whose getResultList method is then used to execute the JPQL query passed to createQuery as the parameter. The Query's getResultList method returns the result of a query as a List whose elements, in this particular example, are cast to type Customer.
852
JPQL and JPA With setParameter, you can bind both named and positional parameters Integer cust_id =2; Customer cust = (Customer)em.createQuery("SELECT c FROM Customer c WHERE c.cust_id=:cust_id") .setParameter("cust_id", cust_id) .getSingleResult(); out.println("Customer with id "+cust.getCust_id()+" is: "+ cust.getCust_name()+"<br/>");
853
JPQL and JPA Similarly, to obtain the entire list of customers' names, you might use the following code: ... List<String> arr_cust_name = (List<String>)em.createQuery("SELECT c.cust_name FROM Customer c") .getResultList(); out.println("List of all customers: "+"<br/>"); Iterator i = arr_cust_name.iterator(); String cust_name; while (i.hasNext()) { cust_name = (String) i.next(); out.println(cust_name+"<br/>"); }
854
JPQL and JPA Like SQL, JPQL lets you define join queries.
JPQL is still evolving, and doesn't have many of important features available in SQL as yet.
855
JPQL-EXAMPLE Suppose we have JPA entity classes defined like this (getter and setter methods omitted for simplicity): @Entity public class Author { @Id private Integer id; private String firstName; private String lastName; @ManyToMany private List<Book> books; ……………………………………….. }
856
JPQL-EXAMPLE @Entity public class Book { @Id private Integer id;
private String title; private String isbn; @ManyToOne private Publisher publisher; @ManyToMany private List<Author> authors; ……………………………………………………… }
857
JPQL-EXAMPLE @Entity public class Publisher { @Id private Integer id;
private String name; private String address; @OneToMany(mappedBy = "publisher") private List<Book> books; ……………………………………. }
858
JPQL-EXAMPLE In this example we have annotated the relationships:
An Author entity (one row of data from the Book table) relates to many entities of Book(many rows from Book table) and vice versa. A Publisher entity can relate to many Book entities but a Book entity can only relate to one Publisher entity. Notice that the many relationship is handled with List structures of the corresponding type (entity). Thus we have an easy way to establish the relationships between tables programmatically.
859
SQL VERSION QUERIES SQL queries can be written:
A simple SQL query to retrieve the list of all authors, ordered alphabetically, would be: SELECT a FROM Author a ORDER BY a.firstName, a.lastName To retrieve the list of authors that have ever been published by XYZ Press: SELECT DISTINCT a FROM Author a INNER JOIN p.books b WHERE b.publisher.name = 'XYZ Press'
860
JPQL Or, Instead of using SQL statements we could write a JPQL function , for example, returning a list of authors with the given first name as follows: import javax.persistence.EntityManager; import javax.persistence.Query; import org.apache.commons.lang.StringUtils; public List<Author> getAuthorsByLastName(String lastNameParam) { String queryString = "SELECT auth FROM Author auth, WHERE :lastName IS NULL OR LOWER(auth.lastName) = :lastNameParam"; Query query = getEntityManager().createQuery(queryString); query.setParameter("lastName", StringUtils.lowerCase(lastNameParam)); return query.getResultList(); }
861
JPQL In the previous example the JPQL syntax for the SELECT query statement was used: JPQL language keywords are underlined. Clauses are keywords and can be lower case or upper case. Entity names can be used as they appear in the class name for the Entity. auth is an identification variable defined in the statement as of type Author lastName is a field of the Entity. lastNameParam is a parameter passed to the method. The SELECT statement selects the author last names that match the value of this parameter.
862
JPQL The WHERE clause restricts the values to a conditional expression. Notice that a colon is used like =: or >: <:
863
JPQL Thus, JPQL has its own syntax somewhat different than SQL.
Details of JPQL syntax can be found on the web. One possible site is:
864
Security A container provides two kinds of security: Declarative
Expresses an application component’s security requirements using deployment descriptors. Annotations in the code are translated and entered into the deployment descriptor file by the IDE (or the deployment descriptor can be edited manually). Programmatic security. Embedded in an application to make security decisions.
865
Security Assume communications between a Client and a EE application that contains web and ejb parts. There are two levels of security Security handled by the web container Security handled by the ejb container.
866
Security Initial Security handled by the web container
In this approach: Client sends a request. Web Server sends back a form asking for user id and password. Client submits the information. Server validates the information. Server allows client requests based on the acceptable security role of the client. Client submits data to be processed by the Session Bean.
867
Security
868
Security The request now is ready to be submitted to the ejb part of the application. Second level of security now has to be established with the ejb container. The EJB container is responsible for enforcing access control on the enterprise bean method. It consults the security policy (derived from the deployment descriptor) associated with the enterprise bean to determine the security roles that are permitting access to the method. For each role, the EJB container uses the security context associated with the call to determine if it can map the caller to the role.
869
Security
870
Security The ejb container will evaluate the credentials submitted by the web container and issue either a call: Is authorized or Not authorized if the call is authorized, the container dispatches control to the enterprise bean method. The result of the bean’s execution of the call is returned to the JSP (or servlet), and ultimately to the user by the web server and the web client.
871
Security Functions A properly implemented security mechanism will provide the following functionality: Prevent unauthorized access to application functions and business or personal data. Hold system users accountable for operations they perform (non-repudiation). Protect a system from service interruptions and other breaches that affect quality of service.
872
Security APIs Security APIs supported are SE APIs
Java Authentication and Authorization Service (JAAS) Java Generic Security Services (Java GSS-API): Java GSS-API is a token-based API used to securely exchange messages between communicating applications. The GSS-API offers application programmers uniform access to security services atop a variety of underlying security mechanisms, including Kerberos.
873
Security APIs EE Java Secure Sockets Extension (JSSE).
Simple Authentication and Security Layer (SASL): SASL is an Internet standard (RFC 2222) that specifies a protocol for authentication and optional establishment of a security layer between client and server applications. EE Can be implemented using declarative or programmatic techniques.
874
Security Layers Application-Layer Security.
In Java EE, component containers are responsible for providing application-layer security. Provides security services for a specific application type tailored to the needs of the application. Security is uniquely suited to the needs of the application. Security is fine-grained, with application-specific settings. The application is dependent on security attributes that are not transferable between application types.
875
Security Layers Transport-Layer Security.
Relies on secure HTTP transport (HTTPS) using Secure Sockets Layer (SSL). Point-to-Point security mechanism that can be used for authentication, message integrity, and confidentiality. The client and server agree on an appropriate algorithm. A key is exchanged using public-key encryption and certificate-based authentication. A symmetric cipher is used during the information exchange.
876
Security Layers Message-Layer Security (Web Services)
Security information is contained within the SOAP message and/or SOAP message attachment. For example, a portion of the message may be signed by a sender and encrypted for a particular receiver (this is for Web Services). When the message is sent from the initial sender, it may pass through intermediate nodes before reaching its intended receiver. The encrypted portions continue to be opaque to any intermediate nodes and can only be decrypted by the intended receiver. For this reason, message-layer security is also sometimes referred to as end-to-end security.
877
Security Layers Security stays with the message over all hops and after the message arrives at its destination. Security can be selectively applied to different portions of a message. Message security can be used with intermediaries over multiple hops. Message security is independent of the application environment or transport protocol.
878
Security for Web Applications
A web application is created by developer. It is passed to a deployer who is responsible for the deployment of the application on servers. The deployer (person who is responsible for deploying the application on the server(s)) must set the security for the application : Either by adding annotations . Or, by modifying the deployment descriptor (web.xml)
879
Security for Web Applications
Deployment Descriptor Setting the attribute full of element web-app determines if the container will supplement the security setting in web.xml with the reading of annotations full=true means that the container will ignore annotations in the servlet classes. full=false means that the container will consider the annotations. Default is full=false. Because there are not annotations, as yet, for all security settings a combination of annotations and explicit deployment descriptor settings may be needed.
880
Security for Web Applications
Annotations for web application components are described in the Java Servlet 2.5 Specification which amongst other changes: Introduced all kinds of annotations to the servlet API (not just security annotations). Make sure that the web server supports servlet API 2.5 and up (most recent versions of Tomcat do support it (6.0 and up)).
881
Web-Applications Using Annotations Examples
@DeclareRoles This annotation is used to define the security roles that comprise the security model of the application. This annotation is specified on a class. Role is defined bycalling isUserInRole method from within the methods of the annotated class i.e. @DeclareRoles("BusinessAdmin") public class CalculatorServlet { //... } Where BusinessAdmin is the security role specified, The value of this parameter can include a list of security roles specified by the application.
882
Web-Applications Using Annotations Examples
This is the same as if we had declared the security role in the web.xml of the applications as: <web-app> <security-role> <role-name>BusinessAdmin</role-name> </security-role> </web-app>
883
Web-Applications Using Annotations Examples
Multiple security roles for the application can be annotated as: @DeclareRoles({"Administrator", "Manager", "Employee"}) When a call is made to isUserInRole from the annotated class, the caller identity associated with the invocation of the class is tested for membership in the role with the same name as the argument to isUserInRole. If a security-role-ref has been defined for the argument role-name, the caller is tested for membership in the role mapped to the role-name.
884
Web-Applications Using Annotations Examples
Another example of a security annotation is: @RunAs AnnotationName RunAs defines the role of the application during execution in a Java EE container and AnnotationName is some name used to define the role. It can be specified on a class, allowing developers to execute an application under a particular role. The role must map to the user/group information in the container’s security realm. The value element in the annotation is the name of a security role of the application during execution in a Java EE container.
885
Web-Applications Using Annotations Examples
annotation is equivalent to the run-as element in the deployment descriptor. @RunAs("Admin") public class CalculatorServlet { @EJB private ShoppingCart myCart; public void doGet(HttpServletRequest, req, HttpServletResponse res) { //.... myCart.getTotal(); //.... } } //....
886
Security Roles What are the security roles:
A role is an abstract name for the permission to access certain resources. The roles are defined in the data source based on the abstract names used.
887
Example Security Elements in Deployment Descriptor
<servelt> <security-role-ref> <role-name>Mgm</role-name> // The security role name used is the value of the security name used in the code of the servlet i.e HttpServletRequest.isUserInRole(String Mgm);
888
Example Security Elements in Deployment Descriptor
Security Constraint element <security-constraint> <display-name>SecurityConstraint</display-name> <web-resource-collection> <web-resource-name>WRCollection </web-resource-name> <url-pattern>/greeting</url-pattern> </web-resource-collection> <auth-constraint> <role-name>helloUser</role-name> </auth-constraint> <user-data-constraint> <transport-guarantee>NONE</transport-guarantee> </user-data-constraint> </security-constraint>
889
Example Security Elements in Deployment Descriptor
Security constraint element is used to define access privileges to a collection of resources. It could call for SSL connection if the sub element <user-data-constraint> is set to CONFIDENTIAL or INTEGRAL. User name and passwords are sent over HTTPS. Role name in <auth-constraint> must correspond to one of the role name used in <security-role> element.
890
Example Security Elements in Deployment Descriptor
Login Config element <login-config> <auth-method>BASIC</auth-method> <realm-name>file</realm-name> </login-config> //Used to describe the user authentication method for access to the web content.
891
Example Security Elements in Deployment Descriptor (web resources)
Authentication Methods are: Basic : requires that the server request a user name and password from the web client. When a request arrives the web server returns a dialog box that requests user name and password. The client fills in the information and submits the dialog box The server authenticates it and processes the request. This form of authentication can expose user names and passwords since they are encoded using Base64 , a simple encoding mechanism. Form: if above authetication fails it submits a form to be filled by the client. Not a very secured way to get user and password information.
892
Example Security Elements in Deployment Descriptor
CLIENT_CERT: requires the client to process a public key certificate. The server will authenticate the client based in the public key. Uses HTTP over SSL (HTTPS). More secure way of authenticating. It can be set for mutual authentication where the client authenticates itself with the server and the server sends a certificate to the client authenticating itself.
894
Example Security Elements in Deployment Descriptor
DIGEST: transmits password in a more secured encoding than BASIC. Not widely used in servers.
895
Study Guide Chapter 27 of EE5 Tutorial. Chapter 28 of EE 5 Tutorial.
Chapter 29 of EE5 Tutorial. (partial coverage). Or read corresponding chapter sin EE6 tutorial.
896
Appendix A JPQL Schema Example
This example assumes that the application developer provides several entity classes, representing: magazines, publishers, authors, and articles. The abstract schema types for these entities are Magazine, Publisher, Author, and Article.
897
Appendix A These are Entities with Abstract Persistence Schemas Defined in the Same Persistence Unit. The entity Publisher has a one-to-many relationships with Magazine. There is also a one-to-many relationship between Magazine and Article . The entity Article is related to Author in a one-to-one relationship.
898
Appendix A Queries to select magazines can be defined by navigating over the association-fields and state-fields defined by Magazine and Author. A query to find all magazines that have unpublished articles is as follows:
899
Appendix A SELECT DISTINCT mag FROM Magazine AS mag JOIN mag.articles AS art WHERE art.published = FALSE This query navigates over the association-field authors of the abstract schema type Magazine to find articles, and uses the state-field published of Article to select those magazines that have at least one article that is published.
900
Appendix A Although predefined reserved identifiers, such as DISTINCT, FROM, AS, JOIN, WHERE, and FALSE appear in upper case in this example, predefined reserved identifiers are case insensitive. The SELECT clause of this example designates the return type of this query to be of type Magazine. Because the same persistence unit defines the abstract persistence schemas of the related entities, the developer can also specify a query over articles that utilizes the abstract schema type for products, and hence the state-fields and association-fields of both the abstract schema types Magazine and Author.
901
Appendix A For example, if the abstract schema type Author has a state-field named firstName, a query over articles can be specified using this state-field. Such a query might be to find all magazines that have articles authored by someone with the first name "John". SELECT DISTINCT mag FROM Magazine mag JOIN mag.articles art JOIN art.author auth WHERE auth.firstName = 'John‘ Because Magazine is related to Author by means of the relationships between Magazine and Article and between Article and Author, navigation using the association-fields authors and product is used to express the query.
902
Appendix A This query is specified by using the abstract schema name Magazine, which designates the abstract schema type over which the query ranges. The basis for the navigation is provided by the association-fields authors and product of the abstract schema types Magazine and Article respectively.
903
George Koutsogiannakis Summer 2011
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 20 George Koutsogiannakis Summer 2011
904
Topics Realms, Users, Groups. Web Security Example.
Application Server Security. Web Services definitions.
905
Realms, Users, Groups A Realm is defined on the Application Server or the Web Server. In this lecture we assume that GlassFish is used regardless if the application is just a web application or a combination of web/ejb.
906
Realms, Users, Groups A REALM
Contains a collection of users that are covered by the same authentication policy. Users are assigned to roles as discussed in previous lecture. A Group is a set of authenticated users classified by common traits defined in the Application Server.
907
Realms, Users, Groups Realm appears as a data source (can be a table) of users and groups. There are 3 mappings of Realm: file:all clients except those that use certificates and HTTPS. certificate: clients are authenticated using certificates and HTTPS admin-realm: special realm reserved for administrators to manage users.
908
Realms, Users, Groups Realm contains a collection of users which may or may not be assigned to a group. For a web application, a realm is a complete database of users and groups that identify valid users of a web application (or a set of web applications) and are controlled by the same authentication policy.
909
Realms, Users, Groups A user is an individual (or application program) identity that has been defined in the Application Server. In a web application, a user can have a set of roles associated with that identity, which entitles them to access all resources protected by those roles. Users can be associated with a group.
910
Realms, Users, Groups A group is a set of authenticated users, classified by common traits, defined in the Application Server. Principal: A principal is an entity that can be authenticated by an authentication protocol in a security service that is deployed in an enterprise (in other words a user). Security policy domain (also known as security domain or realm): A security policy domain is a scope over which a common security policy is defined and enforced by the security administrator of the security service.
912
Web Security Example Overview of Web Application Security
In the Java EE platform, web components provide the dynamic extension capabilities for a web server. Web components are either Java servlets, JSP pages, JSF pages, or web service endpoints.
914
Web Security Example Basic Authentication with a Servlet
Add an authorized user to the Application Server. Start the Application Server in NetBeans services window. Start the Admin Console by right clicking on the server in NetBeans and choosing view admin console.. To log in to the Admin Console, enter the user name and password of a user in the admin-realm who belongs to the asadmin group. The name and password entered during installation will work, as will any users added to this realm and group subsequent to installation. Expand the Configuration node in the Admin Console tree.
915
Web Security Example-Add user to Application Server
Expand the Security node in the Admin Console tree. Expand the Realms node. Select the file realm to add users you want to enable to access applications running in this realm. (For the example security applications, select the file realm.) Select the admin-realm to add users you want to enable as system administrators of the Application Server. You cannot enter users into the certificate realm using the Admin Console. You can only add certificates to the certificate realm.
916
Web Security Example-Add user to Application Server
Click the Manage Users button. Click New to add a new user to the realm. Enter the correct information into the User ID, Password, and Group(s) fields. If you are adding a user to the file realm, enter the name to identify the user, a password to allow the user access to the realm, and a group to which this user belongs.
917
Web Security Example-Add user to Application Server
For the example security applications, enter a user with any name and password you like, but make sure that the user is assigned to the group of user. If you are adding a user to the admin-realm, enter the name to identify the user, a password to allow the user access to the Application Server, and enter asadmin in the Group field. Click OK to add this user to the list of users in the realm. Click Logout when you have completed this task.
918
Web Security Example-Add roles
You can add roles in the web.xml descriptor file. The following is an example of a security constraint from a web.xml application deployment descriptor file where the role of DEPT-ADMIN is authorized for methods that review employee data and the role of DIRECTOR is authorized for methods that change employee data. <security-constraint> <web-resource-collection> <web-resource-name>view dept data</web-resource-name> <url-pattern>/hr/employee/*</url-pattern> ` <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection>
919
Web Security Example-Add roles
<auth-constraint> <role-name>DEPT_ADMIN</role-name> </auth-constraint> <user-data-constraint> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint>
920
Web Security Example-Add roles
<security-constraint> <web-resource-collection> <web-resource-name>change dept data</web-resource-name> <url-pattern>/hr/employee/*</url-pattern> <http-method>GET</http-method> <http-method>PUT</http-method> </web-resource-collection> <auth-constraint> <role-name>DIRECTOR</role-name> </auth-constraint> <user-data-constraint> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint>
921
Web Security Example-Add roles
Notice the element <user-data-constraint> This element requires that all security contraint URL pattrens and HTTP methods are received over a protected transport layer. The choice COFIDENTIAL means that the transmitted data can not be accessed by other entities. HTTPS is used (SSL) Notice the element <auth-constraint> is used to define the users in their roles. The element <web-resource-collection> idetifies the URLs (resources) to be protected. Another element (not shown) is <login-config> is used to authenticate access to the web content by a user (before any request is processed base don a role).
922
Web Security Example-Add roles
The last step is to map the security role to the name of a user, or principal (in the application server). The security architecture provides a mechanism for mapping the roles defined in the application to the users or groups defined in the runtime realm. Use the security-role-mapping element in the runtime deployment descriptor (sun-application.xml, sun-web.xml, or sun-ejb-jar.xml) file.
923
Web Security Example-Add roles
The entry needs to declare a mapping between a security role used in the application and one or more groups or principals defined for the applicable realm of the Application Server. An example for the sun-web.xml file is shown below: <sun-web-app> <security-role-mapping> <role-name>DIRECTOR</role-name> <principal-name>mcneely</principal-name> </security-role-mapping> <role-name>DEPT_ADMIN</role-name> <group-name>administrators</group-name> </sun-web-app>
924
Web Security Example-Servlets
Create a web module hello2. The subsequent steps discuss adding security to this basic application. The files for this example application are in tut-install/javaeetutorial5/examples/web/hello2_basicauth/. There are two servlets: GreetingSerlet.java ResponseServlet.java
925
Web Security Example-Servlets
@DeclareRoles("helloUser") public class GreetingServlet extends HttpServlet { public void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setBufferSize(8192); PrintWriter out = response.getWriter(); // then write the data of the response out.println("<html>" + "<head><title>Hello</title></head>"); out.println("<body bgcolor=\"#ffffff\">"
926
Web Security Example-Servlets
+ "<img src=\"duke.waving.gif\" alt=\"Duke waving\">" + "<h2>Hello, my name is Duke. What's yours?</h2>" + "<form method=\"get\">" + "<input type=\"text\" name=\"username\" size=\"25\">" + "<p></p>" + "<input type=\"submit\" value=\"Submit\">" + "<input type=\"reset\" value=\"Reset\">" + "</form>"); String username = request.getParameter("username"); if ((username != null) && (username.length() > 0)) { RequestDispatcher dispatcher = getServletContext().getRequestDispatcher( "/response"); if (dispatcher != null) { dispatcher.include(request, response);} } out.println("</body></html>"); out.close(); }
927
Web Security Example-Servlets
public String getServletInfo() { return "The Hello servlet says hello."; }
928
Web Security Example-Servlets
public class ResponseServlet extends HttpServlet { public void doGet( HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); // then write the data of the response String username = request.getParameter("username"); if ((username != null) && (username.length() > 0)) { out.println("<h2>Hello, " + username + "!</h2>"); } public String getServletInfo() { return "The Response servlet says hello.";
929
Web Security Example-Servlets
Declare the roles that will be used in this application. For this example, this is done by adding annotation to GreetingServlet.java. The deployment descriptor web.xml should have the role described :
930
Web Security Example-web.xml
<security-constraint> <display-name>SecurityConstraint</display-name> <web-resource-collection> <web-resource-name>WRCollection</web-resource-name> <url-pattern>/greeting</url-pattern> </web-resource-collection> <auth-constraint> <role-name>helloUser</role-name> </auth-constraint> <user-data-constraint> <transport-guarantee>NONE</transport-guarantee> </user-data-constraint> </security-constraint> <login-config> <auth-method>BASIC</auth-method> <realm-name>file</realm-name> </login-config>
931
Web Security Example- sun-web.xml (Application Server)
Map the role name defined for this resource (helloUser) to a group of users defined on the Application Server. That is the roles define din the web.xml must be linked to the users in the Application Server. Mapping Application Roles to Application Server Groups Map the role of helloUser defined in the application to the group of user defined on the Application Server by adding a security-role-mapping element to the sun-web.xml runtime deployment descriptor file.
932
Web Security Example- sun-web.xml
The runtime deployment descriptor is an XML file that contains information such as the context root of the web application and the mapping of the portable names of an application’s resources to the Application Server’s resources.
933
Web Security Example- sun-web.xml
<sun-web-app> <context-root>/hello2_basicauth</context-root> <security-role-mapping> <role-name>helloUser</role-name> <group-name>user</group-name> </security-role-mapping> </sun-web-app>
934
Web Security Example Add authorized users to the file type realm of the Application Server Build, package, and deploy the web application.
935
Summary of Security Settings for a Web Application
Identify realms . Groups and users in the Application server. Create the web.xml security role sin combination with annotations in your web resources code. Identify the security roles.
936
Summary of Security Settings for a Web Application
Map the security roles to the security constraints in the Application server. Elements of the security constraints will define the users/group that pertain to the particular role and the security restrictions for that role. Notice that the security restrictions are linked to particular resources defined in the proper element.
937
Security for Java EE Components.
Let us discuss security for Enterprise Beans. Enterprise Beans can be called from application clients or from web applications (as in previous slides). The EJB container can provide additional security pertaining to the beans. This can be accomplished in a declarative way and/or in a programmatic way.
939
Security for Java EE Components
You can protect enterprise beans by doing the following: Accessing an Enterprise Bean Caller's Security Context Declaring Security Role Names Referenced from Enterprise Bean Code Defining a Security View of Enterprise Beans Using Enterprise Bean Security Annotations Using Enterprise Bean Security Deployment DescriptorElements.
940
Security for Java EE Components
Accessing an Enterprise Bean Caller’s Security Context In general, security management should be enforced by the container in a manner that is transparent to the enterprise beans’ business methods. The security API described in this section should be used only in the less frequent situations in which the enterprise bean business methods need to access the security context information.
941
Security for Java EE Components
The javax.ejb.EJBContext interface provides two methods that allow the bean provider to access security information about the enterprise bean’s caller. java.security.Principal getCallerPrincipal(); The purpose of the getCallerPrincipal method is to allow the enterprise bean methods to obtain the current caller principal’s name. The methods might, for example, use the name as a key to information in a database. boolean isCallerInRole(String roleName); The purpose of the isCallerInRole(String roleName) method is to test whether the current caller has been assigned to a given security role.
942
Security for Java EE Components
If we assume, for example, that the current caller user contains the primary key used for the identification of employees (for example, employee number): / /obtain the caller principal callerPrincipal = ctx.getCallerPrincipal(); // obtain the caller principal’s name. callerKey = callerPrincipal.getName(); // use callerKey as primary key to find EmployeeRecord EmployeeRecord myEmployeeRecord = em.findByPrimaryKey(EmployeeRecord.class, callerKey);
943
Security for Java EE Components
Declaring Security Role Names Referenced from Enterprise Bean Code You can declare security role names used in enterprise bean code using either annotation (preferred) or the security-role-ref elements of the deployment descriptor.
944
Security for Java EE Components
Defining a Security View of Enterprise Beans You can define a security view of the enterprise beans contained in the ejb-jar file and pass this information along to the deployer. When a security view is passed on to the deployer, the deployer uses this information to define method permissions for security roles. If you don’t define a security view, the deployer will have to determine what each business method does to determine which users are authorized to call each method.
945
Security for Java EE Components
A security view consists : of a set of security roles, a semantic grouping of permissions that a given type of users of an application must have to successfully access the application. Security roles are meant to be logical roles, representing a type of user. You can define method permissions for each security role. A method permission is a permission to invoke a specified group of methods of the enterprise beans’ business interface, home interface, component interface, and/or web service endpoints. You can specify an authentication mechanism that will be used to verify the identity of a user.
946
Security for Java EE Components
Use annotations to define security roles using Java language annotations. The set of security roles used by the application is the total of the security roles defined by the security role names used in annotations (multiple roles can be defined).
947
Security for Java EE Components
Enterprise JavaBeans components use an EJB deployment descriptor that must be named : META-INF/ejb-jar.xml (must be contained in the EJB JAR file). The role of the deployment descriptor is to relay information to the deployer about security and other aspects of the application. Specifying this information in annotations or in the deployment descriptor helps the deployer set up the appropriate security policy for the enterprise bean application.
948
Security for Java EE Components
The following is a listing of deployment descriptor elements that address security: The security-role-ref element declares each security role referenced in the code. The security-role element defines broad categories of users, and is used to provide access to protected methods. The method-permission element is used to specify method permissions. The run-as element is used to configure a component’s propagated security identity.
949
Security for Java EE Components
You can augment the set of security roles defined for the application by annotations using the security-role deployment descriptor in the ejb-jar.xml file. i.e. <security-role> <description> This role includes the employees of the enterprise who are allowed to access the employee self-service application. This role is allowed only to access his/her own information. </description> <role-name>employee</role-name> </security-role>
950
Security for Java EE Components
We have two levels of security: We are trying to set the security references of the component. We also have the security references at the application level. The two need to be linked. In the absence of explicit linking a role at the component level will be linked automatically to a role with the same name at the application level. Or, you can explicitly link all the security role references declared in annotation or security-role-ref elements for a component to the security roles defined by the use of annotations and/or in the security-role elements.
951
Security for Java EE Components
You can use the role-link element to link each security role reference of a component to a security role at the application level i.e. <session> <ejb-name>AardvarkPayroll</ejb-name> <ejb-class>com.aardvark.payroll.PayrollBean</ejb-class> ... <security-role-ref> <description> This role should be assigned to the employees of the payroll department. Members of this role have access to anyone’s payroll record. The role has been linked to the payroll-department role. </description> <role-name>payroll</role-name> <role-link>payroll-department</role-link> </security-role-ref> ... </session>
952
Security for Java EE Components
Specifying Method Permissions If you have defined security roles for the enterprise beans in the ejb-jar file, you can also specify the methods of the business interface, home interface, component interface, and/or web service endpoints that each security role is allowed to invoke.
953
Security for Java EE Components
Specifying Method Permissions Using Annotations The method permissions for the methods of a bean class can be specified on the class, the business methods of the class, or both. Method permissions can be specified on a method of the bean class to override the method permissions value specified on the entire bean class. @RolesAllowed("list-of-roles") list-of-roles is a list of security role names to be mapped to the security roles that are permitted to execute the specified method or methods. Specifying this annotation on the bean class means that it applies to all applicable business methods of the class.
954
Security for Java EE Components
@PermitAll Specifies that all security roles are permitted to execute the specified method or methods. Specifying this annotation on the bean class means that it applies to all applicable business methods of the class. @DenyAll Specifies that no security roles are permitted to execute the specified method or methods.
955
Security for Java EE Components
@RolesAllowed("admin") public class SomeClass { public void aMethod () {...} public void bMethod () {...} ... public class MyBean implements SomeClass public void cMethod () {...} ... } The method permissions values of methods aMethod and bMethod and respectively. The method permissions for method cMethod have not been specified.
956
WEB SERVISES What are Web Services?
a software system designed to support interoperable machine-to-machine interaction over a network". Web services are frequently just Web application programming interfaces (API) that can be accessed over a network, such as the Internet, and executed on a remote system hosting the requested services
957
WEB SERVICES What are Web Services?
Web services are application components Web services communicate using open protocols Web services are self-contained and self-describing Web services can be discovered using UDDI Web services can be used by other applications XML is the basis for Web services
958
WEB SERVICES The basic Web services platform is XML + HTTP.
XML provides a language which can be used between different platforms and programming languages and still express complex messages and functions. The HTTP protocol is the most used Internet protocol. Web services platform elements: SOAP (Simple Object Access Protocol) UDDI (Universal Description, Discovery and Integration) WSDL (Web Services Description Language)
959
Study Guide Read Chapters 29 and 30 of EE5 Tutorial or corresponding chapters in EE6 tutorial.
960
George Koutsogiannakis Summer 2011
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 21 George Koutsogiannakis Summer 2011
961
Topics Web Services. XML SOAP WSDL UDDI
962
Web Services Two competing architectures.
.NET (Microsoft). Sun’s Java Web Services. We will discuss Sun’s Web Services.
963
Web Services Deployment is independent of the two technologies.
Interoperability between different languages. Interoperability between different platforms. Interoperability between transport protocols (messages can ride on top of existing protocols by adding an extra layer).
964
Java Web Services Java Web Services Developer Pack is used for web services and clients. Java Web Services Developer Pack includes the following: Java API for XML Messaging (JAXM) Java API for XML Processing (JAXP) Java API for XML Registries (JAXR) Java API for XML based RPC (JAX-RPC) Java API for XML Web Services (JAX-WS) SOAP with Attachments API for Java (SAAJ) Java Server Pages Standard Tag Library (JSTL) Java Server Faces Java WSDP Registry Server Web Applications Deployment Tool Ant Build Tool Apache Tomcat servlet container All of the above are part of EE5 and up .
965
Java Web Services Client Convert XML to Java Service Convert Java Type
to XML Java Types Communicatiosn XML messages communications
966
Web Services Web Services is a technology geared for Internet Based Distributed Computing. Requires adding to the Internet infrastructure another layer that is responsible for managing the resources needed for Web Services. Designers can design a Web Service without a concern as to the type or the number of nodes that are going to use the service. It is based on request/response messages.
967
Web Services Web Services use Internet protocols to publish their existence, discover each other and invoke each other. Publishing and discovery is done via: UDDI Universal Description, Discovery and Integration specification. It is used to list the available services. WSDL Web Services Description Language Describes the available services.
968
Web Services Other Protocols involved: XML
Custom made tags are used to structure the message. SOAP (Simple Object Access protocol) Transfers the messages.
969
Web Services Web Services are based on the concept of Service-Oriented Architecture (SOA). SOAP is based on building components that can communicate with each other. The components as in previous architectures that we studied (RMI, EJBs) must have well defined interfaces.
970
Web Services Any service architecture contains 3 roles:
A service provider Deployment of the service. Publishing (registering) the service. A service requestor Finds a service description published in one or more registries. Invokes the desired service. A service registry Advertizes web services descriptions published. It is the match maker between requestor and provider.
971
Web Services-XML XML mark up language’ specification identifies element as: A pairing of start and end tags in a XML document. Elements have one of the following: element-only content Nested elements mixed content Nested elements and text mixed. empty content.
972
Web Services -XML Elements can have attributes
A name value pair Value is enclosed in quotation marks. For instance we can have an element called purchase order (<po>) <po id=“43871” submitted=“ ” customerID=“1234”> </po>
973
Web Services -XML Alternatively instead of attributes we can define nested elements: <po> <id>43871</id> <submitted> </submitted> <customerID>1234</customerID> </po>
974
Web Services-XML - XML schemas
Document Type Definitions (DTD) document describes rules regarding the elements used. Schemas are used to validate the contents of XML documents as they are parsed by the XML parser. Schemas enable the following: Identification of the elements that are in a XML document. Identification of the order and relationship between elements in the XML document.
975
Web Services-XML Identification of the attributes of an element.
Identification of the data type of the value of an attribute. Thus in summary, we have: An XML document that defines the messages (data) in terms of XML elements. A DTD document that describes the elements. A need for a parser (can be written in Java) that checks the XML document against the DTD. If the XML document adheres to DTD it is called “well formed” otherwise errors are generated.
976
Web Services-XML The XML document then is made of 3 pieces:
Called entities: Elements Attributes Data
977
Web Services-SOAP SOAP is a specification that describes how data should be structured in order to be transported over the Internet as part of distributed services. SOAP is intended for B2B (Business to Business) or A2A (Application to Application) or EAI (Enterprise Application Integration). It is not intended for Business to Customer.
978
Web Services -SOAP SOAP is usually embedded in HTTP packets as part of request / response The riding of one protocol on top of another is called “tunneling”. SOAP handles data in terms of a textual form (RMI, CORBA and other distributed services protocols handle data in binary form).
979
Web Services-SOAP SOAP message An instance of the XML document
SOAP nodes Peers of the distributed network that uses SOAP. SOAP receiver A SOAP node that receives the SOAP message and processes it. SOAP intermediary A SOAP node that acts as receiver and sender.
980
Client requests service
Web Services-SOAP Ultimate receiver Client requests service intermediary intermediay Web Service resides in this node SOAP Message Path
981
Web Services-SOAP Intermediaries:
Can both accept and forward a message. They can do some message processing. Security domains are defined for the message.
982
Web Services-SOAP Message Exchange Patterns (MEP)
One way communication that specifies How many messages are interchanged in a given transaction. Originator of the message. Ultimate receiver of the message. Two types of MEP Request-Response MEP, similar to POST in http. Response MEP , similar to GET in http.
983
Web Services-SOAP A SOAP message consists of: Envelope (mandatory)
It is the root element of the XML document Header (Optional) Passes application specific information. It is used for transaction processing, authentication, login in. Body (mandatory) Actual application data to be transported. Fault Used to report errors back to sender
984
Web Services-SOAP <soap: envelope> <soap: header>
<……………> </soap:header> <soap:body> <………………> <soap:fault> <…………….> </soap:fault> </soap:body> </soap:envelope>
985
Web Services-SOAP The header uses special elements like:
<wsa (web services addressing) i.e. <wsa:ReplyTo><wsa:Address> </wsa:Address></wsa:ReplyTo> <wsa:To> <wsa:Action> Message Exchange Pattern (MEP) type can be specified in the header.
986
Web Services-SOAP The body can be something like:
<soap:Body wsu: ID=“Body”> <po:purchaseOrder xmlsn: po= <po:customer>………….</po:customer> <po:creditCardType>……..</po:creditCardType> <po:creditCardNumber>…….</po:creditCardNumber> </po:purchaseOrder> </soap:Body>
987
Web Services-SOAP SOAP data model follows a hierarchical tree of nodes in the structure of the elements. Therefore we can have a Java program that creates the elements for the message , based on some tree structure.
988
Web Services-SOAP streetNumber name name address address gender gender
Eva Bill 1000 streetNumber name name address address Person Address Person gender gender city state Female Male IL Chicago
989
Web Services-SOAP The java program can be: class Address {
String city; String state; int streetNumber; public Address(int stNum, String c, String st) this.streetNumber=stNum; this.city=c; this.state=st; }
990
Web Services-SOAP Class Person { String name; String gender; Address address; public Person(String n, String g, Address ad) this.name=n; this.gender=g; this.Address=address; }
991
Web Services-SOAP How Java is used in Web Services:
We can create XML documents in XML We can use a Java parser to parse the XML document’ s elements. The Java parser can use our DTD document a steh grammar file. We can use a Java program based on JAXP API to read the XML elements and the data in the XML document.
992
Web Services-JAXP API JAXP (java API for XML Processing) has parsers for XML documents. It provides a default parser. Or it can be configured to use other parsers. Can create a DTD programmatically. Can create the XML document
993
JAX-WS API AX-WS stands for Java API for XML Web Services.
JAX-WS is a technology for building web services using XML. It allows developers to write message-oriented as well as RPC-oriented web services. In JAX-WS, a web service operation invocation is represented by an XML-based protocol such as SOAP
994
JAX-WS API JAX-WS API hides the SOAP complexity from the application developer. On the server side, the developer specifies the web service operations by defining methods in an interface written in the Java programming language. The developer also codes one or more classes that implement those methods.
995
JAX-WS API A client creates a proxy (a local object representing the service) and then simply invokes methods on the proxy. The developer does not generate or parse SOAP messages. It is the JAX-WS runtime system that converts the API calls and responses to and from SOAP messages.
996
JAX-WS API Just like in EE beans and JPA classes ,
annotations are used here also.
997
JAX-WS API package helloservice.endpoint; import javax.jws.WebService;
public class Hello { private String message = new String("Hello, "); public void Hello() {} @WebMethod public String sayHello(String name) { return message + name + "."; } }
998
JAX-WS API In this example, the implementation class, Hello, is annotated as a web service endpoint using annotation. Hello declares a single method named sayHello, annotated with annotation. @WebMethod exposes the annotated method to web service clients. sayHello returns a greeting to the client, using the name passed to sayHello to compose the greeting. The implementation class also must define a default, public, no-argument constructor.
999
JAX-WS API When invoking the remote methods on the port, the client performs these steps: Uses the generated helloservice.endpoint.HelloService class which represents the service at the URI of the deployed service’s WSDL file. HelloService service = new HelloService(); Retrieves a proxy to the service, also known as a port, by invoking getHelloPort on the service. Hello port = service.getHelloPort();The port implements the SEI defined by the service. Invokes the port’s sayHello method, passing to the service a name.
1000
JAX-WS API package simpleclient; import javax.xml.ws.WebServiceRef;
import helloservice.endpoint.HelloService; import helloservice.endpoint.Hello; public class HelloClient { public static void main(String[] args) { try { HelloClient client = new HelloClient(); client.doTest(args); } catch(Exception e) { e.printStackTrace(); } }
1001
JAX-WS API public void doTest(String[] args) { try {
System.out.println("Retrieving the port from the following service: " + service); HelloService service = new HelloService(); Hello port = service.getHelloPort(); System.out.println("Invoking the sayHello operation on the port."); String name; if (args.length > 0) { name = args[0]; } else { name = "No Name"; } String response = port.sayHello(name); System.out.println(response); } catch(Exception e) { e.printStackTrace(); } }
1002
Web Services-WSDL WSDL is used to describe the message syntax associated with the invocation and response of a web service. It is an XML document that conforms to WSDL schema definition. WSDL is to the web services what IDL is to RMI over IIOP and Corba.
1003
Web Services-WSDL It describes 3 fundamental properties of a web service: What a service does- that is the methods of the web service that can be invoked. How a service is accessed- the data formats and protocols required to access the service. Where a service is located- such as the URL for the service. It has special elements to allow description of the above i.e <portType name=“PriceCheckPortType”> <operation name=”checkPrice”> <input message=“pc:PriceCheckRequest”/> <output message=“PriceCheckResponse”> </operation> </portType>
1004
Web Services-WSDL Where message is modeled via the XML document. It has a collection of elements. A special element in WSDL called binding tells how to format the message (the XML elements) The binding element tells how to invoke the operation using SOAP over HTTP (or some other protocol). WSDL maps to Java via tools that automate the process. A tool like that is WSDL2Java provided by Apache Axis. (AXIS = Apache eXtensible Interaction System) .
1005
Web Services-UDDI UDDI facilitates service discovery
At design time (static discovery) Or, at runtime (dynamic discovery). UDDI makes reference to a specific WSDL document for the service. UDDI uses its own elements to provide the description of the service. You can use Java to do the registration or the discovery of the service. A UDDI can be looked at as another web service. It could be accomplished by using JAX (Java for XML ) API.
1006
Links to WSDL Documents
UDDI Registry Links to WSDL Documents Publish Search Service Consumers Service Provider SOAP messages
1007
Study Guide Chapter 16 of EE5 Tutorial
Or Chapters 11,12,13 of EE6 Tutorial
1008
George Koutsogiannakis Summer 2011
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 22 George Koutsogiannakis Summer 2011
1009
Topics Web Services- APIs used in EE5 JAX-RPC (before EE5) JAX-WS JAXB
1010
Web Services-JAX-RPC JAX-RPC enables a Web Service endpoint to be developed using either a Java Servlet or Enterprise JavaBeans (EJB) component model. A Web service endpoint is deployed on either the Web container or EJB container based on the corresponding component model. These endpoints are described using a WSDL document. This WSDL document can be published in public or private registry, though this is not required. A client uses this WSDL document and invokes the Web service endpoint. A JAX-RPC client can use stubs-based, dynamic proxy or dynamic invocation interface (DII) programming models to invoke a heterogeneous Web service endpoint.
1011
Web Services-JAX-RPC RPC stands for Remote Procedure Call.
A protocol used by Microsoft in their systems. RMI (and its offsprings) is similar to RPC. JAX-RPC allows the communication of a web service client with a web component/ejb session bean so that the web service can be invoked via the business rules model.
1012
Web Services-JAX-RPC
1013
Web Services-JAX-RPC It is assumed that the client is aware of the Web service and the remote procedure that it can execute on the Web service. This is what happens: The client calls the method on the stub that represents the remote procedure. The stub executes the necessary routines on the JAX-RPC runtime system. The runtime system converts this method call into a SOAP message and transmits the message to the server as an HTTP request. The server, upon receipt of the SOAP message, invokes the methods on the JAX-RPC runtime. The JAX-RPC runtime converts the SOAP request into a method call. The JAX-RPC runtime then calls the method on the tie object. Finally, the tie object calls the method on the implementation of the Web service. The response to the RPC call is sent in a SOAP response message as an HTTP response.
1014
Web Services-JAX-RPC The Web service is represented by two files: the service definition interface, and the corresponding implementation class. The service definition interface and the implementation class are collectively known as the service endpoint.
1015
EE5 and Web Services-JAX-WS
Java EE5 provides annotations for Web Services. JAX-WS 2.0 is the new API for web services in the Java EE 5 platform and it is a successor to JAX-RPC.
1016
EE5 and Web Services-JAX-WS
Example comparing the approach between JAX-RPC and JAX-WS 2.0 JAX-RPC Web Service: public interface HelloService extends Remote { public String sayHello(String name) throws RemoteException; } public class HelloServiceBean implements SessionBean { public String sayHello(String name) { return "Hello "+ name + " from HelloServiceBean";
1017
EE5 and Web Services-JAX-WS
Example using JAX-WS 2.0 @WebService public class HelloServiceBean { public String sayHello(String name) return "Hello "+ name + " from HelloServiceBean"; } Notice that: No need for an interface! annotation defines the class as a web service end point.
1018
EE5 and Web Services-JAX-WS
Here is another example with more annotations: @WebService(name=”CreditRatingService”, targetNamespace=” public class CreditRating { @WebMethod(operationName=”getCreditScore”) public Score getCredit( @WebParam(name=”customer”) Customer c { // ... implementation code ... }
1019
EE5 and Web Services-JAX-WS
Our diagram is now revised to show that the JAX-WS runtime environment is used instead of JAX-RPC. Notice that the service can also be an ejb.
1020
EE5 and Web Services-JAX-WS
You may specify an explicit interface by adding the endpointInterface element to annotation in the implementation class. You must then provide an interface that defines the public methods made available in the endpoint implementation class.
1021
EE5 and Web Services-JAX-WS
The wsgen tool and the Application Server provide the Application Server’s implementation of JAX-WS. wsgen generates all articrafts (files) needed for the implementation of the web service.
1022
EE5 and Web Services-JAX-WS
Building a Web Service With Java WSDP 2.0 Write an endpoint implementation class. Compile the endpoint implementation class. Generate portable artifacts required for web service by using wsgen tool. Package the web service as a WAR file and deploy it. Code the client class. Use wsimport tool to generate and compile the web service artifacts needed to connect to the service. Compile the client class. Run the client.
1023
EE5 and Web Services-JAX-WS
Suppose our end point service class is: package helloservice.endpoint; import javax.jws.WebService; @WebService public class Hello { private String message = new String("Hello, "); public void Hello() {} //constructor @WebMethod public String sayHello(String name) return message + name + "."; }
1024
EE5 and Web Services-JAX-WS
You can build, package, and deploy the helloservice application using either NetBeans IDE or ant. Notice that the WSDL file is generated automaticaly (as well as the descriptor files needed). Also, notice that XML is totally hidden from the developer. Keep in mind that annotations come with attributes: i.e. annotation has attributes:
1025
EE5 and Web Services-JAX-WS
endpointInterface name portName serviceName targetNamespace wsdlLocation
1026
EE5 and Web Services-JAX-WS
Coding the Client When invoking the remote methods on the port, the client performs these steps: Uses the javax.xml.ws.WebServiceRef annotation to declare a reference to a web service. @WebServiceRef uses the wsdlLocation element to specify the URI of the deployed service’s WSDL file. @WebServiceRef(wsdlLocation=" static HelloService service; Retrieves a proxy to the service, also known as a port, by invoking getHelloPort on the service. Hello port = service.getHelloPort();The port implements the SEI defined by the service. Invokes the port’s sayHello method, passing to the service a name. String response = port.sayHello(name);
1027
EE5 and Web Services-JAX-WS
public class HelloClient helloservice/hello?wsdl") static HelloService service; ……………………………………………………… Hello port = service.getHelloPort(); String response = port.sayHello(name); System.out.println(response); …………………………………………………………….
1028
EE5 and Web Services-JAXB
JAX-WS delegates the mapping of the Java language data types to JAXB API. JAXB stands for Java Architecture for XML Binding. JAXB converts XML schemas to Java Content trees (see example in previous lecture of a content tree) and vice versa.
1029
EE5 and Web Services-JAXB Architecture.
1030
EE5 and Web Services-JAXB Architecture.
Basically JAXB is the translator of XML schemas (and data types) to Java and vice versa. Since the WSDL describes the XML schema there is a need to translate that schema to Java. It is the job of JAXB to do just that.
1031
EE5 and Web Services-JAXB Architecture.
XML Schema Type Java Data Type xsd:string java.lang.String xsd:integer java.math.BigInteger xsd:int int xsd.long long xsd:short short xsd:decimal java.math.BigDecimal xsd:float float
1032
EE5 and Web Services-JAXB Architecture
1033
EE5 and Web Services-JAXB Architecture
Generate classes: An XML schema is used as input to the JAXB binding compiler to generate JAXB classes based on that schema. Compile classes: All of the generated classes, source files, and application code must be compiled. Unmarshal: XML documents written according to the constraints in the source schema are unmarshalled by the JAXB binding framework. Note that JAXB also supports unmarshalling XML data from sources other than files/documents, such as DOM nodes, string buffers, SAX Sources, and so forth. Generate content tree: The unmarshalling process generates a content tree of data objects instantiated from the generated JAXB classes; this content tree represents the structure and content of the source XML documents.
1034
EE5 and Web Services-JAXB Architecture
Validate (optional): The unmarshalling process optionally involves validation of the source XML documents before generating the content tree. Note that if you modify the content tree in step below, you can also use the JAXB Validate operation to validate the changes before marshalling the content back to an XML document. Process content: The client application can modify the XML data represented by the Java content tree by means of interfaces generated by the binding compiler. Marshal: The processed content tree is marshalled out to one or more XML output documents. The content may be validated before marshalling.
1035
EE5 and Web Services-NetBeans support.
NetBeans 6.5 provides support for web services using JAX-WS and JAXB. For more information on how to use NetBeans to develop a web service by utilizing JAX-WS and JAXB see the NetBeans tutorial at:
1036
Study Guide EE5 Tutorial text chapter 15. EE5 Tutorial text chapter 16
NetBeans tutorial online. EE5 Tutorial chapters 11,12
1037
George Koutsogiannakis Summer 2011
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 23 George Koutsogiannakis Summer 2011
1038
Topics Java Server Faces Definitions JSF Parts Why JSF?
JSF Competitors JSF Request Lifecycle. JSF Standard Tag Libraries
1039
What is JSF JavaServer Faces (JSF) is an application framework for creating Web-based user interfaces Java Server Faces (JSF): A set of APIs (Frameworks) that: Have prefabricated UI (User Interface) components. Allow third party developers to add new UI components. Can provide all necessary code for event handling and component organization. Utilizes Java Server Pages and custom tags libraries. Usually an IDE is needed (like NetBeans). JSF is a direct competitor to Microsoft's WebForms(part of ASP.NET MVC)
1040
JSF Parts It consists of UI Components Events Validators & converters
Navigation Back-end-data integration
1041
JSF Parts UI Components
The API provides a set of classes and interfaces that specify component behavior and functionality. UIComponent/UIComponentBase Base class for all user interface components Standard UIComponent Subclasses i.e.: UICommand : represents a control that fires actions when requested. UIForm: Groups a number of controls that can submit data from the user to the application
1042
JSF Parts UIOutput: Displays data output on a page (displayed by the Browser) UIInput: Takes data input from user UISelectItem: Represents a single item selection UISelectMany: Allows a user to select many items from a group of items Many others not listed here. A UI component developer develops the component. Page authors and developers include the component in their design in a tag.
1043
JSF Parts Events and Listeners naming patterns
Follows JavaBeans Specification design and naming patterns Standard events and listeners ActionEvent—UICommand component activated by the user. ValueChangedEvent—UIInput component whose value was just changed.
1044
JSF Parts Event handling is similar to event handling used in a regular Java application: An Event object identifies the component that generated the event and stores information about the event. An application provides an implementation of the Listener class and must register it on the component that generates the event. When the user activates a component, such as by clicking a button, an event is fired. This causes the JavaServer Faces implementation to invoke the listener method that processes the event.
1045
JSF Parts JavaServer Faces technology supports three kinds of events:
value-change events when the user changes the value of a component represented by UIInput or one of its subclasses. An example is selecting a check box, an action that results in the component’s value changing to true. action events An action event occurs when the user activates a component that implements ActionSource. These components include buttons and hyperlinks.
1046
JSF Parts Data model events
occurs when a new row of a UIData component is selected.
1047
JSF Parts Validators—Perform correctness checks on UI Input values
Defines a set of standard classes for performing common data validation. Create your own validators or Use standard Tag library which defines a set of tags that correspond to the standard Validator implementations. Register one or more per component Enqueue one or more messages on errors Standard implementations for common cases
1048
JSF Parts Converters Allow a JSF application ( a component)to be associated with an object such as a Java Bean. An application gets and sets the object data for a component by calling the appropriate object properties for that component. Data can be converted from an Object to a String type and passed to the component or Data can be passed to the component in some primitive data type.
1049
JSF Parts Renderers-Adapt components to a specific markup
language Decoding Encoding A component class can be restricted to define the functionality of the component. Rendering can be done by different classes each of defines a different way to render the component to the same client or to different clients. RenderKits—Library of Renderers Map component classes to component tags Is a custom tag library Basic HTML RenderKit
1050
JSF Parts Navigation Model
Defines the sequence by which pages are loaded. It is the application developer’ s responsibility Defined in Application configuration file (faces-config.xml)
1051
JSF Parts Navigation rules in xml style tags i.e.
<navigation-rule> <from-view-id>/greeting.jsp</from-view-id> <navigation-case> <from-outcome>success</from-outcome> <to-view-id>/response.jsp</to-view-id> </navigation-case> </navigation-rule>
1052
JSF-What it does: Drops components onto a page by adding component tags Connect component-generated events to server-side application code Bind UI components on a page, to server-side data Construct a UI with reusable and extensible components Save and restore UI state beyond the life of server requests
1053
JSF-What it does:
1054
JSF-What it does: A client contacts a JSP page that includes Java Server Faces tags. The UI for the web application (represented by myUI in the previous slide) manages the objects referenced by the JSP page. These objects include The UI component objects that map to the tags on the JSP page Any event listeners, validators, and converters that are registered on the components The JavaBeans components that encapsulate the data and application-specific functionality of the components
1055
JSF-Why use it: Need separation between behavior and presentation.
Can not be achieved with just plain JSP. A JSP application cannot map HTTP requests to component-specific event handling nor manage UI elements as stateful objects on the server. JavaServer Faces technology leverages familiar UI-component and web-tier concepts without limiting the developer to a particular scripting technology or markup language.
1056
JSF-Why use it: Relatively easy to use.
Provides Extendable Component and Rendering architecture. Support for client device independence. Has been met with support from the industry.
1057
Contents of a JSF Application
A set of JSP pages (although you are not limited to using JSP pages as your presentation technology) A set of backing beans, which are JavaBeans components that define properties and functions for UI components on a page An application configuration resource file, which defines page navigation rules and configures beans and other custom objects, such as custom components A deployment descriptor (a web.xml file) Possibly a set of custom objects created by the application developer. These objects might include custom components, validators, converters, or listeners. A set of custom tags for representing custom objects on the page
1058
Competitors Struts Struts is a popular MVC framework from the Apache Software Foundation. It provides page-at-a-time MVC and does not have a component model in the style of JSF. Pages are mapped to models with a dispatch servlet (controller) piping input to actions. Struts applications use JSPs to render views and are amenable to mix-and-match jsp taglib use. (See also Apache Beehive)
1059
Competitors Struts has No built-in UI component model
No built-in event model for UI components No built-in state management for UI components No built-in support of multiple renderers
1060
Competitors Microsoft ASP.NET
JSF features a component based approach to WebApplication development similar to ASP.NET from Microsoft. In ASP.NET v1, component rendering code was bundled with the UI component, unlike JSF, where rendering and component interfaces can be separated, thus allowing for customization of the renderer. ASP.NET v2 introduced the control adapter framework allowing the default rendering to be overridden by third-party code.
1061
Competitors Apache Tapestry
Tapestry is an open-source framework for creating dynamic, robust, scalable web applications in Java. Tapestry builds upon the standard Java Servlet API, and so it works in any servlet container or application server. Unlike JSF, Tapestry does not use JSP as the default view technology — instead preferring an alternate templating engine that allows for easy HTML preview and editing (similar to the JSF-based Facelets).
1062
JSF Development Process
Steps in Development Process Develop model objects which hold the data Add model objects (managed bean) declarations to Application Configuration File faces-config.xml Create Pages using UI component and core tags Define Page Navigation in faces-config.xml Configure web.xml
1063
JSF Request Lifecycle Request Processing Lifecycle Phases
Suppose that a JSF component submits a request. The lifecycle of the request (and its data) is: Reconstitute component tree phase (called View) The JavaServer Faces implementation must build the view while considering state saved from a previous submission of the page. Transmits event handlers and validators to components in the view, and saves the view in the FacesContext instance, which contains all the information needed to process a single request.
1064
JSF Request Lifecycle Apply request values phase
Each component in the tree extracts its new value from the request parameters by using its decode method. The value is then stored locally on the component. Process validations phase The JavaServer Faces implementation processes all validators registered on the components in the tree. Update model values phase After the JavaServer Faces implementation determines that the data is valid, it can walk the component tree and set the corresponding server-side object properties to the components’ local values. Those objects can be Java Beans (called backing beans).
1065
JSF Request Lifecycle Invoke application phase Render response phase
Handling of application level events such as submitting a form to the user or redirecting to another resource. Render response phase The JavaServer Faces implementation delegates authority for rendering the page to the JSP container if the application is using JSP pages. The components will render themselves as the JSP container traverses the tags in the page.
1066
JSF Request Lifecycle Parallel Paths in processing
1067
JSF Standard Tag Libraries
A jsp page can include JSF components. To include the JSF components in the jsp file we need to get access to the standard JSF libraries. There are two libraries of JSF tags: JavaServer Faces HTML render kit tag library represent common HTML user interface components. JavaServer Faces core tag library tags that perform core actions and are independent of a particular render kit
1068
JSF Standard Tag Libraries
An example of standard HTML tag is form: <h:form id="jsftags"> ... </h:form> No Renderer is needed Example: <form id="jsftags" method="post" action="/jsftags/faces/pages/tags.jsp" enctype="application/x-www-form-urlencoded"> <input type="hidden" name="jsftags" value="jsftags" /> <input type="hidden" name="jsftags:link" /> </form>
1069
JSF Standard Tag Libraries
Core tag library tags include tags (amongst others): Eventg Handling Data conversion Validation
1070
Using the JSF standard tags
A typical JavaServer Faces page includes the following elements in the jsp file: A set of tag library declarations that declare the two JavaServer Faces tag libraries A view tag A form tag
1071
Using the JSF standard tags
To use any of the JavaServer Faces tags, you need to include these taglib directives at the top of each jsp page containing the tags defined by these tag libraries: taglib uri=" prefix="h" %> taglib uri=" prefix="f" %> The uri attribute value uniquely identifies the TLD (Tag Library Description) document.
1072
Using the JSF standard tags
taglib is a special directive used to indicate that a tag defined in a library will be used. The uri attribute of taglib is used to point to the document file that describes the tag (TLD). A TLD is identified by the extension filename.tld. The document describes the custom tag that becomes part of a library of tags.
1073
Using the JSF standard tags
Here is an example of a taglib descriptor file for a custom library tag saved in file mycustomtag-taglib.tld: <taglib> <info> A simple custom tag </info> <tag> <name>name_to_be_used_when_tag_is_called</name> <tagclass> path_to_class_for_tag_and_classname</tagclass> </tag> </taglib>
1074
Using the JSF standard tags
The TLD document can be placed in some uri or in the same folder as the jsp file if we want (in the server). Notice that a java class is needed that actually implements the tag’ s functionality. The java class extends interface TagSupport and implements method doStartTag() This class is usually placed either in the same folder as the jsp or it becomes part of the library of tags.
1075
Using the JSF standard tags
The prefix attribute value (in the taglib tag in the jsp file) is used to distinguish tags belonging to the tag library. It identifies the tag by name. Each tag will have a different name. The tag names for the standard JSF html tags are defined in file html_basic.tld and recognized by the h prefix attribute of taglib
1076
Using the JSF standard tags
For instance there are a number of tags recognized under the name h in the tld file i.e. h:form id="jsftags"> ... </h:form> usage: <form id="jsftags" method="post" action="/jsftags/faces/pages/tags.jsp" enctype="application/x-www-form-urlencoded"> .. <input type="hidden" name="jsftags" value="jsftags" /> <input type="hidden" name="jsftags:link" /> </form>
1077
Using the JSF standard tags
<h:commandButton id="submit" value="#{msg.buttonHeader}" action="nextPage"> </h:commandButton> <h:inputText id="address" value="#{jsfexample.address}" /> Therefore different type of html components can be called.
1078
Using the JSF standard tags
Core tag library tags are recognized by the f prefix value and are listed in jsf_core.tld file. The view core tag is at root tag for all component views: <f:view> ... other JavaServer Faces tags, possibly mixed with other content ... </f:view> HTML tags will be enclosed in the view tag to create the view: <f:view> <h:form> other JavaServer Faces tags and core tags, including one or more button or hyperlink components for submitting the form </h:form>
1079
Using the JSF standard tags
The Core Tags that are available in Java Server Faces are categorized as follows. Here the categorization is given based on the Functionality of the Tags. They are: Validation Tags Converter Tags Listener Tags View Tags Select Tags Facet Tag Miscellaneous Tags
1080
Using the JSF standard tags- Validation Tags
Bindings between JSF UI Components and Validation Logic can be done with ease with the help of JSF Core Tags. Four JSF Core Tags are available for doing Validation on the JSF UI Components. They are, Validate Length Tag Validate Long Range Tag Validate Double Range Tag Validator Tag
1081
Using the JSF standard tags- Validation Tags
For example, let us use: Validate Length Tag Validation pertaining to Data between Boundaries is a normal requirement for almost any kind of Web Application. For example, a common case includes "Password must be of [8-16] characters length". Validation Length Tag as identified by <f:validateLength> is used to specify the maximum and the minimum characters, a JSF UI Component can accept. Following is the syntax definition of the Validate Length Tag, <f:validateLength minimum = "minRange" maximum = "maxRange"> </f:validateLength>
1082
Using the JSF standard tags- Validation Tags
Here is an example usage: <h:inputText value = "#{UserBean.userName}" id = "userNameTextField" required="true"> <f:validateLength minimum = "10" maximum = "15"/> </h:inputText> In the above code, UserBean refers to a Managed Bean being defined and declared in the web.xml file and userName is the property of the UserBean class. The attribute 'id' of the <h:inputText> specifies the identifier of the Text Field UI Component and it must be unique among the other Components in the Form.
1083
Using the JSF standard tags
Converter Tags Data entered by the Client Application is always interpreted in the form of Strings. Not this is always we wish to have. There will be times, where the user input like age, salary, date of Birth should be represented by Integer, Double and Date objects respectively. Technically, Data is converted into their appropriate types before being processed by the Application. This is where JSF Converters come into picture. JSF implementation already comes with a bunch of Pre-Built Converters for the conversion of string to int, float, boolean etc. Three Tags are available in this category. Convert Number Tag Convert Date Time Tag Converter Tag
1084
Using the JSF standard tags
Listener Tags JSF UI Components emit Events to Listeners if they are registered. The Event Handling Model in Java Server Faces is very similar to Java Beans Event Handling Model. The types of Events emitted will fall either in Action Event, Value-Change Event or Phase Event. For example, clicking a Button or a Hyperlink will cause the JSF Components to emit Action Events. Change in Value for a UI Input Component will make Value Change Events to happen. Phase Events will occur in any of the 6 Different Phases available in Request Processing Life-cycle.
1085
Using the JSF standard tags
Accordingly, 3 Listener Tags are identified for handling the various types of Events we discussed just before. They are mentioned below. Let us cover in detail in the subsequent sections. Action Listener Tag Value Change Listener Tag Phase Listener Tag
1086
Using the JSF standard tags
View Tags View Tags are Container Tags and they used to hold or Group Multiple UI Components. Following are the identified Tags in the JSF Core Library that comes under this category. View Tag Sub View Tag
1087
Study Guide Chapters 9 and 10 EE5 Tutorial. (JSF TECHNOLOGY)
1088
George Koutsogiannakis Spring 2011
CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 24 George Koutsogiannakis Spring 2011
1089
Topics Java Server Faces
Continue from previous lecture- Standard Tags. Using a managed bean. Registering Listeners. Creating a component with an event listener example.
1090
Standard Tags (continued) Example of the View Tag
Following is an example for the View Tag, that holds a Form Component, which in turn is having two Text Components along with a Submit Button. <f:view locale = "ja" beforeMethod = "#{MyPhaseListener.beforePhase}" afterMethod = "#{MyPhaseListener.afterPhase}" > <h:form> <p>User name: <h:inputText value = "#{UserBean.userName}" id = "userNameTextField" required = "true"> </h:inputText> </p> <p>Password: <h:input Secret value = "#{UserBean.password}" id = "passwordTextField" required = "true"> </h:inputText> </p> <h:commandButton value = "Submit" action = "submit"/> </h:form> </f:view>
1091
Standard Tags (continued) Example of the View Tag
In the previous slide the locale is set to Japanse ('ja' is the Locale Code name for Japanese) The Phase Listener interface is used to call before and after through the help of 'beforeMethod' and 'afterMethod' attributes. afterPhase Handle a notification that the processing for a particular phase has just been completed. beforePhase Handle a notification that the processing for a particular phase of the request processing lifecycle is about to begin.
1092
Standard Tags (continued) Example of the View Tag
By phase we mean a phase in the lifecycle of a request (see previous lecture slides). Let us review the lifecycle phases again: Reconstitute Component Tree A JSP page in a JSF application is represented by a component tree. This phase starts the Lifecycle request processing by constructing this tree. Each component tree has an identifier that is unique throughout the application. The identifier of a component tree is the path information portion of the request URI. For a request with the URI /faces/index.jsp, for instance, the tree identifier is /index.jsp. The constructed component tree is then saved in the FacesContext object for processing by the following request processing phases.
1093
Standard Tags (continued) Example of the View Tag
Apply Request Values In this phase, the local value of each component in the component tree is updated from the current request. A value can come from a request parameter, a header, a cookie, and so on. During this phase, a component may queue events. These events will be processed during the process event steps in the request processing lifecycle.
1094
Standard Tags (continued) Example of the View Tag
Process Validations After the local value of each component is updated, in the Process Validations phase, the Lifecycle object will validate those values if necessary. A component that requires validation must provide implementation of the validation logic. Alternatively, a JSF programmer can register zero or more validators with the component. If one or more external validators are found, the local value of each component will be validated using the validation logic in these external validators.
1095
Standard Tags (continued) Example of the View Tag
Update Model Values This phase can be reached only if the local values of all components in the tree are valid. In this phase, the Lifecycle object updates the application’s model data. During this phase, a component may again queue events. Invoke Application During this phase, the JSF implementation handles any application level events, such as submitting a form or linking to another page. Render Response In this phase, the JSF implementation renders the response to the client.
1096
Standard Tags (continued) Example of the SubView Tag
Sub View represents a portion of the Display in the Entire Page. Sub View may be useful in situations where there is a need for a Main Page which is getting information fetched independently from Different Views.
1097
Standard Tags (continued) Example of the SubView Tag
If we wish to represent a portion of a JSP Page as a Sub View, then it has to be embedded into the Sub View Tag with the help of Import/Include Tags : <c:import>, <jsp:include>), and then the Sub View Tag can be embedded within the View Tag. This Tag is identified by <f:subview> and following is the syntax definition for this Tag, <f:subview id = "SubViewId"> </f:subview>
1098
Standard Tags (continued) Example of the SubView Tag
Assume that there is a Web Page contains several sections like Footer, Header and Advertisements along with other contents. Then subview will be one possible solution for such a kind of View Representation. Consider the following sample which illustrates this, <f:view> <f:subview id = "header"> <jsp:include page = "header.jsp"/> <-- Other Elements Here --> </f:subview> <f:subview id = "footer"> <jsp:include page = "footer.jsp"/> <-- Other Elements Here --> </f:subview> <f:subview id = "advertisements"> <jsp:include page = "advertisements.jsp"/> <-- Other Elements Here --> </f:subview> </f:view>
1099
Standard Library Tags-Select tags
These are tags used to select Single or Multiple Entries from Select Components Like List-Box, Check-Box or a Radio-Button. They usually appear as Child Tags under the Select Component Tags and they are used to represent and select Values. The identified Select tags are given as follows. Select Item Tag Select Items Tag
1100
Standard Library Tags-Select tags
Example: <h:selectItem id = "Id" description = "Some Description" itemValue = "itemValue" itemLabel = "itemLabel" value = "selectValue"> </h:selectItem>
1101
Standard Library Tags-Select tags
Another Example: <h:selectManyMenu id = "seasonListBox"> <f:selectItem itemValue = "Summer_Season" itemLabel = "Summer Season"> <f:selectItem itemValue = "Winter_Season" itemLabel = "Winter Season"> <f:selectItem itemValue = "Spring_Season" itemLabel = "Spring Season"> <f:selectItem itemValue = "Autumn_Season" itemLabel = "Autumn Season"> </h:selectManyMenu>
1102
Standard Library Tags-Select tags
The previous code populates a List-Box Component with Values like 'Summer Season', 'Winter Season', 'Spring Season' and 'Autumn Season'. Note that the value corresponding to 'itemLabel' attribute is the one that will be shown to the Clients. The actual value that is sent to the Server is the corresponding value of the attribute 'itemValue'.
1103
Develop model Objects (Managed Bean)
It is the model (M) part in MVC A regular JavaBeans with read/write properties May contain application methods and event handlers Use to hold data from a UI (page) Creation and lifetime is managed by JSF runtime application, session, request JSF keeps the bean's data in sync with the UI
1104
Managed Bean Declaration (faces-config.xml)
<managed-bean-name>LoginFormBean</managed-bean-name> <managed-bean-class> myapp.LoginFormBean </managed-bean-class> <managed-bean-scope>request</managed-bean-scope> </managed-bean>
1105
Create JSF Pages Must include JSF tag library HTML and core tags
All JSF tags must enclosed between a set of view tag Use JSF form and form component tags <h:input_text> not <input type=”text”> <h:command_button> not <input type=”submit”> May include validators and event listeners on any form components
1106
Sample JSF Page (login.jsp)
<f:view> <f:form formName=”logonForm”> <h:panel_grid columns=”2”> <h:output_text value=”Username:”/> <h:input_text id=”userName” length=”16” valueRef=”LoginFormBean.userName”/> <h:output_text value=”Password:”/> <h:input_secret id=”password” length=”16” valueRef=”LoginFormBean.password”/> <h:command_button type=”submit” label=”Log On” actionRef=”LoginFormBean.logon”/> <h:command_button type=”reset” label=”Reset”/> </h:panel_grid> </f:form> </f:view>
1107
Binding UI to Managed Bean
Login.jsp <h:input_text id=”userName” valueRef=”LoginFormBean.userName”/> Faces-config.xml LoginFormBean.java <managed-bean> <managed-bean-name> LoginFormBean </managed-bean-name> <managed-bean-class> myapp.LoginFormBean </managed-bean-class> public class LoginFormBean ... public void setUserName(...) { public String getUserName(...) {
1108
Define Page Navigation Rules (Faces-config.xml)
<from-tree-id>/login.jsp</from-tree-id> <navigation-case> <from-outcome>success</from-outcome> <to-tree-id>/menu.jsp</to-tree-id> </navigation-case> </navigation-rule> <from-outcome>failure</from-outcome> <to-tree-id>/error.jsp</to-tree-id>
1109
Registering Listeners on Components
Listeners can be implemented either as classes The listener id referenced from either a valueChangeListener tag or an actionListener tag and nest the tag inside the component tag or as backing beans The method that implements the listener in the bean is referenced from either the component’s valueChangeListener attribute or its actionListener attribute.
1110
Registering Listeners on Components
The JSF event model is based on the event model defined by the JavaBeans specification. In this model, an event is represented by an instance of an event class. An event source object fires an event by calling an event notification method on event listener objects registered to receive the event, passing a reference to the event object as a notification method argument.
1111
Registering Listeners on Components
Classes that want to be informed about events are called event listeners. They declare which events they are interested in by implementing the corresponding listener interfaces. Hence, an event listener that wants to deal with the ActionEvent fired by a command component declares its intent like this:
1112
Registering Listeners on Components
The following phases of the request lifecycle can queue events in the FacesConext instance associated with the request: Apply Request Values, Process Validations, Update Model Values, Invoke Application Therefore, the JSF implementation must handle these events after these phases. Between two phases, the Lifecycle object checks any event listener that needs to be called. When writing an event listener, you can choose after which phase the listener should be executed. Alternatively, you can write an event listener that is called after various phases.
1113
Registering Listeners on Components
Note that an event listener can change the course of the processing flow by indicating to the Lifecycle object that the processing should jump to the last phase or be terminated immediately after the current event processing.
1114
Registering Listeners on Components
A valueChangeListener tag can be inside a component tag The valueChangeListener tag supports two attributes: type: References the fully qualified class name of a ValueChangeListener implementation binding: References an object ( a backing bean) that implements ValueChangeListener <h:inputText id="name" size="50" value="#{cashier.name}" required="true"> <f:valueChangeListener type="listeners.NameChanged" /> </h:inputText> Component “name” has the listener class “NameChanged” registered with it. The field name in class cashier is set.
1115
Registering Listeners on Components
You can register (bind) a component to a java bean i.e. <h:output_text valueRef=“myBean.result"></h:output_text> valueRef attribute references the bean myBean The UIOutput component :output_text receives its value form the resultproperty of the bean In the code below an ActionListener is registered with the command_button component: <h:command_button id="submitButton" label="Add" commandName="submit" > <f:action_listener type=“listeners.MyActionListener" /> </h:command_button> You must of course write the java code for the listener class.
1116
Creating a component with an event listener example
Suppose that we have a simple jsp application where a form is generated and sent to the client. The form has input fields to accept two numbers and print the result of the addition of the two numbers. There is also a button that, when clicked, fires an ActionEvent and causes an event listener to be executed. The event listener simply prints the names of the components in the component tree.
1117
Creating a component with an event listener example
The page sent to the client has has five user interface (UI) components: a UIForm component, two UIInput components, a UIOutput component, and a UICommand component The UIInput components and the UIOutput component are bound to a JavaBean The bean stores the two input values and contains the logic of the addition.
1118
Creating a component with an event listener example
The request processing lifecycle always begins with the Reconstitute Component Tree phase. In this phase, the Lifecycle object builds the component tree representing the requested page. To be able to draw the tree, you need to create an event listener that will be called during one of the process event steps in the request processing lifecycle.
1119
Creating a component with an event listener example
Our application consists of the following parts: A JSP page named adder.jsp An NumberBean JavaBean for storing user data An action listener called MyActionListener A deployment descriptor (web.xml) An application configuration file for registering the JavaBean faces-config.xml A set of .jar files containing the JSF reference implementation and other libraries should be available ( or if you use NetBeans -they are available)
1120
Creating a component with an event listener example
If we assume that we are going to deploy this application in Tomcat we need a web app directory. The structure of the web app directory is shown on the next slide:
1121
Creating a component with an event listener example
1122
Creating a component with an event listener example
The web.xml file has two important elements in it: <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup> 1 </load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces
1123
Creating a component with an event listener example
The servlet element registers the FacesServlet, and the servlet-mapping element states that any request containing the pattern /faces/ in the URL must be passed to the FacesServlet. FacesServlet is a servlet that manages the request processing lifecycle for web applications that are utilizing JavaServer Faces to construct the user interface. part of package: javax.faces.webapp.FacesServlet
1124
Creating a component with an event listener example
The code for the java bean needs to be created. public class NumberBean { int firstNumber = 0; int secondNumber = 0; public NumberBean () { } public void setFirstNumber(int number) { firstNumber = number; } public int getFirstNumber() { return firstNumber; } public void setSecondNumber(int number) { secondNumber = number; } public int getSecondNumber() { return secondNumber;} public int getResult() { return firstNumber + secondNumber;} }
1125
Creating a component with an event listener example
We can make the bean available to the application by registering it in the application configuration file faces-config.xml: <faces-config> <managed-bean> <managed-bean-name>numberBean</managed-bean-name> <managed-bean-class>ch02a.NumberBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> </faces-config>
1126
Creating a component with an event listener example
The user interface consists of a JSP page called adder.jsp At the top of the jsp file call the taglibs for the html and core standard tag libraries (see previous letcure) <html> <head> <title>Add 2 numbers</title> </head> <body> <f:use_faces> <h:form formName="addForm" > <br/>First Number: <h:input_number id="firstNumber" valueRef="numberBean.firstNumber"/>
1127
Creating a component with an event listener example
<br/>Second Number: <h:input_number id="secondNumber" valueRef="numberBean.secondNumber"/> <br/>Result: <h:output_number id="output" valueRef="NumberBean.result"/> <br/> <h:command_button id="submitButton" label="Add" commandName="submit" > <f:action_listener type="ch02a.MyActionListener" /> </h:command_button> </h:form> </f:use_faces> </body> </html>
1128
Creating a component with an event listener example
Note that JSF controls (components) must be enclosed in the opening and closing elements: <f:use_faces> ... </f:use_faces> Inside these elements, you have a form Inside the form you have: two input_number controls, an output_number control, and a command_button control. The command button is registered with the ActionListener
1129
Creating a component with an event listener example
The component tree of the adder.jsp page
1130
Creating a component with an event listener example-when is event fired?
The last step involves the generation of the code for the ActionListener: MyActionListener. ActionListener uses the ActionEvent class. The FacesEvent class—which all JSF events must extend either directly or through one of the standard subclasses, such as ActionEvent—defines a property named phaseId:
1131
Creating a component with an event listener example-when is event fired?
The phaseId property data type is PhaseId, which is a type-safe enumeration containing one value per request processing lifecycle phase: PhaseId.APPLY_REQUEST_VALUES, PhaseId.PROCESS_VALIDATIONS, PhaseId.UPDATE_MODEL_VALUES, PhaseId.INVOKE_APPLICATION, PhaseId.RENDER_RESPONSE, or PhaseId.ANY_PHASE. The PhaseId.ANY_PHASE value means "process the event in the phase where it was queued," and it's the default value for the phaseId property.
1132
Creating a component with an event listener example-when is event fired?
The UICommand always queues an ActionEvent in the Apply Request Values phase, it also sets the phaseId to PhaseId.INVOKE_APPLICATION to delay the event handling unless you tell it that you want to process it immediately. You do so through a UICommand property called immediate. If immediate is true, the phaseId is left unchanged so the event is processed in the Apply Request Values phase.
1133
Creating a component with an event listener example-when is event fired?
Most of the logic for keeping track of the phase in which an event is to be processed is implemented by the UIViewRoot component that sits at the top of the component tree. At the end of each phase, UIViewRoot goes through the event queue and calls the broadcast() method on all event source components. It starts with all events with phaseId set to PhaseId.ANY_PHASE and then the events queued for the current phase. It continues until there are no more events with these phaseId values in the queue, so if processing one event leads to a new event, the new event is also processed, as long as it's for a matching phase.
1134
Creating a component with an event listener example
Our class MyActionListener then will look like: import javax.faces.event.ActionListener; public class MyActionListener implements ActionListener { ... public void processAction(ActionEvent e) throws AbortProcessingException { Implement the action associated with the event (In our case the drawing of the component tree) ... }
1135
Creating a component with an event listener example
The ActionListener interface extends the javax.faces.event.FacesListener interface and defines one method, taking an ActionEvent instance as the single argument. Here is the definition of the ActionListener interface in the library: public interface ActionListener extends FacesListener { public void processAction(ActionEvent event) throws AbortProcessingException; }
1136
Study Guide EE 5 Tutorial Chapters 9, 10, 11
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.