jee overview (a.k.a java platform enterprise edition)
TRANSCRIPT
2
Java Editions
Java Platform Micro Edition: Mobile devices, set-top boxes etc Restricted form of Java
Java Platform Standard Edition: Core libraries, what most people use in standard Java
programming
Java Platform Enterprise Edition: Complete server-side enterprise-class development and
deployment platform
3
JEE
Stands for “Java, Enterprise Edition”
It is a collection of standards JDBC, JNDI, JMX, JMS
It is a component technology Enterprise JavaBeans
It is an “application server” Following in the footsteps of Component Transaction Monitors
4
Aside: Java standards process The original model: Sun’s church and state model
Church: Java community process State: Sun commercial business
Java Community Process www.jcp.org Java Service Request (JSR)
Unique id often used to describe pre-standards or recent standards. e.g. JSR 168 is the Portlet specification
Test suite required for compliance Reference implementation
Works but not much more
7
The JEE Architecture Provides the benefits of components based development to
Enterprise Application Integration
These components are: Simpler to develop, portable, reusable
Business logic components: Enterprise JavaBeans
Presentation logic components Servlets JSP
These components are: Configured via Deployment Descriptors Deployed into containers
8
JEE Components Application clients and applets run on the client Java Servlet and JavaServer Pages (JSP ) are
presentation layer components that run on the presentation server
Enterprise JavaBeans (EJB ) components represent business components and run on the business logic server
JEE components are written in Java in the same way ordinary Java programs are created
All JEE components are deployed into containers Containers provide components with services such
as life cycle management, security, deployment, and threading
9
Client-tier/web-tier Components Client can communicate with the application logic tier either
directly or through servlets or JSP that are located in the presentation tier.
Servlets are special classes to realise the request-response model (get, post of HTTP). JSP is a developer-friendly html-friendly wrapper over the
servlet classes.
Javascript is a client-side scripting language which runs in the browser Javascript is not part of JEE. Javascript could be generated by a servlet or JSP.
10
Application logic tier Components
This is defined by the logic that pertains to the (business) application that is being developed.
Enterprise Java Beans (EJB) can be used to implement this tier.
This tier receives the data from the client-tier and processes the data and sends it to the RM-tier and takes the data from the RM and sends it to the client-tier.
11
Resource Management System
In general this corresponds to the database (relational database) and other information management system.
The other information management systems may include Enterprise Resource Planning (ERP) and legacy system connected through open database connectivity.
Or through the Java Connector Architecture (JCA)
13
Enterprise Java Bean(EJB) An enterprise bean is a server-side component that contains the
business logic of an application.
Main goal of Enterprise Java Bean (EJB) architecture is to free the application developer from having to deal with the system level aspects of an application. This allows the bean developer to focus solely on the logic of the application.
At run-time, an enterprise bean resides in an EJB container.
An EJB container provides the deployment environment and runtime environment for enterprise beans including services such as security, transaction, deployment, concurrency etc. EJB container provides services to bean and manages its life cycle
Process of installing an EJB in a container is called EJB deployment.
14
Reminder: components, models and frameworks
Interface that satisfies contracts
Component implementation
Component model
Independent deployment
Component-typeSpecific interface
Coordination Services (transactions, persistence..)
ComponentFramework
15
Types of Enterprise Beans Entity Beans:
Entity beans represent the business objects that need persistence (need to be stored in a database.)
Represents persistent data in a database, as well as methods that act on that data
Session Beans: Created by a client and exist only for the duration of a single session Perform operations on behalf of the client such as reading, writing, or updating a
database; Transient state: Do not represent data that is stored in a database. A logical extension of the client
16
Session Beans
Simple and easy to program.
For transient functions such as controller Represents “conversational” state Typically one per request Data is non-persistent Lifetime is limited by the client’s: once the client exits,
the session bean and data are gone.
Light-weight.
17
Entity Bean “Transactional” in behavior
Can be shared among clients
Persistent: data exists permanently after client quits. E.g. Corresponds to a row a relational database.
The persistence (storing into the database) can be automatically done by the “container” (CMP) or explicitly by the bean (BMP)
NB: Entity beans under-review since JEE v1.5 and EJB3.0 onwards uses Java Persistence framework as an alternative Many developers prefer “light-weight” frameworks such as hibernate or
the Java Persistence framework instead of the “heavier” EJB entity bean
18
Choosing Entity or Session Bean
Entity (business entity) is typically implemented as entity bean or a dependent object of an entity bean.
Conversational (business) process as a session bean. Collaborative bean as an entity bean. Any process that requires persistence is implemented as an
entity bean. When exposure to other applications are not needed for an
entity or process (local/private process) then they are implemented as bean dependent objects.
19
Message-Driven Bean A message driven bean is an enterprise bean that allows JEE applications to
process messages asynchronously. Common mode of communication in enterprise applications
It acts as a listener – for messages sent by any other system or component via a JMS messaging system
Retains no data or conversational state.
20
Core services: More later Container managed persistence
Container does database operations automatically Mapping back to the database is defined in the component’s
“deployment description” Should work with any database.
Container managed transactions One transaction per method call to EJB
Container managed security EJB-container manages roles Rights are applied per role to EJB EJB can check permissions by using API provided by container
22
Servlets
Servlets are programs written in Java which run on the web server and communicate using with the web browser using HTTP and HTML
The servlet runs inside a container called a Servlet Engine The communication services, security etc are provided by the container Container runs within the JVM Hides coding issues around with Sockets, TCP/IP or Java serialisation.
Servlets communicate with the browser using only HTML and HTTP Compatible with all web browsers
Servlets run only on the server Servlets do not need any component to be stored or installed on the
client
23
Client Server
Servlet Lifecycle I:
Web Browser Web Server
Servlet Container
Servlet
Service
InitHTML
Get or Post
1. Web browser sends HTTP Post or Get message to Web Server2. Web server redirect the request to the servlet. If the servlet is not
already loaded it loads it and calls the servlet's init method3. The web browser passes the HTML request to the servlet's service
method
24
Client Server
Servlet Lifecycle II:
Web Browser Web Server
Servlet Container
Servlet
doGet
doPost
Service
Init
Destroy
HTML
HTML HTML
4. Service method calls the doGet or doPost method of the servlet5. Method executes and generates HTML which is passed back to the web
browser.6. Threads in Service method exit
25
Client Server
Servlet Lifecycle III:
Web Browser Web Server
Servlet Engine
Servlet
doGet
doPost
Service
Init
Destroy
4. When the servlet container decides to unload the servlet it calls the destroy method
At shutdown or if memory is short Will not happen until all active threads finish (exit or time out)
26
Writing a Servlet
All Servlets extend the Servlet class Normally extends HttpServlet which is derived from Servlet class
HttpServlet class provides default implementations of Init: Need to override if some additional initialisation required such
as open a database connection. Destroy: Need to override if some additional cleaning up required
such as closing a database connection. Service: Not normally be overridden doGet: Normally over-ridden as HTTP Get is the default web
browser request which causes the doGet method of the servlet to be invoked.
doPost: Over-ridden if HTTP Post is responded to.
27
Worlds simplest Servletimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;
public class HelloWorldExample 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 bgcolor=\"white\">"); out.println("<h1>Hello World!</h1>"); out.println("</body>"); out.println("</html>"); }}
28
What are JSPs?
JSPs are design time entities which are converted into servlets when loaded by the web server
JSPs look much more like standard HTML pages Code is contained within <% %> markers and are referred to a scriptlets
Each JSP page states which programming language is contained within its scriplets <%@page language="java" %> While theoretically it can be any language, in practice the language is
normally Java
29
Simple JSP Example
<%@page language="java" import="java.util.Date" %><HTML><BODY><H1>Welcome to JSP</H1>
<B> Current Time is <%= new Date().toString() %> </B></BODY></HTML>
Welcome to JSP
Current Time is Tue April 24 19:00:55 GMT+00:00 2001
Welcome to JSP
Current Time is Tue April 24 19:00:55 GMT+00:00 2001
Specifies which language the scriptlets are written in
Java import statement
Java scriptlet embeds invocation of method to get the date as a string
Displays
30
Servlet with equivalent functionalityimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;Import java.util.Date;
public class ServWelcome 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("<BODY>"); out.println("<H1>Welcome to Servlets</H1>");
out.println(" <B>Current Time is "+ new Date().toString()+"</B>); out.println("</BODY>"); out.println("</HTML>"); out.close(); }}
Outputting of HTML with outprintln() statements is awkward.
31
Choosing JSP or Servlets
JSPs require less initialisation Simple things are easier to do in JSP than Servlets Much harder to debug Typical of scripts!
JSP mixes code into the HTML Best for lots of HTML (avoids the need to write lots of out.println("..")) and less Java
code Large JSP pages can be difficult to find and read the code Debugging JSP is difficult because the code is translated into another form (servlet)
before being run
Servlets mix HTML into the code Large servlets can be difficult to find and read the HTML Best for little HTML output and lots of Java code
32
Client Server
JSP Lifecycle I:
Web Browser Web Server
Servlet Engine
Servlet
1. Browser sends a HTTP Get or Post including a URL with a ,jsp extension.2. Web server detects .jsp extension in the URL, it delegates the request to
JSP engine.
JSP Engine
JSP Page
33
ClientServer
JSP Lifecycle II:
Web Browser
Web Server
Servlet Engine
Servlet
3. The JSP page is translated into a Java Servlet4. The generated Servlet is loaded by the Servlet engine and handles the
request
JSP Engine
JSP Page
34
ClientServer
JSP Lifecycle III:
Web Browser
Web Server
Servlet Engine
Servlet
5. Translation and compilation takes place only when the JSP is called first time or when it is modified. All subsequent requests are handled by the Servlet generated
There is a slight delay in response first time due to translation and compilation phase If there are any changes, Java/HTML page recompiles automatically
JSP Engine
JSP Page
JSP and Javascript
Javascript is defined between the following html tags:<script language=“JavaScript”>alert (“Welcome to the Test Site!”);</script>
Therefore, a JSP or servlet could define a html page which includes some Javascript.
AJAX and dynamic web-pages
A common programming technique for dynamic web-pages is AJAX Asynchronous JavaScript And XML
The Javascript creates a XMLHttpRequest objectvar request = new XMLHttpRequest();
This is then used to listen for or send messages to the server Allows easy updating of parts of a web-page which change
rapidly (e.g. stock prices)
37
Linking servlets and EJBs
Servlet uses JNDI to find the EJB container Client connects to the EJB container EJB container routes the message to the appropriate
EJB Client uses EJB methods from the component interface
© IBM
38
Example of calling an EJB from a JSP
<%@ page import="javax.naming.*,javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account"
%>
<%! AccountHome accHome=null; public void jspInit() { InitialContext cntxt = new InitialContext( ); Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class); }
%>
<% Account acct = accHome.create(); acct.doWhatever(...);
%>
Initialise the JSP
Get the reference to the session bean (EJB)
Create an instance of the session bean
Call the method doWhatever()
JEE Enterprise Services
These are API definitions The implementation is not specified
Typically allow existing enterprise services to be accessed easily from Java Services such as naming, security, messaging etc.
In most cases, these services can be accessed explicitly or left to the container to interact with.
41
Enterprise Service 1:Naming and Directory Services
Naming and Directory Services allow Allows an application to find the resources its needs Allows searching for components based on name or attribute
Terminology: A name is “Test Topic” (JMS topic) “www.ibm.com” (DNS address) “/usr/local/java/bin/javac” (File name)
Terminology: Binding is Associating a name with an object.
42
Java Naming and Directory Interface
JNDI is an interface and can utilise different naming services DNS, NIS, LDAP
Reference Compact object representation, with information about how to
access the object
Context A context is a set of name-to-object bindings, with an associated
naming convention. E.g. Unix naming convention, “/abc/def”
43
Example of calling an EJB from a JSP
<%@ page import="javax.naming.*,javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account"
%>
<%! AccountHome accHome=null; public void jspInit() { InitialContext cntxt = new InitialContext( ); Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class); }
%>
<% Account acct = accHome.create(); acct.doWhatever(...);
%>
Initialise the JSP
Get the reference to the session bean (EJB)
Create an instance of the session bean
Call the method doWhatever()
44
Enterprise Service 2:JMS - The Java Messaging Service
A Java API that allows applications to create, send, receive, and read messages Interface specification only No vendor interoperability Vendor-agnostic: the same API to access different MOM
vendors.
Two Domains Publish/Subscribe
Use pub/sub messaging when each message can be processed by zero, one, or many consumers.
Point-to-Point Use when every message must be processed successfully by one
consumer.
45
What is messaging?
“e-mail for applications”
Asynchronous communication The sender and receiver do not have to be available at the same time in
order to communicate.
Loosely coupled The sender does not need to know anything about the receiver, nor does
the receiver need to know anything about the sender; they only need to know what message format and what destination to use.
Enterprise messaging requires additional Qualities of Service Guaranteed delivery and fault tolerance Load balancing Scalability Transactional support
46
Publish/Subscribe Messaging Topic – “destination”
Typically associated with a set of related messages
E.g. IBM stock prices, weather reports etc
Producer is a “publisher” Consumer is a “subscriber” Publishers and subscribers are
generally anonymous Unless the message includes the
information Typically “Push” mode
The publisher puts the message on the queue
The consumer listens for new messages
© IBM
47
Point-to-Point Messaging
Asynchronous RPC Queue - “destination” Producer is a “sender” Consumer is a “receiver” “Pull” mode
Consumer must retrieve message And may send an acknowledgement
© IBM
48
Examples of JMS Configuration
JMS Message: Headers + Properties + Payload Headers include:
JMSDestination JMSExpiration, JMSPriority, JMSTimestamp, JMSCorrelationID (Allows messages to be connected logically) JMSReplyTo (Identifies source)
Message Types TextMessage: A string (for example, the contents of an XML file) MapMessage: A set of name-value pairs BytesMessage A stream of uninterpreted bytes (A “blob”). StreamMessage: Primitive values in the Java programming language. ObjectMessage: Serialized Java object Message Nothing: Header fields and properties only. No body.
49
Enterprise Service 3: JDBC
JDBC is the Java API that provides vendor independent connectivity to relational databases
JDBC functionality provides basic connectivity and core database-related classes
The Standard Extension provides additional functionality JNDI can be used to manage data sources and connections Connection pooling provided by database vendors to enhance
performance Support for distributed transactions, including support for the
standard two phase commit protocol used by the Java Transaction API (JTA).
50
JDBC Code Example
Connection con = DriverManager.getConnection(url, "myLogin", "myPassword");
String createTableCoffees = "CREATE TABLE COFFEES " + "(COF_NAME VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT, " + "SALES INTEGER, TOTAL INTEGER)"; Statement stmt = con.createStatement(); stmt.executeUpdate(createTableCoffees);
ResultSet rs = stmt.executeQuery( "SELECT COF_NAME, PRICE FROM COFFEES"); while (rs.next()) {
String s = rs.getString("COF_NAME"); float n = rs.getFloat("PRICE"); System.out.println(s + " " + n);
}
Connect to the DB
Create the query string
Execute query
Execute another query and get return set
Parse return set into java variables
51
Enterprise Service 4: Transactions
A transaction is a set of operations that moves data from one consistent state to another
The set of operations is considered indivisible If one or more operations fail, the entire set is undone
Success: the transaction "commits" Failure: the transaction "rolls back"
The effects of a committed transaction are persistent
Transactional Client: A program which invokes methods on transactional objects
Transaction Manager: A program that coordinates transaction processing
52
Java Transaction API (JTA)
JTA is used by application developers Specifies the interface between the transaction manager
and all involved objects Main class: the UserTransaction interface.
Java Transaction Service (JTS) is used by developers of transaction managers Developers of application servers, EJB containers, etc.
Very few people in the world! Not used by application developers
53
Transactions and EJBs
Transactionality can be handled implicitly by the container Container-managed transaction demarcation (CMT)
The EJB container manages transactions automatically Interaction with databases
Including two-phase commit (2PC) for databases with JDBC drivers that support XA
Starting and ending transactions Creating and propagating the transaction context
Configurable through the deployment descriptor (pre- JEE5) or annotations (JEE5)
However, bean-managed transaction demarcation (BMT) and client-managed transaction demarcation are also available.
54
Security Basics: Authentication and Authorization
Proof Of Identity (Authentication) Verifies the identity of the user, by using
Shared secret (password) Token (Kerberos Ticket or RSA Public Key)
Grant of Access (Authorization) Identity verified, system has to decide what resources (data,
applications etc) the user should be allowed access, based on time of day, IP address etc.
Usually defined on the basis of roles Each user may have many roles Each role has predefined access attributes E.g. a user may have two roles of system admin and pay-roll
admin. In the second role, the user can execute the pay-roll software.
55
Security Basics: Terminology
A principal is something that can be authenticated For example, a user or a server
Each principal has an associated set of security attributes Used to identify which resources the principal can access Also used for auditing
A principal is identified using credentials A credential contains or references security attributes Credentials are acquired via authentication Credentials can also be acquired through delegation from
another principal
56
Challenges of distributed security
Perimeter security is only the start Primarily focused on external attack Internal security focuses on auditing and policing good
behaviour.
Need to ensure authentication can be achieved securely Single sign-on or passing around of authentication data.
Each task must be associated with a principal with valid credentials and authorisations.
Across multiple domains, systems and applications.
57
JEE Container-Based Security
Security for components is provided by the container in which they run
When an EJB method is invoked, it is always with a given security identity A principal and one or more roles
Supports declarative security: defined using deployment descriptors Includes definition of security roles, access control rules and
authentication requirements Mapped by the application deployer to the specific runtime environment
Supports programmatic security: explicit use of security APIs by application code Provides increased flexibility
e.g., the same method can function differently for different pricipals
58
Enterprise Service 5: Java Authentication and Authorization Service (JAAS)
JAAS has two purposes: Authentication of users, to reliably and securely determine who is
currently executing Java code, regardless of how the code is running
Authorization of users to ensure they have the permissions required to do the actions performed
JAAS authentication is pluggable Different underlying authentication technologies can be used
transparently to the client. Usually implemented on Identity Servers.
JAAS authorization extends the existing Java security architecture Role based access control - based not just on what code is
running, but also on who is running it
59
Enterprise Service 6: Java Connector Architecture
JCA allows resource adapters that support access to Enterprise Information Systems (EIS) to be plugged into JEE products Defines a connection management contract between a JEE
server and a resource adapter to allow connection pooling to EIS systems
A transaction management contract between the transaction manager and an EIS that supports transactional access Also supports transactions that are managed entirely by an
EIS. A security contract that enables secure access to an EIS