1 aside: java standards process sun’s original church and state model (now oracle!) church: java...

65
1 Aside: Java standards process Sun’s original church and state model (now Oracle!) 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

Upload: clementine-cobb

Post on 30-Dec-2015

217 views

Category:

Documents


1 download

TRANSCRIPT

1

Aside: Java standards process Sun’s original church and state model (now Oracle!)

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

2

http://www.jcp.org/en/jsr/detail?id=318

3

EXAMPLE OF A COMPONENT-BASED

ARCHITECTURE:JEE OVERVIEW

5

JEE

Stands for “Java, Enterprise Edition”

It is a collection of standards JDBC, JNDI, JMX, JMS

It is a component technology Enterprise JavaBeans`, servlets

It is an “application server” Following in the footsteps of Component Transaction Monitors

6

The JEE Architecture Provides the benefits of components based development for

n-tier applications

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

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)

Servlets and JSP

12

Static HTML Web Server Architecture Web servers where designed to provide web browsers with HTML.

The HTML was read from text files by the server and sent to the client using HTTP. The web server does not modify the HTML. This is now termed static HTML serving

Client Server

Web Browser

Web Server

HTTP Get or Post

HTTP

HTML

files on disk

13

HyperText Transfer Protocol (HTTP)

1) Specify Get / Post

2) Request header

3) Form Data (Parameters)

request

response

1) Status code

2) Response header

3) Content-Type

4) HTML pages / Other files

Web Client Web Server

14

HTML -- Hyper-Text Markup Language

A device independent way to represent documents Specifies the formatting of document

e.g., titles, paragraphs, fonts, colors, lists, tables Hyperlinks permit references to other documents References objects to be inserted into document

e.g., images, applets, frames Forms allow user input

e.g., Text Fields, Buttons, Menus Action causes new HTTP request

15

A simple example of HTML

<HTML><HEAD><TITLE>HTML Reference Library</TITLE></HEAD><BODY><H1>HTML books for everyone</H1<p>HTML library</p><UL><LI>HTML for beginners, Do it yourself!<LI>HTML for experts</UL><H2>Where can i buy it?</H2><Menu><li>IBM book storage </Menu></body></HTML>

16

Requirement for dynamic pages

The Web pages need to be based on data submitted by the user E.g., results page from search engines and order-confirmation pages at on-line

stores

The Web page need to be built from data that changes frequently (E.g., a weather report)

The Web page uses information from databases or other server-side sources for on-line shopping, employee directories, personalized and internationalized

content Web browsers are dumb clients

Not designed to modify web pages Stateless so they process each request in isolation without reference or memory of

what request came before it.

17

Dynamic Web-page Architecture The web page is accessed an external program is run by the web

server. The web server must be able to initiate and communicate with this

program The program generates the HTML and the Web Server passes the

HTML back to the client This process is transparent to the web browser, it does not know it

has been dynamically generated. Common implementations: CGI Common Gateway Interface and

Servlets is another way.

ClientServer

Web Browser

Web Server

HTTP Get or Post

HTTP

Information about the request

External HTML

generatorHTML

18

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

19

Client Server

Servlet Lifecycle I:

Web Browser Web Server

Servlet Container

Servlet

Service

InitHTTP

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

20

Client Server

Servlet Lifecycle II:

Web Browser Web Server

Servlet Container

Servlet

doGet

doPost

Service

Init

Destroy

HTTP

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

21

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)

22

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.

23

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>"); }}

24

Passing a Parameter to Servlets You can pass parameters to the servlet by creating a link to the servlet

and encoding one or more parameters in the link

<a href="http://www.comp.dit.ie:8186/rbradley/servlet/param?p1=hello"> click here for a parameter example! </a>

The servlet can access the parameter called p1 by using the getParameter method in request.

String parameter=request.getParameter("p1");

The name of the parameter

The HttpServletRequest Object

Get parameter always returns a String

The name of the parameter

The value of the parameter

25

Need for scripting

When the balance of the response document is HTML Embed simple code in HTML pages rather than write lots of Java

to create HTML

HTML pages are modified by the code which determines elements and data to display.

Classes and/or subroutines may be called to compute information for inclusion in the web page. Existing APIs can be invoked.

26

Some Approaches to Scripting

JavaServer Pages (JSP)

Active Server Pages (ASP) uses VBScript, Jscript, COM or ActiveX components, ODBC.

ASP.NET Similar to JSP, using C#

PHP C-like syntax, many functions available

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

<%@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

29

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.

30

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

31

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

32

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

33

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

EJB and the EJB Container

35

Enterprise Java Bean(EJB) An enterprise bean is a server-side component that contains

the business logic of an 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

36

Reminder: components, models and frameworks

Interface that satisfies contracts

Component implementation

Component model

Independent deployment

Component-typeSpecific interface

Coordination Services (transactions, persistence..)

ComponentFramework

EJBEJB

EJB container

37

Session Beans Created by a client and exist only for the duration of a

single session Perform operations on behalf of the client inside the

container Transient state: Do not represent data that is stored in a

database. A logical extension of the client

38

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.

39

Entity Bean (up to EJB v3.1)

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

Entity Beans are “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)

Entity Bean(EJB v3.1)

Move away from Entity beans and to use Java Persistence API to support persistence of data

40

41

Message-Driven Bean A message driven bean is an enterprise bean that allows J2EE 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.

42

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

Linking it all together – servlet and EJB communication

44

Linking servlets and EJBs Servlet uses JNDI to find the EJB Client creates or finds EJB Client uses EJB business methods from the component interface JSP example

© IBM

<%@ 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()

Enterprise Services & JEE

Enterprise services

To link applications together a number of additional services are required Naming Transactions Security Management

Common functional requirements for all distributed applications

Typically provided by a centralised server

46

JEE Enterprise Services

These are API definitions for these centralised services 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.

48

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.

49

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”

50

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()

51

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.

52

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

53

Point-to-Point Messaging

Asynchronous RPC Queue - “destination” Producer is a “sender” Consumer is a “receiver”

© IBM

54

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

© IBM

55

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).

56

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

57

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

58

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

59

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

However, bean-managed transaction demarcation (BMT) and client-managed transaction demarcation are also available.

60

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.

61

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

62

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.

63

J2EE 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

64

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

65

Enterprise Service 6: Java Connector Architecture

JCA allows resource adapters that support access to Enterprise Information Systems (EIS) to be plugged into J2EE products Defines a connection management contract between a J2EE

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