Simplifying Microservices & Apps - The art of effortless development - Meetup...
Java EE Pattern: The Control Layer
1. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
1
Session: Pattern of the Control Layer
Singleton
Service Starter
Simple Workflows
2. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
2
Objectives
Learn about:
✔ How to start a service at deploy time
✔ Dealing with timers
✔ The Singleton pattern in Java EE
✔ The State Pattern in conjunction with simple workflows
3. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
3
Some orientation
Consumer
Consumer
Layer
Integration
Layer
Business Process
Layer
Services
Layer
Component
Layer
OS
Layer
4. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
4
ECB Pattern
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
5. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
5
Services, components and patterns
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
6. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
6
Module
Singleton
7. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
7
Singleton
✔ Access to limited resources needs to be shared across user
requests.
✔ Amount of active SLSB is dependent on:
➢ Parallel user requests
➢ Pool settings (min/max)
➢ Both isn't covered by spec.
✔ The solution should be portable
between app.-servers.
8. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
8
Singleton
✔ Most effective in terms of caches,
application-wide configuration
parameters or cyclic actions.
✔ Often combined with Service Starter
(therefore we'll combine both labs)
@Singleton(mappedName = "ejb/facade/ServiceStarter")
@Remote(ServiceStarter.class)
public class ServiceStarterBean implements ServiceStarter
{
...
9. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
9
Module
Service Starter
10. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
10
Service Starter
✔ Some logic needs to be initialized prior to the business logic
✔ Some services might depend on each other
✔ Since EJB 3.1 these initializations are specified, in EJB 3.0 they
were not.
➢ In EJB 3.1: @Startup combined with @PostConstruct
➢ In EJB 3.0: Servlet and <load-on-startup> plus CDI
11. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
11
Example
Think of the following:
✔ Some production data needs to be retrieved for further processing
✔ You have to integrate a 3rd
party system by means of cyclic,
synchronous calls.
✔ Maybe you want to make use of
timers, be aware, you can create
timers from MDBs or Singletons
only.
12. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
12
Example
✔ ServiceStarterBean
@Singleton(mappedName = "ejb/facade/ServiceStarter")
@Startup
@Remote(ServiceStarter.class)
public class ServiceStarterBean implements ServiceStarter
{
private Logger log = Logger.getLogger(ServiceStarterBean.class);
@EJB
private PollingServiceBean pollingService;
/** the timer service */
@Resource
private javax.ejb.TimerService timerService;
@PostConstruct
public void init(){
log.info("initializing");
}
...
13. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
13
Example
✔ ServiceStarterBean (cont.)
@Schedule(second = "*/5", minute="*", hour="*", persistent = false, info="Timer:
external polling")
public void notifyPollingService(){
this.pollingService.doPoll();
}
public void stopTimer(String timerName){
Collection<Timer> timers = this.timerService.getTimers();
for (Timer timer : timers){
if(timer.getInfo().toString().equals(timerName)){
timer.cancel();
log.info("Timer: " + timerName + " has been cancelled");
}
}
15. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
15
Lab
Implement Service Activator
(not more than 15 min.)
16. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
16
Module
Simple Workflows
17. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
17
Simple Workflow
✔ Within the control layer, it might happen, you have to perform
several (identical) steps within different services / methods:
➢ Checking for existence of x, maybe in system y
➢ Calculating amounts of a, b, c (e.g. in a production plan for a certain
period)
➢ ...
✔ You might end up in the idea of decomposition into processes and
activities
➢ Has only little to do with Java EE
➢ Inspired by State Machines and
Workflow Engines
➢ No maintenance of state of a current
workflow instance
18. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
18
The abstract process
An abstract superclass providing methods to:
✔ Proceed (starting the process)
✔ Initialize the process
✔ Finalize the process
19. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
19
The abstract process
public abstract class Process{
private Logger log = Logger.getLogger(Process.class);
public static final int PROCESS_START = 1;
public static final int PROCESS_END = 999;
private int runstate = 1;
private boolean hasFinished = false;
public synchronized void proceed() throws ProcessException{
try{
this.beforeProcess();
while (runstate != Process.PROCESS_END){
runSteps();
}
this.afterProcess();
this.end();
}
catch (ProcessException e) {
...
}
catch (Exception e){
...
}
}
...
20. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
20
The activity
✔ Common interface to all process related activities:
public interface ProcessActivity
{
public <T> T proceedActivity<T>();
}
21. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
21
The activity
✔ Concrete activity (example)
➢ Make use of the constructor to pass parameters
➢ Return whatever you want from processActivity
public class StepOne implements ProcessActivity
{
private Logger log = Logger.getLogger(this.getClass());
private int value;
public StepOne(int value){
this.value = value;
}
public <T> T proceedActivity(){
log.info(this.getClass().getSimpleName() + " invoked");
if(this.value > 99){
return (T) new Boolean(true);
}
else {
return (T) new Boolean(false);
}
}
}
22. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
22
A concrete process
✔ Extend Process and overwrite runSteps() according to the activities
public class SomeProcess extends de.brockhaus.userMgmt.util.Process
{
private int amount;
public SomeProcess(int amount)
{
this.amount = amount;
}
@Override
public void runSteps() throws ProcessException
{
switch(super.getRunstate())
{
case(1): this.triggerStepOne(); break;
case(2): this.triggerStepTwo(); break;
case(3): this.triggerStepThree(); break;
default: super.setRunstate(PROCESS_END);
}
}
23. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
23
A concrete process
✔ Decide upon the activities outcome what needs to be done next
private void triggerStepOne(){
StepOne one = new StepOne(amount);
boolean ret = one.proceedActivity();
if(ret){
super.setRunstate(2);
}
else{
super.setRunstate(3);
}
}
private void triggerStepTwo() {
StepTwo two = new StepTwo();
two.proceedActivity();
super.setRunstate(PROCESS_END);
}
private void triggerStepThree() {
StepThree three = new StepThree();
three.proceedActivity();
super.setRunstate(PROCESS_END);
}
24. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
24
Relation to the control layer
✔ Obviously the process has to be connected to the SLSBs of the
control layer
@Stateless
@Remote(SomeService.class)
public class SomeServiceBean implements SomeService
{
// inject SomeProcess
@Inject
private SomeProcess p;
public void someBusinessMethod(int amount) throws ProcessException
{
// set amount at process
p.setAmount(amount);
// proceed process
p.proceed();
}
}
25. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
25
Some conclusion
Pros
✔ It's pretty simple and effective
✔ Well designed it might help a lot to stay with DRY paradigm
✔ Provides flexibility, just exchange an activity within a process and
the process will behave different.
Cons
✔ Don't think of too many activities, don't
think of fully fledged workflows spanning
several components / modules
✔ No graphical support, no modelling
26. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
26
Lab
Implement Simple Workflows
(State Machine)
(not more than 15 min.)
27. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
27
Review
Session Review:
✔ @PostConstruct, what is this good for?
✔ Can you provide some examples of using Singletons in Java EE?
✔ Why do we have processes and services in the example and what
makes the difference to workflow engines?
28. Copyright by Brockhaus GmbH, alle Rechte reserviert, unautorisierte Vervielfältigung untersagt
28
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
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 &quot;c&quot; is created and managed is not decided in the implementation of Object &quot;a&quot;. Instead, the IoC framework uses the setB() method in Object &quot;a&quot; to inject Object &quot;c&quot;.
Workflows can be described as :
Sequential Workflow
State Machine Workflow
A Sequential Work Flow is a top-Down process, also known as a Human Flow Process, where the activities emerge from a beginning situation and end after a predefined sequence of steps.
The State Machine Workflow does not have a defined path but signifies a set of states and transitions between these states.
Sequential Workflows are self-driven. Once they are initiated, they have an absolutely predictable behavior throughout the execution of the activities.
State Machine Workflows are event-driven. Activation of each state depends on predefined action / event. The engine executes the activities needed and stops after completion of the next state. State Machine Workflows are the solution for complex modeling processes where there is no deterministic execution path between the steps.
Each human activity can be described as a function of a Sequential Workflow. For example – Order processing, Expenses approval or Purchase requests process.
Best example for State Machine Workflow would be an order supply process where an order can have different states: received, approved, and shipped. Most workflows are having states and run for a relatively long time. Workflow which has many unplanned steps to track and where it may not be possible to represent all the possible paths to follow, a State Machine Workflow can be easier and more orderly to program.