Transcript of Entity Control Boundary Pattern and Java EE
1. Copyright by Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung untersagt 1 Session: Pragmatic
Architecture Java EE, latest brew Entity, Control and Boundary
2. Copyright by Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 we right now? Existing architectures
Architecture Patterns Customer & Business needs Further
requirements Reference Architecture mining proven concepts vision
analysis evolution triggering
4. Copyright by Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung untersagt 4 Some orientation
Consumer Consumer Layer Integration Layer Business Process Layer
Services Layer Component Layer OS Layer
5. Copyright by Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung untersagt 5 Module Java EE, latest
brew
6. Copyright by Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung untersagt 12 Lab Implement Stateless
Session Bean (not more than 15 min.)
13. Copyright by Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung untersagt 15 Lab Implement
Dependency Injection (not more than 15 min.)
16. Copyright by Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung untersagt 19 Example: evaluating If
not done by the container (which is the usual case), we can
evaluate 'manually' public void testValidation() { Set>
violations = validator.validate(user); System.out.println("Number
of violations: " + violations.size()); for (ConstraintViolation
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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung untersagt 21 Lab Implement Validator
(not more than 15 min.)
22. 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. 23 Interceptor Non UML: EJB Container Interceptor(s)
Request Response
24. Copyright by Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung untersagt 28 Configuration by XML
The recommened way as we can change without recompilation
UserManagementServiceBean
de.brockhaus.userMgmt.backend.util.PerformanceInterceptor
findUserByCredentialsjava.lang.Stringjava.lang.String
29. Copyright by Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung untersagt 29 Lab Implement
Interceptor (not more than 15 min.)
30. Copyright by Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 units root. Each
persistence unit must be identified with a name that is unique to
the persistence units scope.
39. Copyright by Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung untersagt 41
org.hibernate.ejb.HibernatePersistencede.brockhaus.userMgmt.backend.Userde.brockhaus.userMgmt.backend.Person
Example: persistence.xml (JavaSE) mandatory
42. Copyright by Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung untersagt 47 Invocation Implements
at respective service Make use of TypedQuery (EJB 3.1 only) public
User findUserByCredentials(String user, String pwd) { TypedQuery
tQuery = em.createNamedQuery("User.findUserByCredentials",
User.class); tQuery.setParameter("user", user);
tQuery.setParameter("pwd", pwd); return tQuery.getSingleResult();
}
48. Copyright by Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung untersagt 48 Lab Implement JPA (not
more than 15 min.)
49. Copyright by Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung untersagt 49 Module Entity, Control
and Boundary
50. Copyright by Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung untersagt 54 ECB Pattern in JavaEE
Boundary: Service Faade 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung untersagt 56 Common Interfaces,
Business Objects, Exceptions Architectural blueprint Boundary
Control Entity
57. Copyright by Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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 Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung untersagt 59 Lab Implement ECB
Pattern (not more than 15 min.)
60. Copyright by Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung untersagt 60 Review Session Review:
What is the ECB pattern good for?
61. Copyright by Brockhaus GmbH, alle Rechte reserviert,
unautorisierte Vervielfltigung 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