Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 1 Session: Pragmatic Architecture Java EE, latest brew Entity, Control and Boundary
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 2 Objectives Learn about: ✔ Get an overview about the latest Java EE technologies used at the backend ✔ A warming up for the architectural aspects ✔ Get an idea about the ECB pattern as a general principle
3 Where are we right now? Existing architectures Architecture Patterns Customer & Business needs Further requirements Reference Architecture mining proven concepts vision analysis evolution triggering
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 4 Some orientation Consumer Consumer Layer Integration Layer Business Process Layer Services Layer Component Layer OS Layer
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 5 Module Java EE, latest brew
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 6 The rise of Spring and Hibernate Spring ✔ Application framework ✔ Dependency Injection ✔ AOP support ✔ Non-invasiveness as a basic principle ✔ O/R persistence support for various frameworks Hibernate ✔ POJO based O/R persistence Spring and Hibernate became a popular alternative to J2EE development.
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 7 Don't look back Until V5.0 Enterprise Java really had a bad reputation: ✔ Too complex, especially when it comes to EJBs (Home Interface, Local Interface, Remote Interface, Bean class, Deployment Descriptor) ✔ Too inflexible, especially when it comes to CMP (heavy-weighted objects, Session Facades and Value Objects) ✔ Outdated, especially when it comes to AOP and DI ✔ Too expensive, especially when it comes to app-servers ✔ Too ... But things change!
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 8 Right now Java EE V5.0 (and higher) has a lot to provide: ✔ Context and Dependency Injection (CDI) ✔ Validators ✔ JPA 2.x ✔ Convention over Configuration ✔ And …its a standard supported by various vendors
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 9 Convention over Configuration ✔ A principle borrowed from the Ruby on Rails tribe ✔ Decreases the number of decisions to be made and configurations to be done by default configurations ✔ Annotations replace XDoclet's JavaDoc tags:  Compiler checks  Type safety (instead if just strings) ✔ All information previously stored in the deployment descriptor file (the meta-data hell) now moved into annotations (but DD file still optional and overwrites Annotation)
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 10 XDoclet & Annotations ✔ XDoclet: ✔ Annotation: /** * @ejb.bean name = „UserMgmtService“ view-type = „remote“ */ public class UserMgmtService implements SessionBean { … } @Stateless @Remote(UsrMgmt.class) public class UserMgmtService implements UsrMgmt { … }
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 11 Annotations @Stateless: ✔ Marks the class as a Stateless Session Bean, no need to implement an interface or to extend a class ✔ Provides a default transaction handling (every method will be executed in a single transaction) @LocalBean ✔ All public methods will be exposed to local clients, no need to implement a dedicated interface ✔ Local clients - like Servlets or other EJBs – might obtain a reference by means of dependecy injection.
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 12 Lab Implement Stateless Session Bean (not more than 15 min.)
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 13 Dependency injection ✔ Providing an external dependency (any ressource like another EJB, a DataSource, a JMS destination …) to a software component. ✔ Previously (within a client bean) public void init() { try { ctx = new InitialContext(); facade = (UserManagementService) ctx.lookup("ejb/facade/UserManagementService"); } catch (NamingException e) { e.printStackTrace(); } }
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 14 Dependency Injection In our days: ✔ No Exception handling, no casting issues, no misspelling, no deployment descriptors, no ... @Stateless @Remote(Client.class) public class ClientBean implements Client { @EJB private UserMgmtLocal userMgmt; ... }
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 15 Lab Implement Dependency Injection (not more than 15 min.)
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 16 Bean Validation JSR 303: Bean Validation ✔ you can use it anywhere you like:  front-end,  back-end,  even DTO (if you follow this pattern) ✔ reference implementation is Hibernate Validator v4.x ✔ validation on two different levels: attribute or entire bean ✔ i18n ready and message are parameterized ✔ extensible with your own validators ✔ configurable with annotations or XML
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 17 Several build-in Validators ✔ Quite a few Validators are already implemented within the javax.validator package, some examples: @AssertFalse / @AssertTrue The value of the field or property must be false / true @Max / @Min The value of the field or property must be an integer value lower / higher than or equal to the number in the value element. @NotNull The value of the field must not be null @Past / @Future The date has to be in the past / future ... @see link below
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 18 Example ✔ Considering a user, we might want to ensure the following: public class User implements Serializable { @NotNull private long id; @NotNull @Size(min = 4, max = 8) private String user; @NotNull @Size(min = 8, max = 15) private String password;
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 19 Example: evaluating ✔ If not done by the container (which is the usual case), we can evaluate 'manually' public void testValidation() { Set<ConstraintViolation<User>> violations = validator.validate(user); System.out.println("Number of violations: " + violations.size()); for (ConstraintViolation<User> constraintViolation : violations) { System.out.println(constraintViolation.getPropertyPath() + " " + constraintViolation.getMessage()); } } @BeforeClass public static void init() { user = new User(); user.setPassword("abcdef"); factory = Validation.buildDefaultValidatorFactory(); validator = factory.getValidator(); }
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 20 Writing your own validator ✔ … not covered if this training! ✔ Though the JSR defines a whole bunch of standard constraint annotations such as @NotNull, @Size, @Min or @AssertTrue, there will always be validation requirements, for which these standard annotations won't suffice. ✔ Being aware of that problem, the specification authors laid out the API in an expansible manner, that allows users to define their custom constraint annotations. ✔ A nice tutorial can be found here: http://musingsofaprogrammingaddict.blogspot.de/2009/02/getting-started-with- jsr-303-bean.html
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 21 Lab Implement Validator (not more than 15 min.)
22 AOP / Interceptors Aspect-oriented programming ✔ A paradigm more than a pattern. ✔ Certain software properties cannot be isolated in single functional unit, instead they crosscut multiple components ✔ Such cross-cutting concerns result in tangled code that is hard to develop and maintain, e.g.:  Logging  Authentication
23 Interceptor Non UML: EJB Container Interceptor(s) Request Response
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 24 Interceptors ✔ Introduced with EJB 3.0 ✔ Are one of the Java EE pendant to Aspects (the other is a Servlet Filter). ✔ Are pretty easy to implement
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 25 Interceptors ✔ Provided EJBs with a rudimentary Aspect Oriented Programming system. ✔ Enable a clean distinction of business logic and meta or support code. ✔ Are classes (distinct form the beans themself). ✔ Interpose themselves on methods calls or life cycle events. ✔ Have access to information about the business method that triggered it, including method names an parameters. ✔ Can halt processing of the business method. ✔ Can be used on session and message-driven beans. ✔ A bean can have any number of Interceptors. ✔ Common uses for interceptors are security checking, logging or auditing functions. separation of concerns
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 26 An Interceptor public class PerformanceInterceptor { private Logger log = Logger.getLogger(this.getClass().getName()); @AroundInvoke public Object onMethodCall(InvocationContext ctx) throws Exception { log.info(">>> Entering interceptor"); long start = System.currentTimeMillis(); log.info("Invocation of: " + ctx.getMethod().getName()); try { // go ahead using the invocation context return ctx.proceed(); } finally { long end = System.currentTimeMillis(); long duration = end - start; log.info("Duration of invocation: " + duration); } } }
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 27 Intercepting @Stateless(mappedName = "ejb/facade/UserManagementService") @Remote(UserManagementService.class) // alternatively you can use the interceptor here as well public class UserManagementServiceBean implements UserManagementService { // use interceptor (comment if using ejb-jar.xml) @Interceptors(PerformanceInterceptor.class) public User findUserByCredentials(String user, String pwd) { User u = new User("peterp", "neverland"); return u; } public User createUser(User u) { return u; } } ✔ Annotate method(s) or class
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 28 Configuration by XML ✔ The recommened way as we can change without recompilation <?xml version="1.0" encoding="UTF-8"?> <ejb-jar version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd"> <assembly-descriptor> <interceptor-binding> <ejb-name>UserManagementServiceBean</ejb-name> <interceptor-class> de.brockhaus.userMgmt.backend.util.PerformanceInterceptor </interceptor-class> <method> <method-name>findUserByCredentials</method-name> <method-params> <method-param>java.lang.String</method-param> <method-param>java.lang.String</method-param> </method-params> </method> </interceptor-binding> </assembly-descriptor>
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 29 Lab Implement Interceptor (not more than 15 min.)
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 30 Persistent Entities / JPA 2.x ✔ JPA defines a way to map regular, plain old Java objects (POJOs) to a database. ✔ These plain Java objects are called persistent entities (and no longer EntityBeans):  they can be used in regular Java applications outside of an application server and can even be used to transfer data between a client and a server.  In EJB 2.1 specification, entity beans were „heavyweight“: • dependent on the application server. • dependent on the entire Java EE runtime environment. • cause high memory consumption.
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 31 Parts of JPA The JPA Specification consists of three parts: ✔ Entities  business objects.  persisted in the database. ✔ Persistence unit  A group of a finite set of Entity bean classes.  Associated to a particular database so that the persistence provider knows where, how, and with what kind of database it is interacting.  Are defined in an xml deployment descriptor named persistence.xml. ✔ EntityManager  The EntityManager provides an API to maintain the Entities.  provides the persistence context for a particular persistence unit.
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 32 Basic Mappings The entity: @Entity ✔ Defines the class as persistent Entity The Table: @Table ✔ By default tablename == classname ✔ You can change this (veeeery needful in case of reserved word like USER) by @Table(name=“TABLENAME“) ✔ You can define unique constraints: The primary key: @Id ✔ … you need to have one but can leave generation to the provider, we'll see later @Table( uniqueConstraints=@UniqueConstraint( columnNames={"FIRSTNAME", "LASTNAME"}) )
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 33 Basic Mappings The attributes/fields: @Column ✔ Defines a lot of switches like:  name=“TABLE_NAME“ if the field identifier is not appropriate or whatsoever.  unique=true (default is false),  insertable/updateable=false (default is true)  table=“OTHER_TABLE“, default is „“ (same table)  length=8 (default is 255)  precision=2, column decimal precision (default is 0)  scale=1, column decimal scale if useful (default is 0)
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 34 Example @Entity public class User implements Serializable { private static final long serialVersionUID = 4616273573516105734L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @NotNull @Size(min = 4, max = 8) @Column(unique = true) private String user; @NotNull @Size(min = 8) private String password; @ManyToOne(cascade={CascadeType.ALL}) private Person person; public User() { } public Person getPerson() { return person; }
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 35 The EntityManager ✔ A service provided by JPA, all access to an entity goes through this service. ✔ Provides a query API and life cycle methods for the entity. ✔ To interact with entity beans, just plain Java is needed. ✔ Entity beans and EntityManager do not require an application server to be used.  You can use Java persistence in unit tests and standalone Java applications like any Java library. ✔ Two options for clients to use the EntityManager:  container managed, container runtime is responsible for providing and determining the EntityManager for applications.  application managed, the application is responsible for the EntityManager itself.
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 36 Application-managed EntityManager In Java SE applications you must use an EntityManagerFactory. ✔ How to get the EntityManagerFactory in Java SE: EntityManagerFactory factory; factory = Persistence.createEntityManagerFactory(“persistence-unit-name”); EntityManager manager = factory.createEntityManager(); ... // do some work with the EntityManager ... // close factory and releasing any resources that it holds factory.close();
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 37 Container-managed EntityManager ✔ Only available within an application server. ✔ The container injects the EntityManager, once Annotation @PersistenceContext is used.  unitName is the name of the persistence-unit which will be used.  (optional) type can set to EXTENDED in stateful SessionBeans, default is TRANSACTION-SCOPED. ✔ Alternatively the JNDI lookup can be used. //use the field injection @PersistenceContext(unitName=”persistence-unit-name”) private EntityManager objEntityManager; //alternatively the injection can be used on the setter @PersistenceContext(unitName=”persistence-unit-name”) public void setFactory(EntityManager f){ this.objEntityManager = f; } // or use SessionContext lookup method EntityManager objEntityManager = (EntityManager)ctx.lookup(“java:comp/env/persistence-unit-name”)
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 38 In search for definitions Persistence Unit ✔ A persistence unit defines a set of all entity classes that are managed by EntityManager instances in an application. ✔ This set of entity classes represents the data contained within a single data store. ✔ Persistence units are defined by the persistence.xml configuration file. The JAR file or directory whose META-INF directory contains persistence.xml is called the root of the persistence unit. The scope of the persistence unit is determined by the persistence unit’s root. ✔ Each persistence unit must be identified with a name that is unique to the persistence unit’s scope.
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 39 In search for definitions PersistenceContext ✔ A persistence context is a set of managed entity instances that exist in a particular data store. ✔ The EntityManager interface defines the methods that are used to interact with the persistence context.
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 40 Deployment Descriptor Condensed and simple: ✔ The JPA specification requires a simple XML deployment descriptor. ✔ The deployment descriptor is called persistence.xml and is placed in the META-INF directory. (which has to be on the classpath in case of JavaSE) ✔ the persistence.xml configures basic things like:  name of the persistence unit service.  the used datasource / database  defines where to look for entity beans. mandatory
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 41 <?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0"> <persistence-unit name="user_pu" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <class>de.brockhaus.userMgmt.backend.User</class> <class>de.brockhaus.userMgmt.backend.Person</class> <properties> <property name="hibernate.connection.driver_class" value="org.h2.Driver"/> <property name="hibernate.connection.username" value="sa"/> <property name="hibernate.connection.password" value=""/> <!-- TODO specify your database URL --> <property name="hibernate.connection.url" value="jdbc:h2:tcp://YOUR_DATABASE_LOCATION/> <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/> <!-- automatic 'treatment' of database: validate | update | create | create-drop --> <property name="hibernate.hbm2ddl.auto" value="update"/> <!-- displaying and formatting features regarding SQL --> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.format_sql" value="true"/> </properties> </persistence-unit> </persistence> Example: persistence.xml (JavaSE) mandatory
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 42 The EntityManager Class Three kinds of operations: ✔ Entity live cycle management  persist() a new instance is managed and persistent.  remove() destroy entities data in the database.  merge() merge the state of the given entity into the current persistence context. ✔ Database synchronisation operations  flush() synchronize the persistence context.  refresh() refreshes the instance from database.
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 43 The EntityManager Class Three kinds of operations: ✔ Entity lookup and queries  find() find by primary key and initialize the state based on the lazy-loading policies of each property.  getReference() get an instance, whose state may be lazily fetched.  createQuery() locate persistence object by using JP-QL.
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 44 Example of using the Entity Manager @Stateless(mappedName = "ejb/facade/UserManagementService") @Remote(UserManagementService.class) public class UserManagementServiceBean implements UserManagementService { private EntityManager em; public UserManagementServiceBean() { this.em = EntityManagerHelper.getEntityManager(); } public User createUser(User u) { EntityTransaction tx = em.getTransaction(); try { tx.begin(); em.persist(u); tx.commit(); } catch(Exception e) { e.printStackTrace(); tx.rollback(); } return u; }
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 45 Queries and JPQL ✔ Language to define queries for finder and select methods.  compiled to the target language.  is similar to SQL ✔ The query references the abstract schema name of a bean as its model, defined as the classname of the entitiy (default mapping) or overwritten with the @table annotation on class level. ✔ Used to define the query methods.  Finder methods  Select Methods ✔ In the JP-QL has four clauses: - Select clause  Optional From clause  Optional Where clause  Optional Order By clause
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 46 Named Queries ✔ Are a type of static queries. ✔ Define in the code or overwritten with deployment descriptor (can be changed by administrator or deployer then) @Entity @NamedQueries({ @NamedQuery(name = "User.findByCredentials", query = " FROM User AS u WHERE u.user = :user AND password = :pwd" ) } ) public class User implements Serializable { private static final long serialVersionUID = 4616273573516105734L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id;
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 47 Invocation ✔ Implements at respective service ✔ Make use of TypedQuery<X> (EJB 3.1 only) public User findUserByCredentials(String user, String pwd) { TypedQuery<User> tQuery = em.createNamedQuery("User.findUserByCredentials", User.class); tQuery.setParameter("user", user); tQuery.setParameter("pwd", pwd); return tQuery.getSingleResult(); }
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 48 Lab Implement JPA (not more than 15 min.)
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 49 Module Entity, Control and Boundary
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 50 The dozens of technologies ✔ … but no concise guideline to structure these ✔ To provide an (functional) example:  The ISA 95 international standard for developing an automated interface between enterprise and control systems.  This standard has been developed for global manufacturers. It was developed to be applied in all industries, and in all sorts of processes, like batch processes, continuous and repetitive processes.
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 51 ISA 95 The activity model of ISA 95 ✔ How to apply the technologies? ✔ Guess you can easily find similar in your domain Detailed Scheduling Resource Management Tracking Dispatching Definition Management Data Collection Execution Analysis
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 52 Cohesion From wikipedia ✔ The measure how strongly related and focused the the various responsibilities of a software module are. ✔ Modules with high cohesion tend to be preferrable as high cohesion is associated with various benefits like robustness, reliability and reusability. In Java EE ✔ Main responsibility of a business component is the exposure of it's specifications or contract and hiding it's realization
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 53 ECB Pattern (get the things sorted) Entity Control Boundary ✔ Based upon Robustness Diagrams (http://www.agilemodeling.com/artifacts/robustnessDiagram.htm)  Boundary: user interface  Control: actual process or activity  Entity: a concept from an enterprise context. ✔ Elements are generic enough to be mapped either to service- oriented or object-oriented architectures. Boundary Control Entity Adam Bien
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 54 ECB Pattern in JavaEE Boundary: ✔ Service Façade or Gateway, exposes functionality of a component by means of several protocols and technologies Control: ✔ reusable, fine-grained service behind a boundary ✔ might be optional or generic in simple use cases such as CRUD or MDM (master data management) Entity: ✔ object-oriented or procedural domain objects. ✔ In most cases mapped to a single JPA entity
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 55 Mapping ECB to Java Business components ✔ Can be mapped directly to Java packages, e.g. de.brockhaus.userMgmt ✔ Boundary, control and entity can be mapped to subpackages within the business component package:  de.brockhaus.userMgmt.boundary  de.brockhaus.userMgmt.control  de.brockhaus.userMgmt.entity ✔ The whole business component might be realized as an individual jar ✔ Interfaces and „exchange“ objects might be put into a dedicated services archive (although we don't do during this training)
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 56 Common Interfaces, Business Objects, Exceptions Architectural blueprint Boundary Control Entity
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 57 ECB as a general guideline ✔ Fits nicely into the reference architecture as we can model every activity within the activity model as ECB component ✔ Still there are a lot of Design Patterns which might be applied to improve the design.
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 58 Boundary Control Entity DAO & Domain Store Generic DAO Singleton Service Starter Dual View SOA Facade Lightweight asynchronous Facade Multichannel Facade TO & DTO Paginator Bean Locator Multichannel Facade Resource Binder Payload Extractor Aynchronous Resource Integrator Infrastructure Patterns related to ECB Pattern
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 59 Lab Implement ECB Pattern (not more than 15 min.)
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 60 Review Session Review: ✔ What is the ECB pattern good for?
Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 61 Recommeded reading ✔ http://java.sun.com/blueprints/corej2eepatterns/ ✔ http://www.corej2eepatterns.com/Patterns2ndEd/ ✔ Adam Bien, J2EE Patterns, Addison Wesley 2002, ISBN: 3-8273-1903-X ✔ Floyd Marinescu, Ed Roman: Ejb Design Patterns: Advanced Patterns, Processes, and Idioms; Wiley & Sons, ISBN-10: 0471208310 ✔ And other ... Photo: Bundesarchiv

Java EE Pattern: Entity Control Boundary Pattern and Java EE

  • 1.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 1 Session: Pragmatic Architecture Java EE, latest brew Entity, Control and Boundary
  • 2.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 2 Objectives Learn about: ✔ Get an overview about the latest Java EE technologies used at the backend ✔ A warming up for the architectural aspects ✔ Get an idea about the ECB pattern as a general principle
  • 3.
    3 Where are weright now? Existing architectures Architecture Patterns Customer & Business needs Further requirements Reference Architecture mining proven concepts vision analysis evolution triggering
  • 4.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 4 Some orientation Consumer Consumer Layer Integration Layer Business Process Layer Services Layer Component Layer OS Layer
  • 5.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 5 Module Java EE, latest brew
  • 6.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 6 The rise of Spring and Hibernate Spring ✔ Application framework ✔ Dependency Injection ✔ AOP support ✔ Non-invasiveness as a basic principle ✔ O/R persistence support for various frameworks Hibernate ✔ POJO based O/R persistence Spring and Hibernate became a popular alternative to J2EE development.
  • 7.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 7 Don't look back Until V5.0 Enterprise Java really had a bad reputation: ✔ Too complex, especially when it comes to EJBs (Home Interface, Local Interface, Remote Interface, Bean class, Deployment Descriptor) ✔ Too inflexible, especially when it comes to CMP (heavy-weighted objects, Session Facades and Value Objects) ✔ Outdated, especially when it comes to AOP and DI ✔ Too expensive, especially when it comes to app-servers ✔ Too ... But things change!
  • 8.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 8 Right now Java EE V5.0 (and higher) has a lot to provide: ✔ Context and Dependency Injection (CDI) ✔ Validators ✔ JPA 2.x ✔ Convention over Configuration ✔ And …its a standard supported by various vendors
  • 9.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 9 Convention over Configuration ✔ A principle borrowed from the Ruby on Rails tribe ✔ Decreases the number of decisions to be made and configurations to be done by default configurations ✔ Annotations replace XDoclet's JavaDoc tags:  Compiler checks  Type safety (instead if just strings) ✔ All information previously stored in the deployment descriptor file (the meta-data hell) now moved into annotations (but DD file still optional and overwrites Annotation)
  • 10.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 10 XDoclet & Annotations ✔ XDoclet: ✔ Annotation: /** * @ejb.bean name = „UserMgmtService“ view-type = „remote“ */ public class UserMgmtService implements SessionBean { … } @Stateless @Remote(UsrMgmt.class) public class UserMgmtService implements UsrMgmt { … }
  • 11.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 11 Annotations @Stateless: ✔ Marks the class as a Stateless Session Bean, no need to implement an interface or to extend a class ✔ Provides a default transaction handling (every method will be executed in a single transaction) @LocalBean ✔ All public methods will be exposed to local clients, no need to implement a dedicated interface ✔ Local clients - like Servlets or other EJBs – might obtain a reference by means of dependecy injection.
  • 12.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 12 Lab Implement Stateless Session Bean (not more than 15 min.)
  • 13.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 13 Dependency injection ✔ Providing an external dependency (any ressource like another EJB, a DataSource, a JMS destination …) to a software component. ✔ Previously (within a client bean) public void init() { try { ctx = new InitialContext(); facade = (UserManagementService) ctx.lookup("ejb/facade/UserManagementService"); } catch (NamingException e) { e.printStackTrace(); } }
  • 14.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 14 Dependency Injection In our days: ✔ No Exception handling, no casting issues, no misspelling, no deployment descriptors, no ... @Stateless @Remote(Client.class) public class ClientBean implements Client { @EJB private UserMgmtLocal userMgmt; ... }
  • 15.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 15 Lab Implement Dependency Injection (not more than 15 min.)
  • 16.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 16 Bean Validation JSR 303: Bean Validation ✔ you can use it anywhere you like:  front-end,  back-end,  even DTO (if you follow this pattern) ✔ reference implementation is Hibernate Validator v4.x ✔ validation on two different levels: attribute or entire bean ✔ i18n ready and message are parameterized ✔ extensible with your own validators ✔ configurable with annotations or XML
  • 17.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 17 Several build-in Validators ✔ Quite a few Validators are already implemented within the javax.validator package, some examples: @AssertFalse / @AssertTrue The value of the field or property must be false / true @Max / @Min The value of the field or property must be an integer value lower / higher than or equal to the number in the value element. @NotNull The value of the field must not be null @Past / @Future The date has to be in the past / future ... @see link below
  • 18.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 18 Example ✔ Considering a user, we might want to ensure the following: public class User implements Serializable { @NotNull private long id; @NotNull @Size(min = 4, max = 8) private String user; @NotNull @Size(min = 8, max = 15) private String password;
  • 19.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 19 Example: evaluating ✔ If not done by the container (which is the usual case), we can evaluate 'manually' public void testValidation() { Set<ConstraintViolation<User>> violations = validator.validate(user); System.out.println("Number of violations: " + violations.size()); for (ConstraintViolation<User> constraintViolation : violations) { System.out.println(constraintViolation.getPropertyPath() + " " + constraintViolation.getMessage()); } } @BeforeClass public static void init() { user = new User(); user.setPassword("abcdef"); factory = Validation.buildDefaultValidatorFactory(); validator = factory.getValidator(); }
  • 20.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 20 Writing your own validator ✔ … not covered if this training! ✔ Though the JSR defines a whole bunch of standard constraint annotations such as @NotNull, @Size, @Min or @AssertTrue, there will always be validation requirements, for which these standard annotations won't suffice. ✔ Being aware of that problem, the specification authors laid out the API in an expansible manner, that allows users to define their custom constraint annotations. ✔ A nice tutorial can be found here: http://musingsofaprogrammingaddict.blogspot.de/2009/02/getting-started-with- jsr-303-bean.html
  • 21.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 21 Lab Implement Validator (not more than 15 min.)
  • 22.
    22 AOP / Interceptors Aspect-orientedprogramming ✔ A paradigm more than a pattern. ✔ Certain software properties cannot be isolated in single functional unit, instead they crosscut multiple components ✔ Such cross-cutting concerns result in tangled code that is hard to develop and maintain, e.g.:  Logging  Authentication
  • 23.
  • 24.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 24 Interceptors ✔ Introduced with EJB 3.0 ✔ Are one of the Java EE pendant to Aspects (the other is a Servlet Filter). ✔ Are pretty easy to implement
  • 25.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 25 Interceptors ✔ Provided EJBs with a rudimentary Aspect Oriented Programming system. ✔ Enable a clean distinction of business logic and meta or support code. ✔ Are classes (distinct form the beans themself). ✔ Interpose themselves on methods calls or life cycle events. ✔ Have access to information about the business method that triggered it, including method names an parameters. ✔ Can halt processing of the business method. ✔ Can be used on session and message-driven beans. ✔ A bean can have any number of Interceptors. ✔ Common uses for interceptors are security checking, logging or auditing functions. separation of concerns
  • 26.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 26 An Interceptor public class PerformanceInterceptor { private Logger log = Logger.getLogger(this.getClass().getName()); @AroundInvoke public Object onMethodCall(InvocationContext ctx) throws Exception { log.info(">>> Entering interceptor"); long start = System.currentTimeMillis(); log.info("Invocation of: " + ctx.getMethod().getName()); try { // go ahead using the invocation context return ctx.proceed(); } finally { long end = System.currentTimeMillis(); long duration = end - start; log.info("Duration of invocation: " + duration); } } }
  • 27.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 27 Intercepting @Stateless(mappedName = "ejb/facade/UserManagementService") @Remote(UserManagementService.class) // alternatively you can use the interceptor here as well public class UserManagementServiceBean implements UserManagementService { // use interceptor (comment if using ejb-jar.xml) @Interceptors(PerformanceInterceptor.class) public User findUserByCredentials(String user, String pwd) { User u = new User("peterp", "neverland"); return u; } public User createUser(User u) { return u; } } ✔ Annotate method(s) or class
  • 28.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 28 Configuration by XML ✔ The recommened way as we can change without recompilation <?xml version="1.0" encoding="UTF-8"?> <ejb-jar version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd"> <assembly-descriptor> <interceptor-binding> <ejb-name>UserManagementServiceBean</ejb-name> <interceptor-class> de.brockhaus.userMgmt.backend.util.PerformanceInterceptor </interceptor-class> <method> <method-name>findUserByCredentials</method-name> <method-params> <method-param>java.lang.String</method-param> <method-param>java.lang.String</method-param> </method-params> </method> </interceptor-binding> </assembly-descriptor>
  • 29.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 29 Lab Implement Interceptor (not more than 15 min.)
  • 30.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 30 Persistent Entities / JPA 2.x ✔ JPA defines a way to map regular, plain old Java objects (POJOs) to a database. ✔ These plain Java objects are called persistent entities (and no longer EntityBeans):  they can be used in regular Java applications outside of an application server and can even be used to transfer data between a client and a server.  In EJB 2.1 specification, entity beans were „heavyweight“: • dependent on the application server. • dependent on the entire Java EE runtime environment. • cause high memory consumption.
  • 31.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 31 Parts of JPA The JPA Specification consists of three parts: ✔ Entities  business objects.  persisted in the database. ✔ Persistence unit  A group of a finite set of Entity bean classes.  Associated to a particular database so that the persistence provider knows where, how, and with what kind of database it is interacting.  Are defined in an xml deployment descriptor named persistence.xml. ✔ EntityManager  The EntityManager provides an API to maintain the Entities.  provides the persistence context for a particular persistence unit.
  • 32.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 32 Basic Mappings The entity: @Entity ✔ Defines the class as persistent Entity The Table: @Table ✔ By default tablename == classname ✔ You can change this (veeeery needful in case of reserved word like USER) by @Table(name=“TABLENAME“) ✔ You can define unique constraints: The primary key: @Id ✔ … you need to have one but can leave generation to the provider, we'll see later @Table( uniqueConstraints=@UniqueConstraint( columnNames={"FIRSTNAME", "LASTNAME"}) )
  • 33.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 33 Basic Mappings The attributes/fields: @Column ✔ Defines a lot of switches like:  name=“TABLE_NAME“ if the field identifier is not appropriate or whatsoever.  unique=true (default is false),  insertable/updateable=false (default is true)  table=“OTHER_TABLE“, default is „“ (same table)  length=8 (default is 255)  precision=2, column decimal precision (default is 0)  scale=1, column decimal scale if useful (default is 0)
  • 34.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 34 Example @Entity public class User implements Serializable { private static final long serialVersionUID = 4616273573516105734L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @NotNull @Size(min = 4, max = 8) @Column(unique = true) private String user; @NotNull @Size(min = 8) private String password; @ManyToOne(cascade={CascadeType.ALL}) private Person person; public User() { } public Person getPerson() { return person; }
  • 35.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 35 The EntityManager ✔ A service provided by JPA, all access to an entity goes through this service. ✔ Provides a query API and life cycle methods for the entity. ✔ To interact with entity beans, just plain Java is needed. ✔ Entity beans and EntityManager do not require an application server to be used.  You can use Java persistence in unit tests and standalone Java applications like any Java library. ✔ Two options for clients to use the EntityManager:  container managed, container runtime is responsible for providing and determining the EntityManager for applications.  application managed, the application is responsible for the EntityManager itself.
  • 36.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 36 Application-managed EntityManager In Java SE applications you must use an EntityManagerFactory. ✔ How to get the EntityManagerFactory in Java SE: EntityManagerFactory factory; factory = Persistence.createEntityManagerFactory(“persistence-unit-name”); EntityManager manager = factory.createEntityManager(); ... // do some work with the EntityManager ... // close factory and releasing any resources that it holds factory.close();
  • 37.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 37 Container-managed EntityManager ✔ Only available within an application server. ✔ The container injects the EntityManager, once Annotation @PersistenceContext is used.  unitName is the name of the persistence-unit which will be used.  (optional) type can set to EXTENDED in stateful SessionBeans, default is TRANSACTION-SCOPED. ✔ Alternatively the JNDI lookup can be used. //use the field injection @PersistenceContext(unitName=”persistence-unit-name”) private EntityManager objEntityManager; //alternatively the injection can be used on the setter @PersistenceContext(unitName=”persistence-unit-name”) public void setFactory(EntityManager f){ this.objEntityManager = f; } // or use SessionContext lookup method EntityManager objEntityManager = (EntityManager)ctx.lookup(“java:comp/env/persistence-unit-name”)
  • 38.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 38 In search for definitions Persistence Unit ✔ A persistence unit defines a set of all entity classes that are managed by EntityManager instances in an application. ✔ This set of entity classes represents the data contained within a single data store. ✔ Persistence units are defined by the persistence.xml configuration file. The JAR file or directory whose META-INF directory contains persistence.xml is called the root of the persistence unit. The scope of the persistence unit is determined by the persistence unit’s root. ✔ Each persistence unit must be identified with a name that is unique to the persistence unit’s scope.
  • 39.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 39 In search for definitions PersistenceContext ✔ A persistence context is a set of managed entity instances that exist in a particular data store. ✔ The EntityManager interface defines the methods that are used to interact with the persistence context.
  • 40.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 40 Deployment Descriptor Condensed and simple: ✔ The JPA specification requires a simple XML deployment descriptor. ✔ The deployment descriptor is called persistence.xml and is placed in the META-INF directory. (which has to be on the classpath in case of JavaSE) ✔ the persistence.xml configures basic things like:  name of the persistence unit service.  the used datasource / database  defines where to look for entity beans. mandatory
  • 41.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 41 <?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0"> <persistence-unit name="user_pu" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <class>de.brockhaus.userMgmt.backend.User</class> <class>de.brockhaus.userMgmt.backend.Person</class> <properties> <property name="hibernate.connection.driver_class" value="org.h2.Driver"/> <property name="hibernate.connection.username" value="sa"/> <property name="hibernate.connection.password" value=""/> <!-- TODO specify your database URL --> <property name="hibernate.connection.url" value="jdbc:h2:tcp://YOUR_DATABASE_LOCATION/> <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/> <!-- automatic 'treatment' of database: validate | update | create | create-drop --> <property name="hibernate.hbm2ddl.auto" value="update"/> <!-- displaying and formatting features regarding SQL --> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.format_sql" value="true"/> </properties> </persistence-unit> </persistence> Example: persistence.xml (JavaSE) mandatory
  • 42.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 42 The EntityManager Class Three kinds of operations: ✔ Entity live cycle management  persist() a new instance is managed and persistent.  remove() destroy entities data in the database.  merge() merge the state of the given entity into the current persistence context. ✔ Database synchronisation operations  flush() synchronize the persistence context.  refresh() refreshes the instance from database.
  • 43.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 43 The EntityManager Class Three kinds of operations: ✔ Entity lookup and queries  find() find by primary key and initialize the state based on the lazy-loading policies of each property.  getReference() get an instance, whose state may be lazily fetched.  createQuery() locate persistence object by using JP-QL.
  • 44.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 44 Example of using the Entity Manager @Stateless(mappedName = "ejb/facade/UserManagementService") @Remote(UserManagementService.class) public class UserManagementServiceBean implements UserManagementService { private EntityManager em; public UserManagementServiceBean() { this.em = EntityManagerHelper.getEntityManager(); } public User createUser(User u) { EntityTransaction tx = em.getTransaction(); try { tx.begin(); em.persist(u); tx.commit(); } catch(Exception e) { e.printStackTrace(); tx.rollback(); } return u; }
  • 45.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 45 Queries and JPQL ✔ Language to define queries for finder and select methods.  compiled to the target language.  is similar to SQL ✔ The query references the abstract schema name of a bean as its model, defined as the classname of the entitiy (default mapping) or overwritten with the @table annotation on class level. ✔ Used to define the query methods.  Finder methods  Select Methods ✔ In the JP-QL has four clauses: - Select clause  Optional From clause  Optional Where clause  Optional Order By clause
  • 46.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 46 Named Queries ✔ Are a type of static queries. ✔ Define in the code or overwritten with deployment descriptor (can be changed by administrator or deployer then) @Entity @NamedQueries({ @NamedQuery(name = "User.findByCredentials", query = " FROM User AS u WHERE u.user = :user AND password = :pwd" ) } ) public class User implements Serializable { private static final long serialVersionUID = 4616273573516105734L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id;
  • 47.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 47 Invocation ✔ Implements at respective service ✔ Make use of TypedQuery<X> (EJB 3.1 only) public User findUserByCredentials(String user, String pwd) { TypedQuery<User> tQuery = em.createNamedQuery("User.findUserByCredentials", User.class); tQuery.setParameter("user", user); tQuery.setParameter("pwd", pwd); return tQuery.getSingleResult(); }
  • 48.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 48 Lab Implement JPA (not more than 15 min.)
  • 49.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 49 Module Entity, Control and Boundary
  • 50.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 50 The dozens of technologies ✔ … but no concise guideline to structure these ✔ To provide an (functional) example:  The ISA 95 international standard for developing an automated interface between enterprise and control systems.  This standard has been developed for global manufacturers. It was developed to be applied in all industries, and in all sorts of processes, like batch processes, continuous and repetitive processes.
  • 51.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 51 ISA 95 The activity model of ISA 95 ✔ How to apply the technologies? ✔ Guess you can easily find similar in your domain Detailed Scheduling Resource Management Tracking Dispatching Definition Management Data Collection Execution Analysis
  • 52.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 52 Cohesion From wikipedia ✔ The measure how strongly related and focused the the various responsibilities of a software module are. ✔ Modules with high cohesion tend to be preferrable as high cohesion is associated with various benefits like robustness, reliability and reusability. In Java EE ✔ Main responsibility of a business component is the exposure of it's specifications or contract and hiding it's realization
  • 53.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 53 ECB Pattern (get the things sorted) Entity Control Boundary ✔ Based upon Robustness Diagrams (http://www.agilemodeling.com/artifacts/robustnessDiagram.htm)  Boundary: user interface  Control: actual process or activity  Entity: a concept from an enterprise context. ✔ Elements are generic enough to be mapped either to service- oriented or object-oriented architectures. Boundary Control Entity Adam Bien
  • 54.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 54 ECB Pattern in JavaEE Boundary: ✔ Service Façade or Gateway, exposes functionality of a component by means of several protocols and technologies Control: ✔ reusable, fine-grained service behind a boundary ✔ might be optional or generic in simple use cases such as CRUD or MDM (master data management) Entity: ✔ object-oriented or procedural domain objects. ✔ In most cases mapped to a single JPA entity
  • 55.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 55 Mapping ECB to Java Business components ✔ Can be mapped directly to Java packages, e.g. de.brockhaus.userMgmt ✔ Boundary, control and entity can be mapped to subpackages within the business component package:  de.brockhaus.userMgmt.boundary  de.brockhaus.userMgmt.control  de.brockhaus.userMgmt.entity ✔ The whole business component might be realized as an individual jar ✔ Interfaces and „exchange“ objects might be put into a dedicated services archive (although we don't do during this training)
  • 56.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 56 Common Interfaces, Business Objects, Exceptions Architectural blueprint Boundary Control Entity
  • 57.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 57 ECB as a general guideline ✔ Fits nicely into the reference architecture as we can model every activity within the activity model as ECB component ✔ Still there are a lot of Design Patterns which might be applied to improve the design.
  • 58.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 58 Boundary Control Entity DAO & Domain Store Generic DAO Singleton Service Starter Dual View SOA Facade Lightweight asynchronous Facade Multichannel Facade TO & DTO Paginator Bean Locator Multichannel Facade Resource Binder Payload Extractor Aynchronous Resource Integrator Infrastructure Patterns related to ECB Pattern
  • 59.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 59 Lab Implement ECB Pattern (not more than 15 min.)
  • 60.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 60 Review Session Review: ✔ What is the ECB pattern good for?
  • 61.
    Copyright by BrockhausGmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt 61 Recommeded reading ✔ http://java.sun.com/blueprints/corej2eepatterns/ ✔ http://www.corej2eepatterns.com/Patterns2ndEd/ ✔ Adam Bien, J2EE Patterns, Addison Wesley 2002, ISBN: 3-8273-1903-X ✔ Floyd Marinescu, Ed Roman: Ejb Design Patterns: Advanced Patterns, Processes, and Idioms; Wiley & Sons, ISBN-10: 0471208310 ✔ And other ... Photo: Bundesarchiv

Editor's Notes

  • #18 Complete list: http://docs.oracle.com/javaee/6/tutorial/doc/gircz.html
  • #29 Intercepting all methods of a certain EJB &amp;lt;assembly-descriptor&amp;gt; &amp;lt;interceptor-binding&amp;gt; &amp;lt;ejb-name&amp;gt;UserManagementServiceBean&amp;lt;/ejb-name&amp;gt; &amp;lt;interceptor-class&amp;gt; de.brockhaus.userMgmt.backend.util.PerformanceInterceptor &amp;lt;/interceptor-class&amp;gt; &amp;lt;!-- uncomment and only this method will be intercepted &amp;lt;method&amp;gt; &amp;lt;method-name&amp;gt;findUserByCredentials&amp;lt;/method-name&amp;gt; &amp;lt;method-params&amp;gt; &amp;lt;method-param&amp;gt;java.lang.String&amp;lt;/method-param&amp;gt; &amp;lt;method-param&amp;gt;java.lang.String&amp;lt;/method-param&amp;gt; &amp;lt;/method-params&amp;gt; &amp;lt;/method&amp;gt; --&amp;gt; &amp;lt;/interceptor-binding&amp;gt; &amp;lt;/assembly-descriptor&amp;gt; Intercepting all EJBs (Default Interceptor): &amp;lt;assembly-descriptor&amp;gt; &amp;lt;interceptor-binding&amp;gt; &amp;lt;ejb-name&amp;gt;*&amp;lt;/ejb-name&amp;gt; &amp;lt;interceptor-class&amp;gt; de.brockhaus.userMgmt.backend.util.PerformanceInterceptor &amp;lt;/interceptor-class&amp;gt; &amp;lt;/interceptor-binding&amp;gt; &amp;lt;/assembly-descriptor&amp;gt; How do you exclude the DefaultInterceptor ? If you have defined a default interceptor for all your EJB in a jar file, you can use the following annotation to exclude it and instead execute the Interceptor in the class: @ExcludeDefaultInterceptors Order of Interception The default interceptor is invoked at first. Then Bean level interceptors are invoked and, at last, method level interceptors. If you declare a list of interceptors in your xml/annotations the interceptors are invoked in the order in which they are declared in the annotation.
  • #31 Generally, an entity EJB class represents a table in a database, and each instance of the entity EJB represents a single row in the table. It is possible to define an entity EJB that represents multiple rows from tables related by a join in the data model schema. In most cases this is not done. Entity beans are more complex than session beans. There lifecycle management is a bit more involved, and the container has more work to do to ensure that the bean’s state is always synchronized with the data in the row in the table.
  • #32 Generally, an entity EJB class represents a table in a database, and each instance of the entity EJB represents a single row in the table. It is possible to define an entity EJB that represents multiple rows from tables related by a join in the data model schema. In most cases this is not done. The persistence units group a set of Entities together and bind them to a database. So the persistence units define where, how and with what kind of database this entities are interact. The EntityManager in JEE applications are managed by the container and can be get with dependency injection. He is responsible for the life-cycle management of the beans.
  • #41 The persistence.xml file is one of the only deployment descriptors which are mandatory in EJB 3.0. Most of the other DD&amp;apos;s which was known in EJB 2.1 are know optional. The persistence.xml file defines the databases which should be used with the entity beans. It defines the persistence units, which are in difference to the two other parts of JPA are not Java classes. Each entity must be assigned to one persistence unit, so that the container know where and how to map this entities to the database. The contents of the persistence.xml file are discussed on the next slides.
  • #43 Persist, merge and remove operations may or may not happen immediately, the reason for this is to batch work and then execute it thus saving on the number of database calls which increases performance. By default the database flush mode is set to AUTO, this means that the EntityManager performs a flush operation when needed, this normally occurs at the end of a transaction or when the persistence context is closed for application managed or extended-scope EntityManagers. You can set the EntityManager flush mode to COMMIT, thus the persistence provider will only synchronize with the database when the transaction commits, however it will be your responsibility to synchronize entity state with the database before executing a query, if you don&amp;apos;t do this you could end up with an inconsistent application. You can also explicitly flush the EntityManager by using the flush method. for more details see: http://java.sun.com/javaee/5/docs/api/javax/persistence/EntityManager.html
  • #44 for more details see: http://java.sun.com/javaee/5/docs/api/javax/persistence/EntityManager.html Regrading getReference: @see: http://stackoverflow.com/questions/1607532/when-to-use-entitymanager-find-vs-entitymanager-getreference
  • #45 The EntityManagerHelper: public class EntityManagerHelper { // create EntityManagerFactory using clazz Persistence private static final EntityManagerFactory emf = Persistence.createEntityManagerFactory(&amp;quot;user_pu&amp;quot;); // create EntityManager using the EntityManagerFactory private static final EntityManager em = emf.createEntityManager(); public static EntityManager getEntityManager() { return em; } }
  • #46 The EJB QL query specification language is used to specify data selection statements to support finder and select statements defined within an entity bean. Unlike SQL, it only supports the extraction of data. It cannot be used to perform insertions or updates of data. Insertions and updates are performed implicitly as the result of operations on the bean (data value changes) and its home (creation and removal). The container is responsible for generating the code necessary to support these types of operations. JP-QL statements are specified in the deployment descriptor for each query method for the enterprise bean. At deployment time the deployment tool will read the JP-QL and generate the database specific commands necessary to perform the requested database operations. In the Deployment Descriptor each CMP Entity bean has an abstract schema name. This way the persistent view and the component view of the Entity is separated.
  • #54 You can see that there is no tight coupling between the classes. Both can be changed independently without affecting each other. Of course, if there is any change in the public methods of Class Callee, Class Caller needs to change as well. But how Object &amp;quot;c&amp;quot; is created and managed is not decided in the implementation of Object &amp;quot;a&amp;quot;. Instead, the IoC framework uses the setB() method in Object &amp;quot;a&amp;quot; to inject Object &amp;quot;c&amp;quot;.