Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Jee design patterns- Marek Strejczek - Rule Financial


Published on

Jee design patterns- Marek Strejczek - Rule Financial

  1. 1. JEE Design PatternsPrepared by: Marek StrejczekSubmitted on: 2012-10-19 Confidential
  2. 2. AgendaAbout JEE, J2EE and design patternsBusiness tier patternsIntegration tier patternsJEE infrastructure patternsRetired J2EE patternsSummary © Rule Financial 2012 2
  3. 3. JEE Design PatternsAgendaAbout JEE, J2EE and design patternsBusiness tier patternsIntegration tier patternsJEE infrastructure patternsRetired J2EE patternsSummary © Rule Financial 2012 3
  4. 4. What is JEE• JEE platform provides an API and runtime environment for developing and running enterprise software • including network and web services, and other large-scale, multi- tiered, scalable, reliable, and secure network applications• The platform incorporates a design based largely on modular components running on an application server Based on © Rule Financial 2012 4
  5. 5. What is JEETechnologies• Chosen JEE6 technologies (there are many more): • JCA • EJB • JPA • JSF • JAX-WS, JAX-RS • JMS • JDBC • Servlet • JTA © Rule Financial 2012 5
  6. 6. What is JEETechnologies cont’d• Chosen JEE6 technologies: • JCA Accessing external systems • EJB Single-threaded programming model, remote invocations • JPA Managing relational data • JMS Async communication – good for scalability • JTA Distributed transactions, declarative transactions © Rule Financial 2012 6
  7. 7. JEE Architecture © Rule Financial 2012 7
  8. 8. J2EE drawbacksPrior to JEE5• Lots of boilerplate code • Local, Remote, Remote Home interfaces • XML deployment descriptor • plus another XML for vendor-specific stuff Spring and Hibernate • JNDI lookups emerged as a viable• EJBs tightly coupled to J2EE API alternative • Both session and entity beans • Lack of encapsulation of technical details © Rule Financial 2012 8
  9. 9. J2EE DrawbacksDesign Patterns come to rescue• Some design patterns were invented just to work around platform limitations • Example: Service Locator, Business Delegate• Some design patterns solved genuine problems inherent to enterprise environment • Example: Session Facade, DAO © Rule Financial 2012 9
  10. 10. J2EE DrawbacksJEE comes to rescue• Totally redesigned EJB programming model • Dependency Injection • Convention over Configuration • POJO-based persistence • Minimal coupling of business logic to EJB API• Most APIs were not redesigned: JTA, JMS, JNDI, Servlets © Rule Financial 2012 10
  11. 11. Architecture styleSOA, DDD• Service Oriented Architecture • Business functionalities exposed using interoperable services built from reusable components• Domain Driven Design • Mapping of business domain concepts into software artifacts• Good when work together • however easily degenerate - e.g. anemic model with SOA © Rule Financial 2012 11
  12. 12. Design PatternWhat is it?• A general reusable solution to a commonly occurring problem within a given context in software design. • Can speed up development process as it provides a tested, proved development paradigm. • Facilitates communication among developers/architects by providing universal jargon. Based on © Rule Financial 2012 12
  13. 13. Design PatternA simple Builder © Rule Financial 2012 13
  14. 14. Questions? © Rule Financial 2012 14
  15. 15. JEE Design PatternsAgenda Introduction Business tier patterns Integration tier patterns JEE infrastructure patterns Retired J2EE patterns Summary © Rule Financial 2011 15
  16. 16. Service FacadeApplication Service• Forces • High-level business API is needed. • State of the application must remain consistent. • Logic can be invoked remotely. • Realization behind the Service Facade should be encapsulated. • Business API must not change when the realization is modified. © Rule Financial 2012 16
  17. 17. Service FacadeApplication Service © Rule Financial 2012 17
  18. 18. Service FacadeApplication Service• Boundary between presentation and business layers.• A stateless session bean.• Coarse-grained methods, designed from domain perspective.• @TransactionAttributeType(REQUIRES_NEW).• A composition of independent and reusable services.• Very simple business logic can be realised directly. © Rule Financial 2012 18
  19. 19. Service FacadeBasic implementation © Rule Financial 2012 19
  20. 20. Service FacadeCRUD Facade © Rule Financial 2012 20
  21. 21. Service FacadeDual-view Facade © Rule Financial 2012 21
  22. 22. Service FacadeSOA Facade © Rule Financial 2012 22
  23. 23. Service FacadeLightweight asynchronous facade EJB 3.1: © Rule Financial 2012 23
  24. 24. Service FacadeMultichannel facade – JAX-WS © Rule Financial 2012 24
  25. 25. Service FacadeMultichannel facade – JAX-RS © Rule Financial 2012 25
  26. 26. ServiceSession Facade• Forces • Services should be independent of each other. • Services are not accessible from outside the business tier or remotely. • A Service is aimed to be used by another component or Service Facade. • State of the application must remain consistent. • Business API must not change when the realization is modified.• In DDD a Service realizes cross-cutting, domain object-independent logic. In SOA a Service plays a main role and implements the actual business logic. © Rule Financial 2012 26
  27. 27. ServiceSession Facade © Rule Financial 2012 27
  28. 28. ServiceSession Facade• Rationale for J2EE-style Session Facade is to large extent gone. • Entity beans are no longer remotely-accessible. • Container can manage relations between different entities itself.• A session bean.• Not concerned with remoting, transactions, security. • These are responsibilities of Service Facade. • Local interface only. • @TransactionAttributeType(MANDATORY). © Rule Financial 2012 28
  29. 29. ServiceBasic implementation © Rule Financial 2012 29
  30. 30. ServicePOJO implementation © Rule Financial 2012 30
  31. 31. ServicePOJO implementation – cont’d © Rule Financial 2012 31
  32. 32. Service Facade + Service © Rule Financial 2012 32
  33. 33. Persistent Domain ObjectBusiness Object• Forces • Complex business logic. • Validation rules are domain-related and sophisticated. • Domain objects need to be persisted in a relational DB.• J2EE Business Object pattern was invented around shortcomings of the technology • CMP persistence didn’t support inheritance or polymorphic queries. • Anemic model was the only viable solution. © Rule Financial 2012 33
  34. 34. Persistent Domain ObjectBusiness Object• Anemic entities and procedural approach are widely used. • They didn’t go away even when JDO or Hibernate became available. • Procedural approach actually works quite well.• However when the domain model is complex and full of sophisticated business rules, the code may become brittle and difficult to enhance. © Rule Financial 2012 34
  35. 35. Persistent Domain ObjectBusiness Object © Rule Financial 2012 35
  36. 36. Persistent Domain ObjectAnemic model © Rule Financial 2012 36
  37. 37. Persistent Domain ObjectPDO © Rule Financial 2012 37
  38. 38. Persistent Domain ObjectModel with PDOs © Rule Financial 2012 38
  39. 39. Persistent Domain ObjectModel with PDOs © Rule Financial 2012 39
  40. 40. Persistent Domain Object• Self-contained domain objects. • Clear responsibilities. • Encapsulated state and behaviour.• Best when PDOs are used in attached state. • Otherwise be prepared for complex merging of changes…• Accessing Entity Manager from inside JPA entities is problematic.• Lack of JavaBean-style getters/setters makes PDOs not suitable for data-binding UI frameworks. © Rule Financial 2012 40
  41. 41. Persistent Domain ObjectGateway pattern• Gateway pattern • Not covered in this presentation. Too big and too unusual – this presentation is already large enough. • That pattern is related to exposing PDOs to the presentation layer.• Try this link to study on your own:• driven-design.html © Rule Financial 2012 41
  42. 42. Fluid Logic• Forces • Ability to execute parts of the business logic dynamically. • Algorithms often change and therefore should be reloadable. • A custom interpreter is too expensive to develop and maintain. • Integration of scripting components with JEE environment is desired.• Solution: • Implement volatile algos in a scripting language that would be interpreted dynamically at runtime. • Possible with JSR-223 (Scripting for the Java Platform). © Rule Financial 2012 42
  43. 43. Fluid Logic• Using dynamic languages to build enterprise applications is still risky. • Poor static analysis, refactoring facilities and IDE support. • Lack of type safety requires writing more unit tests.• Reasonable use of scripting can be advantageous, though.• Scripting can be used in any layer and for any purpose. © Rule Financial 2012 43
  44. 44. Fluid Logic © Rule Financial 2012 44
  45. 45. Fluid Logic• Script can be loaded as a resource at runtime, from any location.• The script can be invoked in the context of the EJB. • Participates in transactions. • Has access to container services.• Testing of the dynamic scripts may be a challenge. • Fortunately only little parts of the application are likely to be scripted. © Rule Financial 2012 45
  46. 46. Fluid LogicConsequences• Flexibility of the business logic is improved.• Performance will suffer. Hopefully it’ll be still acceptable.• Heterogenous projects are more difficult to understand and maintain.• Security might suffer. • SecurityManager remains there, but someone might use the ScriptingEngine to introduce a malicious script into the system.• If support for multiple scripting languages is not required then direct integration might be more efficient (e.g. Rhino). © Rule Financial 2012 46
  47. 47. Questions? © Rule Financial 2012 47
  48. 48. JEE Design PatternsAgenda Introduction Business tier patternsIntegration tier patterns JEE infrastructure patterns Retired J2EE patterns Summary © Rule Financial 2011 48
  49. 49. Data Access Object• Forces • Access a legacy (JPA-incompatible) data source or resource is needed. • Strict separation of business logic and persistence details is needed. • Resource access must be decoupled from the rest of the application (e.g. because it uses a proprietary interface). • The queries are very complex and it is desired to maintain them in a separate place. • Data access abstraction must be testable and mockable. © Rule Financial 2012 49
  50. 50. Data Access Object• A DAO is a stateless session bean. • @TransactionAttributeType.MANDATORY• For JPA-incompatible access the JEE approach is basically the same as before.• EntityManager is a DAO in itself. • In simple cases it can be injected directly into the business logic.• DAO that relies on JPA is basically a wrapper around EntityManager. © Rule Financial 2012 50
  51. 51. Data Access ObjectCRUD Service (Generic DAO) © Rule Financial 2012 51
  52. 52. Data Access ObjectCRUD Service (Generic DAO) © Rule Financial 2012 52
  53. 53. Data Access ObjectOther variants• A domain-specific DAO. • A type-safe DAO designed to act on a particular domain object. • Could contain domain-specific extensions going beyond standard functionality provided by EntityManager.• Detached-result DAO. • If DAO returns detached objects then it’s a good practice to indicate it in the type name of the returned value, e.g. List<BookDTO> findByNamedQuery(String queryName) © Rule Financial 2012 53
  54. 54. Data Access ObjectOther variants• Abstract DAO • Business logic service extends an abstract class with DAO capabilities. • Not ok for purists, but may be pragmatic in small DB-driven applications. © Rule Financial 2012 54
  55. 55. Transfer Object• In J2EE intended: • to decouple domain objects from its users and reduce coupling between tiers. • to transfer all requested data at once, to avoid many remote calls to CMP entity bean getters. © Rule Financial 2012 55
  56. 56. Transfer ObjectRethinking the original intention• Decoupling was often a myth, as structure of TOs was very similar or identical to that of domain objects. • Usually new feature impact cross-cuts all layers, so TOs had to be modified at the same time as domain entites and presentation forms, effectively crippling maintainability. • JPA entites are by definition local and not available for remote calls. • Detached JPA entites can often be used as TOs! © Rule Financial 2012 56
  57. 57. Transfer ObjectRethinking the original intention• Transfer Objects in JEE can be used to decouple external interfaces from domain model. • Service-oriented applications need to expose a stable interface. • Change in domain model due to a request from one client should not affect other clients. • Transfer Objects can be used to provide client-specific views, providing additional flexibility compared to detached JPA entites.• Transfer Objects might carry only the required subset of the object graph to reduce overhead in a distributed environment. © Rule Financial 2012 57
  58. 58. Transfer Object• Transfer Object may represent a simplified view of domain objects for use e.g. with web services.• Transfer Object may carry additional metadata for the presentation tier. © Rule Financial 2012 58
  59. 59. Transfer ObjectImplementation• A serializable class, no logic.• Many approaches: • Java bean • Builder-style, possibly final • Generic DTO • Data stored as key-value pairs. • Most flexible, but verbose and not type safe. © Rule Financial 2012 59
  60. 60. Questions? © Rule Financial 2012 60
  61. 61. JEE Design PatternsAgendaIntroductionBusiness tier patternsIntegration tier patternsJEE infrastructure patternsRetired J2EE patternsSummary © Rule Financial 2011 61
  62. 62. Singleton• Wanted: a bean that exists only once in a JVM.• Could be useful for keeping master data cache or configuration.• Not possible to achieve in a portable way prior to EJB 3.1. • In EJB 3.1: @Singleton • In a clustered environment there will be multiple Singleton instances! © Rule Financial 2012 62
  63. 63. Singleton• Default settings for singletons: • ConcurrencyManagementType.Container • LockType.Write © Rule Financial 2012 63
  64. 64. Singleton• Could be used to throttle access to legacy backend resources.• Contain cache data • E.g. configuration, internationalization messages. • If cache data is loaded at startup and is read-only then LockType.READ mode could be used. • Consider using a real caching solution, like EHCache.• No cluster-wide singletons as of EJB 3.1. © Rule Financial 2012 64
  65. 65. Service Starter• Wanted: certain logic must be executed before business requests can be handled. • E.g. huge XMLs must be parsed first.• Prior to EJB 3.1: • Invoke EJB from servlet’s init method. The servlet has <load-on- startup> set to 1.• In EJB 3.1: • Annotate class with @Singleton and @Startup • Put required logic inside a method annotated with @PostConstruct. © Rule Financial 2012 65
  66. 66. Service Starter• Sequence in which @Singleton EJBs are initialized can be controlled using @DependsOn annotation. © Rule Financial 2012 66
  67. 67. Bean Locator• Wanted: a way to access EJBs where Dependency Injection won’t work. • E.g. from POJOs, from outside of EJB container. • Lookup of stateful EJBs from servlets.• Similar concept to J2EE Service Locator • JNDI lookups are ugly and should be hidden. • However use of a Bean Locator is an exception rather than rule. • Bean Locator is used for looking up EJBs, while Service Locator was used to fetch all type of resources (JMS destinations, data sources, EJBs) © Rule Financial 2012 67
  68. 68. Bean Locator• New in EJB 3.1: global JNDI naming of EJB components. • jndi:global[/<app-name>]/<module-name>/<bean-name>#[<fully- qualified-interface-name>]• Bean Locator returns the business interface (or bean instance), while Service Locator fetched the home interface.• Bean Locator goes well with the GoF Builder pattern – Builder is useful for creating JNDI names. © Rule Financial 2012 68
  69. 69. Other neat patterns• Dependency Injection Extender • Inject Guice or Spring beans into EJBs. • These external components will participate in EJB transactions and security context.• Resource Binder • Register custom resources in JNDI in a portable way.• Context Holder • Pass information between transaction participants without polluting your application API. Uses TransactionSynchronizationRegistry class. © Rule Financial 2012 69
  70. 70. Other neat patterns © Rule Financial 2012 70
  71. 71. Questions? © Rule Financial 2012 71
  72. 72. JEE Design PatternsAgendaIntroductionBusiness tier patternsIntegration tier patternsJEE infrastructure patternsRetired J2EE patternsSummary © Rule Financial 2011 72
  73. 73. Service Locator• Original intention • Abstract all JNDI usage and hide complexities of initial context creation and JNDI lookups.• Reasons for retirement • Dependency Injection is available in most JEE components. • Service Locator would increase complexity instead of decreasing it. • In exceptional cases – use the Bean Locator pattern. © Rule Financial 2012 73
  74. 74. Composite Entity• Original intention • Represent a set of interrelated persistent objects instead of exposing fine-grained entity beans directly. • Necessary as entity beans were available remotely. • Also relations between persistent entities were not transparent.• Reasons for retirement • JPA handles relations between entities well. • JPA entities are not available remotely. © Rule Financial 2012 74
  75. 75. Value Object Assembler• Original intention • To extract, merge and transform data from different data sources and expose them using Transfer Objects.• Reasons for retirement • EntityManager is able to return a submodel from a graph of interconnected entities. • Service or Service Facade is responsible for converting entities into Transfer Objects. Separate pattern is not required. • Meaning of TOs has dropped since in many cases detached entities can be moved between layers directly. © Rule Financial 2012 75
  76. 76. Business Delegate• Original intention • Hide the complexity of accessing business services in EJB architecture (JNDI lookups and remoteness of invocations) from J2EE clients.• Reasons for retirement • Checked exceptions are gone from the API (e.g. RemoteException) – EJB business interface is the same as Business Delegate interface. • Obtaining reference to an EJB is significantly simplified – even if Dependency Injection cannot be used, the JNDI lookup returns the business interface directly, without going through the home interface. © Rule Financial 2012 76
  77. 77. Domain Store• Original intention • To transparently persist an object model, hiding the required CMP J2EE plumbing.• Reasons for retirement • EntityManager can be considered as a standardized Domain Store. © Rule Financial 2012 77
  78. 78. Questions? © Rule Financial 2012 78
  79. 79. JEE Design PatternsAgendaIntroductionBusiness tier patternsIntegration tier patternsJEE infrastructure patternsRetired J2EE patterns Summary © Rule Financial 2011 79
  80. 80. Useful facility: interceptorsNot covered in this presentation• EJB come with a AOP framework. • Lightweight • Easy to use • Still, lots of interesting capabilities - some patterns (not described here) rely on this mechanism. © Rule Financial 2012 80
  81. 81. Useful facility: interceptors © Rule Financial 2012 81
  82. 82. Summary• JEE is not heavyweight anymore.• The paterns make application architecture cleaner and more maintainable.• Some patterns may be used in Spring-based applications.• References: • „Real World Java EE Patterns Rethinking Best Practices” Adam Bien • • © Rule Financial 2012 82
  83. 83. Thank you! Confidential