JEE – components and services

Download Report

Transcript JEE – components and services

JEE Overview
(a.k.a Java Platform
Enterprise Edition)
Java Editions

Java Platform Micro Edition:



Java Platform Standard Edition:


Mobile devices, set-top boxes etc
Restricted form of Java
Core libraries, what most people use in standard Java
programming
Java Platform Enterprise Edition:

Complete server-side enterprise-class development and
deployment platform
2
JEE

Stands for “Java, Enterprise Edition”

It is a collection of standards


It is a component technology


JDBC, JNDI, JMX, JMS
Enterprise JavaBeans
It is an “application server”

Following in the footsteps of Component Transaction Monitors
3
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
4
5
http://www.jcp.org/en/jsr/detail?id=31
6
The JEE Architecture

Provides the benefits of components based development to
Enterprise Application Integration

These components are:


Business logic components:


Enterprise JavaBeans
Presentation logic components



Simpler to develop, portable, reusable
Servlets
JSP
These components are:


Configured via Deployment Descriptors
Deployed into containers
7
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
8
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.
9
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.
10
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)
11
EJB and the EJB
Container
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.
13
Reminder: components, models
and frameworks
Interface that satisfies contracts
Component-type
Specific interface
Independent
deployment
Coordination Services (transactions, persistence..)
Component
implementation
Component
model
Component
Framework
14
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
15
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.
16
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
17
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.
18
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
19

Retains no data or conversational state.
Core services: More later

Container managed persistence




Container managed transactions


Container does database operations automatically
Mapping back to the database is defined in the component’s
“deployment description”
Should work with any database.
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
20
Servlets and JSP
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




Servlets communicate with the browser using only HTML and
HTTP


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.
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
22
Servlet Lifecycle I:
1.
2.
3.
Web browser sends HTTP Post or Get message to Web Server
Web server redirect the request to the servlet. If the servlet is not
already loaded it loads it and calls the servlet's init method
The web browser passes the HTML request to the servlet's service
method
Server
Client
Servlet Container
HTML
Get or Post
Web
Browser
Init
Web Server
Service
Servlet
23
Servlet Lifecycle II:
4.
5.
6.
Service method calls the doGet or doPost method of the servlet
Method executes and generates HTML which is passed back to the web
browser.
Threads in Service method exit
Server
Client
Servlet Container
Init
Web
Browser
Web Server
HTML
Service
Servlet
HTML
HTML
doPost
doGet
Destroy
24
Servlet Lifecycle III:
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)
Server
Client
Servlet Engine
Init
Web
Browser
Web Server
Service
Servlet
doPost
doGet
Destroy
25
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.
26
Worlds simplest Servlet
import 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>");
}
}
27
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
28
Simple JSP Example
Specifies which language
the scriptlets are written in
Java import statement
<%@page language="java" import="java.util.Date" %>
<HTML>
<BODY>
<H1>Welcome to JSP</H1>
<B> Current Time is <%= new Date().toString() %> </B>
</BODY>
</HTML>
Java scriptlet embeds
invocation of method to get
the date as a string
Displays
Welcome to JSP
Current Time is Tue April 24 19:00:55 GMT+00:00 2001
29
Servlet with equivalent functionality
import 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
Outputting of HTML with
{
response.setContentType("text/html");
outprintln() statements is
PrintWriter out = response.getWriter();
awkward.
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();
}
}
30
Choosing JSP or Servlets

JSPs require less initialisation




JSP mixes code into the HTML




Simple things are easier to do in JSP than Servlets
Much harder to debug
Typical of scripts!
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
31
JSP Lifecycle I:
1.
2.
Browser sends a HTTP Get or Post including a URL with a ,jsp extension.
Web server detects .jsp extension in the URL, it delegates the request to
JSP engine.
Server
Client
Servlet Engine
Web
Browser
Servlet
Web Server
JSP Engine
JSP Page
32
JSP Lifecycle II:
3.
4.
The JSP page is translated into a Java Servlet
The generated Servlet is loaded by the Servlet engine and handles the
request
Server
Client
Servlet Engine
Servlet
Web
Browser
Web Server
JSP Engine
JSP Page
33
JSP Lifecycle III:
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
5.


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
Server
Client
Servlet Engine
Servlet
Web
Browser
Web Server
JSP Engine
JSP Page
34
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 object
var 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)
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
37
Example of calling an EJB from a JSP
<%@ page import="javax.naming.*,javax.rmi.PortableRemoteObject,
foo.AccountHome, foo.Account"
Initialise the JSP
%>
<%! AccountHome accHome=null;
Get the reference to
public void jspInit() {
the session bean (EJB)
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(...);
%>
Create an instance of
the session bean
Call the method
doWhatever()
38
JEE: Enterprise Services
JEE Enterprise Services

These are API definitions


Typically allow existing enterprise services to be
accessed easily from Java


The implementation is not specified
Services such as naming, security, messaging etc.
In most cases, these services can be accessed
explicitly or left to the container to interact with.
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.
41
Java Naming and Directory Interface

JNDI is an interface and can utilise different naming services


Reference


DNS, NIS, LDAP
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”
42
Example of calling an EJB from a JSP
<%@ page import="javax.naming.*,javax.rmi.PortableRemoteObject,
foo.AccountHome, foo.Account"
Initialise the JSP
%>
<%! AccountHome accHome=null;
Get the reference to
public void jspInit() {
the session bean (EJB)
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(...);
%>
Create an instance of
the session bean
Call the method
doWhatever()
43
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.
44
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
45
Publish/Subscribe Messaging

Topic – “destination”





Producer is a “publisher”
Consumer is a “subscriber”
Publishers and subscribers
are generally anonymous


Typically associated with a
set of related messages
E.g. IBM stock prices,
weather reports etc
Unless the message
includes the information
Typically “Push” mode


The publisher puts the
message on the queue
The consumer listens for
new messages
© IBM
46
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
47
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
48
Message Nothing: Header fields and properties only. No body.
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).
49
JDBC Code Example
Connect to the DB
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)";
Create the query string
Statement stmt = con.createStatement();
stmt.executeUpdate(createTableCoffees);
Execute query
ResultSet rs = stmt.executeQuery( "SELECT COF_NAME, PRICE FROM
COFFEES");
while (rs.next()) {
String s = rs.getString("COF_NAME");
Execute another query
float n = rs.getFloat("PRICE");
and get return set
System.out.println(s + " " + n);
}
Parse return set into
java variables
50
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
51
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
52
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.
53
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.
54
Security Basics: Terminology

A principal is something that can be authenticated


Each principal has an associated set of security attributes



For example, a user or a server
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
55
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.
56
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


Supports declarative security: defined using deployment descriptors



A principal and one or more roles
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
57
Enterprise Service 5: Java
Authentication and Authorization
Service (JAAS)

JAAS has two purposes:



JAAS authentication is pluggable



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
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
58
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
59