background knowledge

Post on 04-Feb-2016

19 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

SEN 972 Java EE Programming Course Introduction Application Server Technology and the Java 2 Enterprise Edition. Background Knowledge. What you need to know: Java It’s not necessary to understand all the different packages - just knowing how to program in it. - PowerPoint PPT Presentation

TRANSCRIPT

1

SEN 972Java EE Programming

Course Introduction

Application Server Technology and the

Java 2 Enterprise Edition

2

Background Knowledge

What you need to know:– Java

It’s not necessary to understand all the different packages - just knowing how to program in it.

– Relational DatabasesBasic understanding, including how tables are related and how to execute transactions using SQL.

– How is your Java Background? Do we need to review some basics?

3

Java EE Programming

Why You’re Here:

• This is some of the hottest technology in the classifieds.

• Experience in Java 2EE (and more importantly, a working understanding of a distributed architecture) will keep you extremely marketable.

4

Application Servers

• What is it?

– A server, similar to a web server, that provides middle tier logic to Enterprise applications.

– They do more then just serve web pages and provide middle layer support for web applications.

5

Application Servers - Example

• A web page with a <submit> button that invokes a Perl script or a Java class could be served by a web server.

• If that Java class used data from an Enterprise database (such as Oracle) and was shared by other applications, this class may be better implemented in an application server, rather then just a web server.

6

Application Server “Technology”

• Various levels of technology exist within an application server.

• Usually N-Tier, meaning there a many transparent client/server relationships working together, to form what appears to the user as a single application.

• HTTP Server

• EJB Server

7

Application Server “Technology”

• JDBCProvides connectivity to databases from Java classes.

• JNDIEnables components to “find” other components within an enterprise system.

• ServletsJava’s answer to traditional CGI, with the advanced ability to stay connected (and persist) in the server between calls.

• JSPJava Server Pages, which allows for embedded Java calls (similar to PHP/C). Used for presentation layer.

8

Application Server “Technology”

• EJBEnterprise Java Beans provide business logic and database connectivity and allow sharing of resources between many different applications.

• RMIAllows separate java applications/layers to communicate with each other. It’s a level above sockets.

• JMSJava messaging is a newer technology in J2EE, providing a publish/subscribe & point-to-point framework.

9

Why Use Java?There are others: VB, C++, Pascal, Prolog, etc...

• Portability (especially for web applications)

• One standard (not like various flavors of C)

• Deployable on all leading web/app servers, with minimal modifications needed when you change servers (java has defined standard API’s/Protocols for server communication)

10

Why Use Java?

• Java provides a single technology for an entire enterprise system(compared to combining for other applications:

CGI/Perl/C, ASP/VBScript, DCOM/C++, etc…)

11

Tech Review

• Clients:– HTML

– Applets

– Java Applications

– VB

– C++

– Delphi

– VBScript

– JavaScript

– PHP

– Cold Fusion

– Flash

12

Tech Review

• Web Servers– HTML

– JSP

– ASP

– Servlets

– PHP

– Cold Fusion

– Perl

– C

– CGI

13

Tech Review

• Databases– Relational Tables– Primary Keys– Foreign Keys– Schemas– Operations (SELECT, INSERT, UPDATE, DELETE)

– Transaction Blocks

14

Client/Serverand

Distributed Systems

An Overview

15

Distributed Systems Overview

• What is a distributed system?– “one in which components located at networked

computers communicate and coordinate their actions by passing messages”

– Most enterprise and web applications fall under the umbrella of distributed systems

16

Distributed Systems Consequences

• Concurrency– work is happening at the same time on different

computers and share resources• No global clock

– all computers on the network do NOT share the same clock or time – no notion of correct time

• Independent failures– faults in a network result in isolation of the computers

that are connected to it– each component can fail independently

• Motivation to construct a distributed system– desire to share resources

17

Examples of Distributed Systems

• Internet – WWW, email, file transfer

• Intranet – firewalls, routers, servers

• Mobile and ubiquitous computing– Laptops– Handheld devices (PDAs, mobile phones, smart

watches, smart appliances)

18

intranet

ISP

desktop computer:

backbone

satellite link

server:

network link:

A Typical Portion of the Internet

19

A Typical Intranet

the rest of

email server

Web server

Desktopcomputers

File server

router/firewall

print and other servers

other servers

print

Local areanetwork

email server

the Internet

20

Portable and Handheld Devices in a Distributed System

Laptop

Mobile

PrinterCamera

Internet

Host intranet Home intranetWAP

Wireless LAN

phone

gateway

Host site

21

Web Servers and Web Browsers

Internet

BrowsersWeb servers

www.google.com

www.cdk3.net

www.w3c.org

Protocols

Activity.html

http://www.w3c.org/Protocols/Activity.html

http://www.google.comlsearch?q=kindberg

http://www.cdk3.net/

File system ofwww.w3c.org

22

Challenges of Distributed Systems

• Heterogeneity– Variety and difference as applied to:

• networks, computer hardware, operating systems, programming languages, implementations by different developers

– Middleware• Software layer that provides a programming abstraction as

well as masking the heterogeneity of the underlying networks, hardware, operating systems, and programming languages

– CORBA (Common Object Request Broker) (www.omg.org)– RMI (Java Remote Invocation) – covered later in the course –

only supports single programming language

– Mobile code• Code sent from one computer to another to run at the

destination (Java applets)

23

Challenges of Distributed Systems

• Openness– Determines whether the system can be extended and re-

implemented in various ways• Degree to which a new resource-sharing service can be added

and be made available for use by a variety of client programs

– Open distributed systems:• have key interfaces published

• have a uniform communication mechanism and published interfaces to shared resources

• are constructed from heterogeneous hardware and software probably from different vendors but all vendors conform to a published standard

24

Challenges of Distributed Systems

• Security– Information resources are of high intrinsic

value to users – security is vitally important! – Must have:

• confidentiality – protection against disclosure to unauthorized individuals

• integrity – protection against alteration or corruption• availability – protection against interference with

the means to access the resources– Denial of service attack, Trojan horse attachment

25

Challenges of Distributed Systems

• Scalability– System is scalable if it will remain effective

when there is a significant increase in the number of resources and the number of users

• i.e. The Internet

– Challenges• Controlling the cost of physical resources• Controlling the performance loss• Preventing software resources from running out• Avoiding performance bottlenecks

26

Challenges of Distributed Systems

• Failure Handling– More failure types can occur in processes and networks

– Failures are partial – some components fail while others continue to function

– Techniques for handling failures:• Detecting failures (checksums)

• Masking failures (retransmit dropped messages)

• Tolerating failures (user keeps trying)

• Recovery from failures (rollback state of component)

• Redundancy (hardware)

27

Challenges of Distributed Systems

• Concurrency– Several clients attempt to access a shared

resource at the same time• Program threads

– Distributed software must be responsible for ensuring that servers and applications operate correctly in a concurrent environment

28

Challenges of Distributed Systems

• Transparency– Concealment from the user and the application

programmer of the separation of components in a distributed system

– System is perceived as a “whole” rather than a collection of independent components

• Programmer only concerned with the design of their particular applications

29

Transparency Forms• Access transparency: enables local and remote resources to

be accessed using identical operations.• Location transparency: enables resources to be accessed

without knowledge of their physical or network location (for example, which building or IP address).

• Concurrency transparency: enables several processes to operate concurrently using shared resources without interference between them.

• Replication transparency: enables multiple instances of resources to be used to increase reliability and performance without knowledge of the replicas by users or application programmers.

30

Transparency Forms

• Failure transparency: enables the concealment of faults, allowing users and application programs to complete their tasks despite the failure of hardware or software components.

• Mobility transparency: allows the movement of resources and clients within a system without affecting the operation of users or programs.

• Performance transparency: allows the system to be reconfigured to improve performance as loads vary.

• Scaling transparency: allows the system and applications to expand in scale without change to the system structure or the application algorithms.

31

The Enterprise

32

Enterprise Framework

• Schema for classifying and organizing the topics related to managing the enterprise

• Assists the organization to become more accountable and responsive

• Shows how enterprise architecture considers the design and operation of an organization from many aspects, perspectives, and disciplines

33

Distributed System Architectures

• Architecture Model – what is it?– Defines the way in which the components of

systems interact with one another– Defines the way in which components are

mapped onto the underlying network of computers

• Decompose architecture of a distributed system into both vertical and horizontal tiers

34

Layers

• Application, operating system, and hardware layers

Layer

Application Layer

Operating System Layer

Hardware Layer

Internet Explorer

Microsoft XP

Dell Inspiron (pentium)

PlatformLayer

Example

35

Tiers – Internet Example

• Three tiers – client, web server, and persistence• Each tier consists of one or more components

that collectively fulfill a common purpose

Client Tier Web-Server Tier Persistence Tier

Internet Explorer Apache Oracle Database

Tier

Example

36

Logical and Physical Tiers

• Physical tiers – Based on the assumption that application

software components found in the different tiers reside on different computers

– Or, on different processors

• Logical tiers– If system deployed on a single computer but

has the separate software tiers

37

Windows XP

Client Tier Web-Server Tier Database Tier

Unix Host Linux Host

Apache Web Server

IEBrowser

OracleDatabase1

*1

1

Windows XP

IEBrowser

Apache Web Server

OracleDatabase

1*

11

Client Tier Web-Server Tier Database Tier

Physical Tiers (3)

Logical Tiers (3)

38

Single Tier Architecture – Student Services Application

The simplicity of single-tier architectures provides a convenient initial framework for subsequently examining more sophisticated multi-tier architectures.

localhost

«Jar»StudentServices

Advisor

Scheduler

package sss.ui

AdvisorPanel

SchedulePanel

package sss.server

FileMgr

package sss.doman

Student

Schedule

«create»

package sss.io

ObjectStream

«create»

LogicalClientTier

LogicalServerTier

LogicalPersistenceTier

Doman is sharedbetween all tiers

Tiers based on common functionality

39

Two-Tier Physical Architecture

The simplified design given in the previous figure can be transformed into a two-tier physical architecture by deploying the classes related to the client aspects of the design on a different host computer from the classes related to the server aspects of the design.

ServerClient

domain

ui ioserver

domain

«import»

«Jar»S3Client

«import»

«Jar»S3Server

«tcp/ip»

40

Three-Tier Physical Architecture

The simplified two tier architecture presented in the previous figure can be transformed into a three-tier physical architecture by separating the handling of persistence in the server tier into its own tier.

DbServerServerClient

domain

ui server

domain

«import»

«Jar»S3Client

«import»

«Jar»S3Server

«tcp/ip» db

Package1

«import»

«Jar»S3Db

«jdbc»

Database replacesfile I/O

41

Multi-Tier Physical Architecture Large Telecommunication’s Company

The key feature of this architecture concerns the fact that any client can communicate with any web server, but these clients cannot directly communicate with other tiers.

Client

Client

Client

Webserver

Webserver

AppServer

AppServer

Client

Webserver

DbServer

DbServer

Legacy

Legacy

42

Middleware

• Software layer that provides an abstract programming interface that hides, via encapsulation, the details associated with heterogeneity in both the layers and tiers of distributed architecture

Layers

Application Layer

Middleware Layer

Platform Layer

Internet Explorer

Distributed ComponentObject Model (DCOM)

MS/Dell

Examples

Firefox Browser

Web Services

Sun Solaris

43

Example – Student Services – EJB as Middleware

• While contemplating the design of the new student services application, you realize that using a middleware platform will result in a more robust application that can be developed in a shorter time.

• A web survey identifies three major middleware contenders: – W3’s Web Services (http://www.w3.org/) – Microsoft’s .Net (http://www.microsoft.com)– Sun’s EJB Application Server (http://java.sun.com)

44

A multi-tier architecture for the student services application utilizing a Java 2 Enterprise Edition (J2EE), Java Enterprise Bean (EJB) & corresponding EJB application server middleware technologies

Example Architecture

Layers

TiersBusiness Logic

S3User Interface

J2EEClient EJB

Microsoft XP(Dell/Pentium)

ClientS3

Server

J2EEEJB App Server

Solaris Unix (Sun)

S3Database

J2EEOracle JDBC

Open Linux(HP)

Persistence

Application

Middleware

Platform

Student uses XP uses MySQL

45

Component Transaction Monitor (CTM)

• Component Transaction Monitor (CTM)– Server-side application that combines the features of a

traditional Transaction Processing Monitors (TPMs) and more recent distributed Object Request Brokers (ORBs)

– TPM – emerged in 1960s at IBM to handle large online transaction processing associated with large systems (i.e., airline reservation system)

– ORB – emerged to support the deployment of objects across a network (i.e, RMI, will study in this class)

46

Object Life Cycle

• Life cycle of an object is the “life” of an object from creation, modification, and deletion– Object instance – not domain data associated with the

application (saved data)

• Factory Design Pattern– Often used to encapsulate the functionality associated

with the life cycle maintenance of an object– This pattern separates the business logic of the domain

being modeled from the object’s life cycle

47

Example: Student Factory in a Distributed System

• Student Factory contains methods for creating, finding, and removing a Student object

+create() : Student+find(in id : int) : Student+findByName(in name : String) : Student+remove(in id : int) : void

StudentFactory

Student

«create»

Student object contains operations associated with the domain application (i.e., addCourse (course))

48

• Factory can be conveniently implemented using a Singleton design pattern as shown in this example

• Hides the actual location of the business object from the user (i.e., two Student objects located on different servers)

Example: Student Factory in a Distributed System using Singleton

+getSingleton() : StudentFactory-StudentFactory()+create() : Student+find(in id : int) : Student+remove(in id : int) : void

-singleton : StudentFactory = new StudentFactory()

StudentFactory

Student

«create»

Given this singleton design, a new Student object can be created using Java:Student aStudent = StudentFactory.getSingleton().create();

49

Persistence Tier

• In multi-tier enterprise architectures, the persistence tier encapsulates the logic for saving data to, and loading data from, persistent storage

• Within a CTM (application) server, enterprise information in the business-logic tier is represented using remote objects.

• As with all objects, a remote object captures state by encapsulating local data as a set of attributes. Consequently, the long-term persistence of an object requires saving its attribute values to non-volatile storage.

50

Persistence Tier

• Examples– Java serialized objects– Local files using XML– Databases

• Design patterns developed to capture the saving of data to files or database– Data Access Object (DAO pattern)

51

Design Patterns

• What is a design pattern?– Patterns provide generic, reusable designs that

solve problems at the design level– Provides a proven, tested solution for a class of

similar design problems– Lend common terminology that you can use to

make your own designs easier to document and understand

• Provides a common “language” for developers to use in meetings and documentation

52

DAO Design Pattern

BusinessObject

+create(in id : int) : BusinessObject+find(in id : int) : BusinessObject+save(in obj : BusinessObject) : void

DataObject

+create(in id : int) : BusinessObject+find(in id : int) : BusinessObject+save(in obj : BusinessObject) : void

«interface»DataAccessObject

PersistenceMgr

«use» «use»

«use»

«instantiate»

Factory

53

DAO Design Pattern

• DAO used to separate business logic aspects of an object from the code used to access persistent storage

• In a distributed system, using a factory to find a remote object does not always require loading the object from persistent storage – it could have been previously loaded and found on the network

• Example – when the Student object is sent a message to “save” itself, the Student will delegate the request via a message sent to a corresponding data access object (DAO)– DAO “knows” how to “save” the object (write it to a particular

database system, i.e., MySQL) and “where” (location of DB)

54

DAO Factory Pattern

DaoFactory

+create() : DataAccessObject

DatabaseDaoFactory

+create() : DataAccessObject

XmlFileDaoFactory

+create(in id : int) : BusinessObject+find(in id : int) : BusinessObject+save(in obj : BusinessObject) : void

«interface»DataAccessObject

+create(in id : int) : BusinessObject+find(in id : int) : BusinessObject+save(in obj : BusinessObject) : void

MySqlDAO

+create(in id : int) : BusinessObject+find(in id : int) : BusinessObject+save(in obj : BusinessObject) : void

XmlDAO

«uses»

«implement» «implement»

«uses»

«instantiate»«instantiate»

BusinessObject«uses»

55

DAO Factory Pattern• A DAO factory pattern is often used to further separate the

application server from the persistence engine. • For example, consider a situation in which data may be

saved either to a relational MySQL database or to an XML file. – Business object, such as student, would request a data access

object from a data access object (DAO) factory. – Since the factory knows which type of persistence is being

used, it returns a data access object (DAO) corresponding to the appropriate persistence engine.

– Specifically, if the application is currently using a MySQL database for persistence, a MySqlDAO object will be returned.

56

Example: Saving a Student

«use»

+getName() : String+setName(in name : String) : void+getPlan() : DegreePlan+setPlan(in p : DegreePlan) : void+getSchedule() : Schedule+setSchedule(in s : Schedule) : void+getStudentId() : int+setStudentId(in id : int) : void+save() : void

-name : String-plan : DegreePlan-schedule : Schedule-studentId : int

Student

+create(in id : int) : Student+find(in id : int) : Student+save(in s : Student) : void

«interface»StudentDAO

+create(in id : int) : Student+find(in id : int) : Student+save(in s : Student) : void

-dbMgr : JDBC

StudentMySqlDAO JDBC

«implements»

«use»

+getStudentDAO() : StudentDAO

MySqlDaoFactory «instantiate»

57

Example: Saving a Student

• Having investigated the benefits of the DAO approach to persistence, you decide to update your Student persistence to utilize a DAO and an associated DAO factory.

• While developing your design, you realize that you’re not exactly sure how the student data access object should be implemented, but remember that JDBC can be used to save Java objects to a relational database.

• So, you have your DAO use JDBC.

58

JDBC

• Java DataBase Connectivity (JDBC) consists of a set of interfaces whose methods can be used to connect to and access data within a relational database using SQL.

• The methods of these JDBC interfaces are defined in the following UML diagram.

59

+createStatement(in sql : String) : Statement+prepareCall(in sql : String) : CallableStatement+prepareStatement(in sql : String) : PreparedStatement

«interface»Connection

+connect(in url : String, in info : Properties) : Connection

«interface»Driver

+executeQuery() : ResultSet+executeUpdate() : int

«interface»Statement

jdbc::Driver

«implements»

+getConnection(in url : String) : Connection

DriverManager

package java.sql

package com.mysql.jdbc

+getFloat(in columnIndex : int) : float+getFloat(in columnName : String) : float+getInt(in columnIndex : int) : int+getInt(in columnName : String) : int+getString(in columnIndex : int) : String+getString(in columnName : String) : String+next() : boolean

«interface»ResultSet

+setFloat(in index : int, in x : float) : void+setInt(in index : int, in x : int) : void+setString(in index : int, in x : String) : void

«interface»PreparedStatement

«interface»CallableStatement

«instantiate»

«instantiate»

«instantiate»

Only a subset of the java.sql interfaces andoperations relevant to the examples foundin this section are displayed in this diagram.

«instantiate»

jdbc::ResultSet jdbc::Connectionjdbc::PreparedStatement

«iimplements»«iimplements»

60

Connecting to the Database• The first step in using JDBC is to load the driver you are using into the JVM. • The following code, which only needs to be executed once, will load the

MySQL driver.

Note: Explicitly loading the driver in this fashion allows you to avoid errors that occur in certain JVMs

try { Class.forName(“com.mysql.jdbc.Driver”).newInstance();

catch (ClassNotFoundException e) { // Class not on the CLASSPATH . . . catch (InstantiationException e) { // Error in the instantiation . . .catch (IllegalAccessException e) { // Security policy violation . . .} // try

61

Connecting to the Database

• The next step is to obtain a connection to the database. • JDBC uses a Uniform Resource Locator (URL) to specify the

information required to establish this connection. The general form of this URL is:– jdbc:<subprotocol>:<subname>

• For example, the URL establishing a connection between a Java application and a MySQL database executing on the same computer is:

"jdbc:mysql://localhost/rubs?user=root&password=dbadmin”

62

Connecting to the Database

• The jdbc token designates that this URL uses the JDBC protocol. • The mysql token indicates that the <subname> adheres to the mysql sub-

protocol, which specifies that a MySQL database named rubs located on the localhost is to be used and that our Java application is logging into this database as the user “root” with a password of “dbadmin”.

String url = "jdbc:mysql://localhost/rubs?user=root&password=dbadmin";

try { Connection dbConn = DriverManager.getConnection(connUrl);

} catch (SQLException e) { . . . // Unknown db or login failed} // try

63

Querying the Database

• Assume the following book table exists in the previous rubs database• The SQL query required to obtain the name and price of the book with id

81763 is:

select name,price from Book where id = 81763;

Id:int Name:varchar Price:float

12294 Pride and Prejudice 7.95

81763 The Little Prince 5.50

64

Querying the Database• The JDBC code required to issue this query to the database begins by first

declaring a prepared statement. • In this prepared statement, the optional arguments of the query are indicated

with a question mark (?). • Once all of the parameters of the statement have been supplied values, the

statement can be executed and the results of this execution will be returned in a result set.

int id = 81763; try { String sqlStmt = “select Name,Price from Book where id = ?”; PreparedStatement stmt = conn.prepareStatement(sqlStmt); stmt.setInt(1, id); ResultSet rs = stmt.execute(); . . .} catch (SQLException e) { . . .} // try

65

Mapping Result Sets to Objects

• If one or more rows in the table were found, the ResultSet’s next() method returns true.

• As book ids are unique, a maximum of one row can be found for the previous query. – Hence, success can be checked with a single if statement (as

opposed to a while loop).

• Once the database row has been obtained from the database, it is necessary to map the data into an object.

• This can easily be accomplished by creating a new instance corresponding to the row and using mutator methods to assign the appropriate values

66

Mapping Result Sets to Objects

if (rs.next()) { Book book = new Book(id);

book.setBook(rs.getString(“Name”)); book.setPrice(rs.getFloat(“Price”));

return book;} else { System.out.printl(“There is no book with id “ + id);} // if

Note: There are a number of more generic ways to accomplish this mapping, however, to keep things simple, they are not be discussed in this course.

67

CRUD Operations

• Create, Update, and Delete operations• Handled by constructing the appropriate SQL

statement and using JDBC to execute the corresponding statement.

• Since no results are expected from these operations, the executeQuery method is not used.

• Instead, the executeUpdate method is used, which returns the number of rows that were successfully created, updated, or deleted.

68

CREATE Row in Table

try { sqlStmt = “insert into Book (id, name, price) values (?, ?, ?)”;

PreparedStatement stmt = conn.prepareStatement(sqlStmt);

stmt.setInt(1, book.getId()); stmt.setString(2, book.getName()); stmt.setFloat(1, book.getPrice()); int rowsInserted = stmt.executeUpdate(sqlStmt);} catch (SQLException e) { . . . } // try

69

DELETE Row in Table

try { sqlStmt = “delete from into Book where is = ?”;

PreparedStatement stmt = conn.prepareStatement(sqlStmt);

stmt.setInt(1, book.getId());

int rowsDeleted = stmt.executeUpdate(sqlStmt);

} catch (SQLException e) { . . . } // try

70

UPDATE Row in Table

try { sqlStmt = “update Book set price = ? where id = ?”;

PreparedStatement stmt = conn.prepareStatement(sqlStmt);

stmt.setPrice(1, newPrice); stmt.setInt(2, book.getId());

int rowsUpdated = stmt.executeUpdate(sqlStmt);

} catch (SQLException e) { . . . } // try

71

End of Lecture 1More Information - Resources

• J2EE Core Patterns (DAO especially)– http://java.sun.com/blueprints/corej2eepatterns/

index.html

• Middleware: A History of Objects, Components, and the Web– http://www.awprofessional.com/articles/article.

asp?p=345781&seqNum=2&rl=1

top related