Presentation is loading. Please wait.

Presentation is loading. Please wait.

J2EE Architecture, System Qualities and Design Patterns

Similar presentations


Presentation on theme: "J2EE Architecture, System Qualities and Design Patterns"— Presentation transcript:

1 J2EE Architecture, System Qualities and Design Patterns
Enterprise Java Architect Sun Java Center

2 Agenda J2EE Architecture Fundamentals J2EE system Qualities
J2EE Design Pattern

3 What is J2EETM? Built on JavaTM 2 SDK
J2EE is component based application Framework J2EE specifies a set of API for Enterprise Development J2EE platform provides a set of Services Development, Deployment, and Management J2EE specifies Distributed, Server-Centric Applications Architecture Blueprint J2EE is a platform for developing, deploying, and managing multi-tier, server centric applications. J2SE == JDK

4 J2EE Platform Architecture

5 Component Based Framework
Component A component is an application level software unit. The J2EE platform supports the following types of components: Applets, Application clients, EJB and Web components (in addition to J2SE) Container All J2EE components depend on the runtime support of a system-level entity called a container. Containers provide components with services such as life cycle management, security, deployment, and Transaction

6 J2EE API Database: JDBC Directory:JNDI Transaction JTA,JTS
Mail: Java Mail Messaging: JMS Communication: RMI Server-Side Component: EJB Presentation-Side: Servlet, JSP Legacy Connector: Connector

7 Deployment Services J2EE deployment services allow components and applications to be customized at the time they are packaged and deployed. A J2EE application consists of one or more J2EE modules and one J2EE application deployment descriptor (EAR file) A J2EE module consists of one or more J2EE components and one deployment descriptor of that component type.

8 Transaction Services The J2EE platform handles many transaction details, such as propagating and coordinating among multiple transaction managers. Web components are not designed to be transactional (can demarcate). Transactions are propagated from a Web component to an enterprise bean only when the Web component starts the transaction.

9 Security Services Authentication--An entity must establish its identity through authentication. It typically does so by providing authentication data Authorization--When an authenticated principal tries to access a resource, the system determines whether the principal is authorized to do so based on the security policies in force in the application's security policy domain.

10 J2EE App Architecture BluePrint

11 Agenda J2EE Architecture Fundamentals J2EE System Qualities
J2EE Design Pattern

12 Qualities of J2EE Architecture
Scalability – Scalability relates to the ability for an e-commerce site to add capacity and thus add users over time. Scalability will usually require the addition of resources, but scalability should not require changes in the architecture, code to scale. Reliability —System reliability describes the likelihood of any component failures. Availability —The percentage of time that the system is available for use.

13 Qualities of J2EE System
Maintainability –How easy it is to monitor, upgrade and configure a system. Securibility – Includes the levels of authentication, authorization, audibility supported. Performance - relates both to the specific performance metrics (e.g., responsiveness, latency) and the users expectations about performance.

14 Scalability Bigger Boxes – Provides More capability.
Pipeline – Applies more processing power during a unit of time. Load Banancing Router- Handles all requests and distributes them among the replicated servers

15 Availability and Reliability
Better Boxes – Ensure that an appropriate level of reliability and availability is provided from the hardware Cluster - Involves the provision of ensembles of hardware resources, externally visible as a single resource, no noticeable loss of service is experienced.

16

17 Maintainability Thin Client or Fat client with web start – Enables access devices to be treated as disposable assets entirely in the control of the end user. Wrappering – Provides external systems and software with nonstandard interfaces with given standardized interfaces that conform to the rest of the system being built Centralized control, configuration and management

18 Performance - General Procedure
Understand Application Architecture Replicate Runtime Production Environment Establish Meaningful Metrics Execute Steps to Isolate Bottlenecks Review Data Gathered in Metrics and Take Corrective Action Create a Report Describing Findings and Lessons Learned

19 Application Performance tuning
Keep your servlet session object small Reuse session EJB handler Reuse all datasource Object Use DB Connection Pool Turn off all “System.out.print()” Always use PrepareStatement for JDBC Avoid Memory Leak in Collection Object

20 Application Performance tuning
Avoid Type Casting Avoid Use of Reflection Use the right type JDBC Connector Use coarse granularity Object if networking involves Always minimize the web response size Always set the response size if possible

21 Platform parameter tuning
Http – Keep Alive TCP/IP – wait_Time_Interval Different Encoding schema between Application and platform Native IO driver instead pure Java Drive Thread Model – Native Thread, alternative thread lib(solaris) Data Source Pool size

22 VM Performance Tuning How garbage collection works Hotspot VM tuning

23 How Garbage collection works?
Young Generation Eden, SurvivorX2 space Old Generation perm

24 Object migration thru ‘Spaces’
When an Object is first created, it is allocated in the Eden Space When Eden space fills up, a garbage collection occurs (GC). Objects that are reachable are copied to one of survivor space If survivor space fills up, a Full GC occurs. A Full GC will tenure Objects from survivor to the perm space, collect all unreachable objects in the perm space, Eden space and survivor space. Then do what GC will do.

25 How to observe Garbage Collector?
Use the VM command line switch -verbose:gc IMPORTANT: All threads in the JVM block while garbage collection is running. Example output: [GC 1868K->1445K(1984K), secs] [GC 1957K->1506K(1984K), secs] [Full GC 2018K->1218K(2608K), secs]

26 HotSpot VM Tuning Unless you have problems with pauses, try granting as much memory as possible to the JVM.  The default size 64MB is too small for server side application Set the maximum heap size to 25% larger than the largest amount memory used by the application under a load test. set minimum and maximum heap sizes to the same Set young generation 25% of the max heap. Always use –server as first arguments for Server side application

27 Security Client tier Security Communication Security
J2EE Security Services

28 Thin Client tier Security
HTML hidden variables – Don’t use hidden variables to keep sensitive information Parameter Tampering – Parameters sent to the server can be tampered legal clients Client side user validation – Only for performance and user friendly. Server side app should never trust the client side user validation GET vs. Post – Always use Post Cookies – Cookie can be used to track the client activities, the content of Cookie can be exposed to the third party

29 Communication Security
Authentication – Establishes the identity between the client and the server side Authorization – Determine what the authenticated identity can do Confidentiality-Message is only read by intended recipient Integrity - Message sent is the message received Nonrepudiation – Provides a way to prove that certain principal sent or received a particular message

30 J2EE Security - GOAL Supports security application deployments without relying on private networks environments. Minimizes the application developer’s responsibility and delegate the responsibility to the more qualified security administrator Be policy driven and requires no application code

31 How to get J2EE Security Services?
Defines Security Identity using deployment tools Defines Authentication policy in web.xml Defines Authorization Policy for Web Tier in web.xml Defines Authorization Policy for EJB Tier in ejb-jar.xml

32 J2EE security Identity User – Legal identity that is allowed to access system. Group – Global Categories of users for enterprise Role - An application specific type of group defined by application assembler.

33 J2EE security identity (cont.)

34 J2EE Authentication HTTP Basic Authentication – Web server authenticate user by ID and Password Form-based Authentication – Servlet Engine authenticate user by ID and password and store security context in Cookie and server container. Key tech to single sign-on and declarative security Customize Basic Authentication – Application programmatically authenticate user ID and Password Client-certificate Authentication – Authenticate client side by client certificate

35 WEB Tier Authorization Policy Sample
<security-constraint id=“supervisor"> <web-resource-collection id=“Super_Res_1"> <web-resource-name> Super_Res</web-resource-name> <url-pattern>/Supervisor</url-pattern> <url-pattern>/Manager</url-pattern> <http-method>POST</http-method> </web-resource-collection> <auth-constraint id="AuthConstraint_1"> <description>ManagerSecuirty</description> <role-name>supervisor</role-name> </auth-constraint> </security-constraint>

36 Roles AccountBean. getBanance() setBalance() Teller Yes No supervisor
EJB Tier Authorization Example Roles AccountBean. getBanance() setBalance() Teller Yes No supervisor

37 Declarative Security Containers intercept requests/method invocations, enforce security policy Access security policy is declared at deployment Not embedded in code Flexible, just change and redeploy

38 Programmatic Security
For custom security functionality not provided by declarative security Determine the principle associated with a request HttpServletRequest.getUserPrinciple() EJBContext.getCallerPrinciple() Determine if the caller/user is in the specified role HttpServletRequest.isUserInRole() EJBContext.isCallerInRole()

39 Case Study Web Page: Search by Transaction Number Transaction:
Server Object create SQL as: Select * from tranTable where tranID= ; 123456

40 Case Study (Cont.) Web Page: Search by Transaction Number Transaction:
Server Object create SQL as: Select * from tranTbl where transactionID= ; Drop Table TranTbl; 123456;drop table tranTbl;

41 Agenda J2EE Architecture Fundamentals J2EE System Qualities
J2EE Design Pattern

42 What are Patterns? Patterns are about communicating problems and solutions Recurring problems within a context Expert solutions Patterns originated as a field of study in brick and mortar architecture as a result of the work done by Christopher Alexander. He has numerous books on patterns, but only became aware of the software industry’s interest in his work in the last decade.

43 J2EETM Design Patterns Based on experience in SJC
Collection of best practices The Java Center has approximately 300 architects worldwide.

44 J2EE Patterns Partitioning
Presentation Tier a.k.a. Web Tier Building application's presentation Business Tier a.k.a. Enterprise JavaBeansTM (EJB TM) Tier Contains business logic Business processing and data access Integration Tier a.k.a. EIS Tier Integration of J2EE code with legacy systems / applications

45 Presentation-Tier Patterns
Intercepting Filter <---- Front Controller View Helper Composite View Dispatcher View Service To Worker

46 Intercepting Filter Problem: Forces:
Preprocessing and post-processing of a client web request and response are required Forces: Centralization of common logic Processing components should be easily added and removed

47 Intercepting Filter : Solution
When a request enters a Web application, it often must pass several entrance tests prior to the main processing stage. For example: • Has the client been authenticated? • Does the client have a valid session? • Does the request path violate any constraints? • What encoding does the client use to send the data? • Do we support the browser type of the client? Common examples of Pre-processing: Decompressing incoming stream Decrypting incoming stream Translating encoding scheme to a common format Authenticating a request Common examples of Post-processing: Compressing outgoing stream Encrypting outgoing stream Translating outgoing stream for delivery to different client devices (XML, HTML, WML)

48 Intercepting Filter : Class Diagram

49 Presentation-Tier Patterns
Intercepting Filter Front Controller <---- View Helper Composite View Dispatcher View Service To Worker

50 Front Controller Pattern
Problem: There is no centralized access point for presentation request handling Forces There is common processing that is performed across requests. Common logic is duplicated in numerous views Need to perform Request handling Data access View management Navigation and Dispatch The real issue is that of centralizing or decentralizing control of the request handling process.

51 Front Controller: Solution
Use a FrontController as the initial point of contact for handling requests. The FrontController is responsible for managing the handling of the request. Its responsibilities include delegation of business processing, managing the choice an appropriate view, error handling, selecting content-creation strategies.

52 Front Controller—Class Diagram
Use a controller as the initial point of contact for handling requests

53 Front Controller: Strategies
ServletFront Strategy – The Front Controller is implemented as a servlet. This is the preferred strategy. JSPFront Strategy – The Front Controller is implemented as a JSPTM. More cumbersome and difficult to debug than using a servlet for this function.

54 Front Controller: Consequences
Centralized control Improves Reusability Improves manageability, as typically only one resource is registered with web container Using a single lightweight Servlet as a controller along with command objects that are specific to one (or a set of) use-case(s) has the added benefit of easing administration, since only one resource needs to be registered with the application server. In other words, as use cases are implemented, the functionality is encapsulated in helper objects, implemented as javabeans, not Servlets, and thus require no server admin.

55 Presentation-Tier Patterns
Intercepting Filter Front Controller View Helper <---- Composite View Dispatcher View Service To Worker

56 View Helper Problem – Presentation tier changes occur often and are difficult to develop and maintain when business logic and presentation formatting logic are interwoven. The “Model-View-Controller” (MVC) pattern describes the logical separation of concerns of an application. The “View Helper” J2EE pattern is related, in that it addresses the key aspect of MVC, that of separating the View of the application from the Model. A good reference for learning more about MVC is: “Pattern-Oriented Software Architecture, Volume 1: A System of Patterns” (POSA).

57 View Helper: Forces Embedding business logic in the view promotes a copy-and-paste type of reuse. It is desirable to promote a clean separation of roles Software developer Web production team Enforces logical separation of View and Model

58 View Helper: Solution A View contains formatting code, delegating its processing responsibilities to its helper classes, implemented as JavaBeansTM or custom tags. Helpers also store the view’s intermediate model and serve as business data adapters.

59 View Helper: Class Diagram
In terms of MVC, the helper objects, among other things, perform the role of the intermediate Model for the View. Helper objects also initiate content retrieval and adapt the retrieved model for use by the View.

60 View Helper: Consequences
Improved application partitioning Improved role separation Reusability Another way to think about this issue is to always try to: Separate “Implementation” from “Intent” within your application.

61 Presentation-Tier Patterns
Intercepting Filter Front Controller View Helper Composite View <---- Dispatcher View Service To Worker

62 Composite View Example
Logical regions are defined, such as: - Search bar - Navigation Panel - Feature Story region - Headlines region These regions describe the layout of the page and have different frequencies of variation.

63 Composite View Pattern
Problem: Instead of providing a mechanism to combine modular, atomic portions of a view into a composite whole, pages are built by embedding formatting code directly within each view. Forces: Multiple composite view use similar subviews Modularity

64 Composite View: Forces
Layout changes are more difficult to manage and code harder to maintain when subviews are directly embedded and duplicated in multiple view. Atomic portions of view content change frequently. Managing Content versus Managing Layout.

65 Composite View: Solution
Use CompositeViews that are composed of multiple atomic subviews.

66 Composite View Example
And numerous pages like this... Concrete view implementations, such as banner.jsp and footer.jsp are mapped to the logical regions that were defined in the previous template.

67 Composite View: Consequences
View based on role or policy-based decisions Improved manageability Enhances flexibility Improved reusability Performance impact

68 Presentation-Tier Patterns
Intercepting Filter Front Controller View Helper Composite View Service To Worker <---- Dispatcher View <----

69 Service To Worker and Dispatcher View
Problem – The problem is a combination of the problems solved by the Front Controller and View Helper patterns in the presentation tier. There is no centralized component for managing access control, content retrieval, or view management, and there is duplicate control code scattered throughout various views. Additionally, business logic and presentation formatting logic are intermingled within these views, making the system less flexible, less reusable, and generally less resilient to change.

70 Service To Worker: Solution
Combine a Controller and Dispatcher with Views and Helpers (see Front Controller and View Helper Patterns) to handle client requests and prepare a dynamic presentation as the response.

71 Service To Worker Dispatcher View

72 Service To Worker / Dispatcher View: Consequences
Centralized control Improved reusability and maintainability Improved role separation

73 J2EE Pattern Catalog - Business Tier
Service Locator <---- Business Delegate Session Façade Value Object Value Object Assembler Value List Handler Composite Entity

74 Service Locator Problem ­ J2EE clients interact with service components such as EJB components, which provide business services and persistence capabilities. “Patterns do not exist in isolation” - Christopher Alexander The Service Locator pattern is commonly combined with the Business Delegate pattern.

75 Service Locator: Forces
EJB clients need to use the JNDITM API to lookup EJBHome objects by using the enterprise bean's registered JNDI name. Lookup and creation of service components could be complex and may be used repeatedly in multiple clients in the application. EJB Clients may need to re-establish connection to a previously accessed enterprise bean having only its EJB Handle object.

76 ServiceLocator: Solution
Use a Service Locator object to abstract all JNDI usage and to hide the complexities of initial context creation, EJB home object lookup, and EJB object re-creation. Multiple clients can reuse the Service Locator object to reduce code complexity, provide a single point of control, and improve performance by providing a caching facility.

77 ServiceLocator: Class Diagram
The Service Locator may return the factory object to the client, or may simply return the service, hiding the factory from the client. An example of a ServiceFactory object is a subclass of EJBHome. An example of a BusinessService object is a subclass of EJBObject Also, the InitialContext may be cached in the Service Locator for performance purposes.

78 Service Locator: Consequences
Abstracts complexity Provides uniform access to clients Improves network performance

79 J2EETM Pattern Catalog - Business Tier
Service Locator Business Delegate <---- Session Facade Value Object Value Object Assembler Value List Handler Composite Entity

80 Business Delegate Problem ­ Presentation-tier components interact directly with business services. This direct interaction exposes the underlying implementation details of the business service API to the presentation tier. This pattern is categorized in the business tier, but remember that these are logical divisions. The business delegate is typically implemented physically within the web container. It acts as a proxy to bridge the gap of communication across tiers.

81 Business Delegate : Forces
It is desirable to minimize coupling between presentation-tier clients and the business service, thus hiding the underlying implementation details of the service, such as lookup and access. It is desirable to reduce network traffic between client and business services. There is often a skill disparity between presentation tier developers and business tier developers. Why should presentation tier developers be forced to understand and work with implementation artifacts of the service layer, such as EJB?

82 Business Delegate : Solution
Use a Business Delegate to reduce coupling between presentation-tier clients and business services. The Business Delegate hides the underlying implementation details of the business service, such as lookup and access details of the EJBTM architecture.

83 Business Delegate : Class Diagram
The role of the LookupService may be fulfilled by implementing another pattern called “Service Locator”, an example of how the patterns in the J2EE Pattern catalog typically work together in combination. The “Service Locator” pattern is coming up shortly...

84 Business Delegate: Strategies
Delegate Proxy Strategy - The BusinessDelegate exposes an interface that provides clients access to the underlying methods of the business service API. Delegate Adapter Strategy - The Business Delegate proves to be a nice fit in a B2B environment when communicating with J2EE services. Disparate systems may use an XML as the integration language. Integrating one system to another typically requires an Adapter [GoF] to meld the two disparate systems.

85 Business Delegate: Consequences
Reduces Coupling, Improves Manageability - Reduces coupling between the Presentation tier and the Business tier Translates Business Service Exceptions - The BusinessDelegate is responsible for translating any network or infrastructure-related exceptions into business exceptions. Impacts Performance - The BusinessDelegate may provide caching services The delegates act as central access points to the business services. Thus, it is an excellent component within which to encapsulate retries upon service failure. Also, if there is a need to synchronize access to a service, this code can be implemented within the delegate, as well, so that it can be reused and maintained in a single place.

86 J2EE Pattern Catalog - Business Tier
Business Delegate Service Locator Session Façade <---- Value Object Value Object Assembler Value List Handler Composite Entity

87 Session Facade Problem - Three problems may arise in a multi-tiered J2EE application environment: Tight coupling which leads to direct dependence between clients and business objects Too many method invocations between client and server leading to network performance problems Lack of a uniform client access strategy exposing business objects to misuse

88 Session Facade: Forces
Provide a simpler interface to the clients by hiding all the complex interactions between business components. Reduce the number of business objects that are exposed to the client across the service layer over the network. Hide from the client the underlying interactions and inter-dependencies between business components. This provides better manageability, centralization of interactions (responsibility), greater flexibility, and greater ability to cope with changes Provide a uniform coarse-grained service layer to separate business object implementation from business service abstraction. Avoid exposing the underlying business objects directly to the client to keep tight coupling between the two tiers to a minimum.

89 Session Facade: Solution
Use a session bean as a Facade to encapsulate the complexity of interactions between the business objects participating in a workflow. The Session Facade manages the business objects, and provides a uniform, coarse-grained service access layer to clients. The Session Façade is a controller for the business service layer, not entirely unlike the Front Controller in the Presentation tier.

90 Session Facade: Class Diagram
The SessionFacade provides a course-grained, uniform point of access into the business service layer. It aggregates the behavior of the underlying business objects. This is why it is called a course-grained façade. Remember that the Business Delegate acted as a Proxy, not a Façade.

91 Session Facade: Consequences
Introduces Business Tier Controller layer Reduces Coupling, Increases Manageability Improves Performance, Reduces Fine-grained Methods Provides Coarse-Grained Access Centralizes Transaction Control Simply put, the main benefit of using this pattern is that it will reduce the number of remote invocations necessary for clients to use the services of the business tier.

92 J2EE Pattern Catalog - Business Tier
Business Delegate Service Locator Session Facade Value Object <---- Value Object Assembler Value List Handler Composite Entity

93 Value Object Problem ­ J2EE applications implement server-side business components as session beans and entity beans. Some methods exposed by the business components return data to the client. Often, the client invokes a business object’s get methods multiple times until it obtains all the attribute values.

94 Value Object: Forces The client usually requires more than one attribute value of an enterprise bean. The number of calls made by the client to the enterprise bean impacts network performance.

95 Value Object : Solution
Use a Value Object to encapsulate the business data. A single method call is used to send and retrieve the Value Object.

96 Value Object : Class Diagram

97 Value Object : Consequences
Transfers more Data in fewer remote calls Reduces Network Traffic Reduces Code Duplication May Increase Complexity due to Synchronization and Concurrent Access and Transactions

98 J2EE Pattern Catalog - Business Tier
Business Delegate Service Locator Session Facade Value Object Value Object Assembler <---- Value List Handler Composite Entity

99 Value Object Assembler
Problem ­ Application clients typically require the data for the model or parts of the model to present to the user or to use it for an intermediate-processing step before providing some service.

100 Value Object Assembler: Forces
Separation of business logic is required between the client and the server side components. Because the model consists of distributed components, access to each component is associated with a network overhead. Clients do not need to be aware of the intricacies and dependencies in the model implementation. Clients do not otherwise need to have the additional business logic required to construct the model from various business components.

101 Value Object Assembler: Solution
Use a Value Object Assembler to build the required model or sub-model. The Value Object Assembler uses value objects to retrieve data from various business objects and other objects that define the model or part of the model. This is not exactly a Gof “Builder” because it does not include the use of a generic “Director”, as described in that pattern.

102 Value Object Assembler: Class Diagram

103 Value Object Assembler: Strategies
JavaTM Object Strategy - The ValueObjectAssembler can be an arbitrary Java object and need not be an enterprise bean. Session Bean Strategy - This strategy implements the ValueObjectAssembler as a session bean Note: The BusinessObject role in this pattern can be supported by different types of objects Session Bean Entity Bean DAO

104 Value Object Assembler: Consequences
Separates business logic Reduces coupling between clients and the Application Model Improves Network performance

105 J2EE Pattern Catalog - Business Tier
Business Delegate Service Locator Session Facade Value Object Value Object Assembler Value List Handler <---- Composite Entity

106 Value List Handler Problem ­Most J2EE applications have a search / query requirement to search and list certain data. In some cases, such a search and query operation could yield results that can be quite large. It is impractical to return the full result set when the client’s requirements are to traverse the results, rather than process the complete set.

107 Value List Handler: Forces
The application client needs an efficient query facility to avoid having to call the entity bean’s ejbFind method and invoking each remote object returned. A query that is repeatedly executed on reasonably static data can be optimized to provide faster results. Client may want to scroll forward and backward within a result set. EJBFind methods return one or more remote references and we prefer to hide these references from clients in the presentation tier.

108 Value List Handler: Solution
Use a Value List Handler to control the search, cache the results, and provide the results to the client in a result set whose size and traversal meets the client’s requirements.

109 Value List Handler: Class Diagram

110 ValueListHandler: Consequences
Provides alternative to EJB Finders for large queries Caches query results on server-side Provides better querying flexibility Improves network performance

111 J2EE Pattern Catalog - Business Tier
Business Delegate Service Locator Session Facade Value Object Value Object Assembler Value List Handler Composite Entity <----

112 Composite Entity. Problem ­ In a J2EE application, clients (applications, JSPTM technology, ServletsTM, JavaBeans) access entity beans via their remote interfaces. When entity beans are fine-grained objects, clients tend to invoke more individual entity bean methods, resulting in high network overhead.

113 Composite Entity: Forces
Entity beans are best implemented as coarse-grained objects due to the high overhead associated with each entity bean. Applications that directly map relational database schema to entity beans (where each row in a table is represented by an entity bean instance) tend to have a large number of fine-grained entity beans. Direct mapping of object model to EJB model yields fine-grained entity beans. Fine-grained entity beans usually map to the database schema.

114 Composite Entity: Solution
Use Composite Entity bean to model, represent, and manage a set of inter-related persistent objects rather than representing them as individual fine-grained entity beans. An Composite Entity bean represents a graph of objects. If a database schema is translated into an object model, one typically ends up with too many Entity beans, since each maps to a db table. The relationships between tables are then represented as relationships between Entity beans. We prefer to better understand the parent-child relationships that exist between the entities and to model these as course-grained Entity beans (parents) and dependent objects, implemented as plain old Java objects (children).

115 Composite Entity: Class Diagram

116 J2EE Pattern Catalog - Integration Tier
Data Access Object Service Activator

117 Data Access Object Problem: Many real-world J2EE applications need to use persistent data at some point. For many applications, persistent storage is implemented with different mechanisms, and there are marked differences in the APIs used to access these different persistent storage mechanisms. Access to data varies depending on the source of the data. Access to persistent storage, such as to a database, varies greatly depending on the type of storage (relational databases, object-oriented databases, flat files, and so forth) and the vendor implementation.

118 Data Access Object: Forces
Components such as bean-managed entity beans, session beans, servletsTM and JSPsTM need to retrieve and store information from persistent stores. Components typically use proprietary APIs to access legacy systems to retrieve and store data. Components need to be transparent to the actual persistent store or data source implementation to provide easy migration to different vendor products, different storage types, and different data source types.

119 Data Access Object: Solution
Use a Data Access Object to abstract and encapsulate all access to the data source. The Data Access Object manages the connection with the data source to obtain and store data.

120 Data Access Object: Class Diagram

121 DataAccessObject: Strategies
Automatic DAO Code Generation ­ Each BusinessObject has its own DAO and storage (for example, table in RDBMS). Build or buy a code generator to create DAOs from metadata automatically. Factory for DAO ­ Define an Abstract Factory for DAOs. Each concrete DAO Factory encapsulates storage vendor-specific details. Clients request DAOs from the abstract factory, which delegates creation to the appropriate concrete DAO factory. Implementing the “Factory for DAO” strategy using Factory Method

122 Data Access Object: Consequences
Enables transparency Enables easier migration to different persistent storage implementation Reduces code complexity in business objects Centralizes data access into a separate layer Not useful for EJBsTM with container-managed persistence

123 J2EE Pattern Catalog - Integration Tier
Data Access Object Service Activator <----

124 Service Activator Problem: Enterprise beans implemented prior to the EJB specification version 2.0 (EJB 2.0) do not support asynchronous invocation. EJB 2.0 introduces integration with JMS by providing a Message Driven Bean, which is a new type of stateless session bean.

125 Service Activator: Forces
EJBs are accessed using remote interfaces, which support synchronous processing only. All interactions are performed through remote references. Implementing JMS listener by an EJB is not allowed. An application might need to provide a publish/subscribe framework for EJBs. Clients want to invoke EJBs asynchronously without waiting for processing to complete. Clients want to use the messaging facilities offered by JMS interfaces to call an EJB An EJB needs to provide daemon-like facilities without being passivated

126 Service Activator: Solution
Use a Service Activator to receive asynchronous client requests and messages. On receiving a message, the Service Activator locates and invokes the necessary business methods on the business service components to fulfil the request asynchronously.

127 Service Activator: Sequence Diagram

128 Service Activator: Consequences
Integrates JMS into pre-EJB 2.0 implementations Provides asynchronous processing for any enterprise beans Standalone process

129

130 Find out More… Check out the book—Core J2EE™ Patterns
Subscribe to J2EE Patterns Interest alias Tools: TogetherSoft Rational iPlanet Updates at

131 Reference Architecturing and J2EE Patterns -Mark Cada
SUN One Architecture Enterprise Java Architecture-Sameer Tyagi Garbage Collection & Performance Tuning -Charlie Hunter


Download ppt "J2EE Architecture, System Qualities and Design Patterns"

Similar presentations


Ads by Google