Ilovepdf Merged
Ilovepdf Merged
SOFTWARE DEVELOPMENT
CONTEXT [C1]
2
1.1 Software Development Build process
3
Project Management and Build
Process: RUP
Software Process Model: Rational Unified Process
4
Agile Software Process Model
Scrum
5
Proposal/Simplified BUILD process model
[process diagram]
6
Proposal BUILD process model
[local and integrated]
● Local build ● Integration build
○ init: ○ consolidation: source code
■ seed/configuration; integration;
■ dependency management; ○ integrated deployment:
○ implementation: ■ dependency management;
■ source coding; ○ validation:
■ test coding; ■ integrated product testing;
○ pack/local deployment: ■ testing review;
■ compile; ○ publish integrated product.
■ local deploy;
○ validation:
■ run xUnit tests;
■ debug;
○ consolidation
■ team publishing source
code and test suites. 7
Practice:
Eclipse Software Process Model
8
TDD: Test Driven Development
JUnit Framework
● TDD
● JUnit Framework
○ @Test
○ org.junit.Assert:
■ assertEquals();
■ assertNotNull();
■ ...
10
1.2 Tools
● 1.2.1 IDE: Integrated Development Environments
11
Java/Spring/JEE IDEs
“An IDE is no substitute for an Intelligent Developer.”*
13
ANT
14
ANT Project Model
15
ANT Build Process
Workflow control strategies
16
ANT Build Process
17
ANT Common Tasks
18
ANT Misc. useful tasks
19
Practice: ANT Build Process
build.xml
20
Apache Ivy*:
Dependency management tool for ANT
● Ivy ant task: build.xml
<project name="project-name" default="build-app"
xmlns:ivy="antlib:org.apache.ivy.ant">
<target name="build-app" description="Test ivy installation">
<ivy:resolve />
<ivy:retrieve/>
</target>
</project>
2
1.2 Tools
● IDE: Integrated Development Environments
3
Software building process
with MAVEN
● Maven simplified build process workflow:
○ compile;
○ resolve dependencies;
○ test;
○ package;
○ install;
○ deploy.
4
Maven Build Process Model
[Conceptual Model diagram]
5
Maven Build Process
validate validate the project is correct and all necessary information is available.
initialize initialize build state, e.g. set properties or create directories.
generate-sources generate any source code for inclusion in compilation.
process-sources process the source code, for example to filter any values.
generate-resources generate resources for inclusion in the package.
process-resources copy and process the resources into the destination directory, ready for packaging.
process-test-sources process the test source code, for example to filter any values.
generate-test-resources create resources for testing.
process-test-resources copy and process the resources into the test destination directory.
test-compile compile the test source code into the test destination directory
9
Practice 2
● MVN-eclipse integration
○ run builds from eclipse
● MVN-command
○ mvn-installation
○ run builds from command-shell
mvn phase
mvn plugin:goal
10
Maven POM: Project Object Model: pom.xml
11
Maven Project Object Model: pom.xml
12
Maven Profiles and Properties
13
MVN project structure
Default properties
● ${project.basedir}
● Default target folder
○ ${project.build.directory}
● Default target/classes folder
○ ${project.build.outputDirectory}
● Default target/test-classes folder
○ ${project.build.testOutputDirectory}
● Default src/main/java folder
○ ${project.build.sourceDirectory}
● Default src/test/java folder
○ ${project.build.testSourceDirectory}
14
MVN project structure
Convention over configuration
15
Maven Repositories and
Dependency management
16
Maven Repositories and
Dependency management
<repositories>
<repository>
<id>my-repo1</id>
<name>your custom repo</name>
<url>http://remote-repo-url.org</url>
</repository>
<repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit}</version>
<scope>test</scope>
</dependency>
</dependencies>
17
Maven Common Commands
execute task (unit-of-work) as {plugin}:{goal}
● mvn archetype:generate
○ generate project (structure and configuration)
● mvn compile
○ execute compile phase
■ from default build lifecycle
○ mvn compiler:compile [and up]
● mvn package
○ execute phase from default build lifecycle
○ mvn jar:jar [and up]
18
Maven Common Commands (2)
● mvn install
○ execute install phase
■ from default build lifecycle
○ mvn install:install [and up]
● mvn
○ dependency:resolve
○ dependency:analyze
○ dependency:tree
○ dependency:copy-dependencies
19
Practice: MVN
20
Maven managing hierarchical project
structure: project and sub-projects
21
Other build-support management tools
● Gradle
● Apache Buildr
● Jeka
22
Collaborative programming workflow.
Software Development & Teaming
23
Features of Version Control Systems
(or Source Code Management Systems)
24
SVN System
25
SVN Concepts
26
SVN Repositories
27
SVN Client - common commands
28
TortoiseSVN
29
Eclipse
Subclipse
30
GIT System and Approach
31
GiT Distributed Architecture and
Git Process
32
Eclipse Git - eGit
33
Eclipse Git - eGit
34
Git commands
● git init
● git clone username@host:/path/to/repository
------------------------------------------------
● git add <filename>
● git fetch
● git pull
● git commit -m "Commit message"
● git push origin master
------------------------------------------------
● git diff
● git checkout -- <filename>
● git reset --hard origin/master
35
Git Workflow
36
Git GUI Tools
● Git-GUI Console
● SourceTree
● GitHub Desktop
● TortoiseGit
● Git Extensions
37
Refs: Ant Build Tool
38
Refs: Maven Build Tool
39
Refs: SVN and GiT
● SVN
○ http://www.tutorialspoint.com/svn/
○ http://www.ibm.com/developerworks/library/os-ecl-su
bversion/
● GiT
○ http://www.vogella.com/tutorials/Git/article.html
○ http://www.tutorialspoint.com/git/
○ http://www.vogella.com/tutorials/EclipseGit/article.ht
ml#creating-an-eclipse-project
○ Pro Git online version
40
Tutorial Sources
● Tutorial Point
○ http://www.tutorialspoint.com/index.htm
● Java Code Geeks
○ http://www.javacodegeeks.com/2014/04/java-ee7-an
d-maven-project-for-newbies-part-1-a-simple-maven
-project-structure-the-parent-pom.html
○ http://www.javacodegeeks.com/2014/06/java-ee7-an
d-maven-project-for-newbies-part-5-unit-testing-usin
g-arquillian-wildfly-8.html
41
T2. Enterprise Architecture and
Components [C3]
Course_3
Agenda
3
Enterprise Architecture
Concept - TOGAF Model
4
(1) Layered Architecture
● Multi-tier/Layered
Architectures for
Enterprise
5
Logical Layers [PoDDD]
6
Clean Architecture
7
Physical Layers: Tiered Architectures
● Two tier
● Three tier
● N-tier
8
Multi-tier architectural models
3-tier Architecture 4-tier Architecture 5-tier Architecture
Presentation: Presentation: Client:
user interface and user interface displaying UI content, taking over of UI
interactions. events and handing them to (controller)
presentation tier.
Applications: Presentation:
UI events, business logic - handling (generating) UI content to client,
as business services handling client events, mediator to business
services.
Domain: Business logic:
business logic. business services + business domain
Integration: Integration:
access drivers to external accessing external resources (databases,
resources messaging systems, mail systems etc.), and
domain mapping to specific external
resource structural domain.
Data Sources: Infrastructure: Resources:
specific DS, external resources. database servers, messaging servers, mail
databases. servers . 9
(2) Enterprise Components Patterns
10
Enterprise Architectural Patterns
Sources
Representative Patterns
• Application Controller – UI workflow coordination within
presentation services;
• Application Service – inter level/tier component orchestration:
coordination of business services and presentation services;
• Business Object – business logic/business rules management
[Domain Object];
• DataAccessObject – data access management [Repository];
• Business Facade – context delimitation of clients and service
providers [SessionFacade];
• Transfer Object – state (data) transfer between tiers/levels (e.g
between presentation and business logic tiers).
12
PoJEE: Pattern of JEE
[JEE Architectural Model]
13
PoDDD: Domain Driven Design Patterns
14
DDD
Patterns
15
Common Enterprise Patterns review:
Common Enterprise Components Types
● Presentation/Client Tier
○ ApplicationController
● Business Tier
○ ApplicationService
○ BusinessService and/or DomainService
○ BusinessObject
■ Domain Entity, Aggregate, ValueObject
● Integration Tier
○ Data Layer Integration
■ DataAccessObject, Repository
○ Client Layer Integration
■ BusinessFacade
○ DataTransferObject
16
(3) Enterprise Components implementation
with Dependency Injection Mechanism
17
Component Design Principles: SOLID
● DI: Dependency Inversion
○ “Depend upon Abstractions. Do not depend upon
concretions.”
○ “High-level modules should not depend on low-level
modules. Both should depend on abstractions.”
○ “Abstractions should not depend on details. Details
should depend on abstractions.”
18
Component Design Patterns:
Inversion of Control and Dependency Injection
19
Types of IoC
● Dependency Lookup
○ Pulled from (JNDI) Registry
○ Contextualized (to container).
● Dependency Injection
○ Constructor Dependency Injection
○ Setter Dependency Injection
○ (Field Dependency Injection)
20
Types of IoC
21
Design Patterns: Inversion of Control with
Dependency Injection
22
Enterprise Platforms
For Enterprise Components
23
(4) Spring Platform
For Enterprise Components with DI
● Spring Core Modules
○ Spring Beans & DI
○ Spring AOP Module
● Spring Data Modules
○ Spring JDBC
○ Spring JPA
● Spring Web Modules
○ Spring MVC
○ Spring REST
Services
● Spring Security Module
● Spring Testing
24
Spring Core: Component Model
Layered Application Component Types
25
Spring.DI Component Model
26
Spring
DI
Types
27
Spring.DI Application Initialization
ApplicationContext Activation
28
Spring Beans Initialization
29
Spring App Study Case
Bean Factory Strategies
Strategy/ Configuration Configuration Study Case: Test Application Class
Spring Context Class Class Bean
Class Invocation Annotation
@Bean TestProjectDomainServiceBeanSDI
(FactoryMethod) AppBeanConfig
30
Spring App Study Case
Components
Enterprise Application TestProjectDomainServiceDefSDI @Test
(Spring App) JUnit4:@RunWith(SpringRunner.
class)
JUnit5:@ExtendWith(SpringExten
sion.class)
32
Java EE 8
33
COURSE REFERENCES
● PoEAA
○ [Evans, 2004] Eric Evans, Domain-Driven Design: tackling complexity in the heart of
software, Addison-Wesley, 2004 [PoDDD]
○ [Fowler et a., 2002] Martin Fowler, David Rice, Matthew Foemmel, Edward Hieatt,
Robert Mee, Randy Stafford, Patterns of Enterprise Application Architecture, Addison
Wesley, 2002 [PoEAA]
● PoJEE
○ [Yener&Theedom, 2015] Murat Yener, Alex Theedom, Professional Java® EE Design
Patterns, John Wiley & Sons, Inc., 2015
○ [Alur et al., 2003] Deepak Alur, John Crupi, Dan Malks, Core J2EE Patterns. Best
Practices and Design Strategies, 2nd Edition, Prentice Hall, 2003 [PoJEE]
● JEE
○ [Goncalves, 2013] Antonio Goncalves, Beginning Java EE 7, Apress Media, LLC,
2013
● Spring
○ [Cosmina et.al.,2017] Iuliana Cosmina, Rob Harrop, Chris Schaefer, Clarence Ho, Pro
Spring 5: An In-Depth Guide to the Spring Framework and Its Tools, Apress, 2017 34
Misc.Refs: Design Patterns
35
Online Refs - Spring 5
● https://howtodoinjava.com/spring-5-tutorial/
● https://www.baeldung.com/bootstraping-a-web-applicati
on-with-spring-and-java-based-configuration
● https://www.logicbig.com/tutorials/spring-framework/spri
ng-core.html
● https://dzone.com/articles/ioc-vs-di
● https://mobiarch.wordpress.com/2013/01/11/spring-di-a
nd-cdi-comparative-study/
● https://dzone.com/articles/cdi-10-vs-spring-31-feature
● http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfO
od
36
Misc.Refs.OnLine
● PoEAA
○ https://martinfowler.com/eaaCatalog/
● DDD
○ https://martinfowler.com/tags/domain%20driven%20design.html
○ https://www.thoughtworks.com/insights/blog/domain-driven-design-services-architecture
○ http://dddcommunity.org/
○ https://dzone.com/refcardz/getting-started-domain-driven
○ https://www.codeproject.com/Articles/339725/Domain-Driven-Design-Clear-Your-Concepts
-Before-Yo
● PoJEE
○ http://www.corej2eepatterns.com/
○ http://www.oracle.com/technetwork/java/patterns-139816.html
○ https://www.oreilly.com/ideas/modern-java-ee-design-patterns
● Business Logic
○ MSFT: https://msdn.microsoft.com/en-us/library/ee658103.aspx
○ https://ramj2ee.blogspot.ro/2013/12/all-design-patterns-links.html
● DIP
○ https://dzone.com/articles/design-patterns-explained-dependency-injection-wit
○ https://martinfowler.com/articles/dipInTheWild.html
○ http://www.labri.fr/perso/clement/enseignements/ao/DIP.pdf
○ https://dzone.com/articles/reevaluating-the-layered-architecture
37
T2. Enterprise Architecture and
Components [C4]
Course_4
Agenda
● 2.2 Business Logic Components: Domain Model and
Business Services
○ Business Logic Design Patterns
■ (1) Domain Model Patterns:
● Entities, value-objects, aggregates
● Factories and repositories
■ (2) Business Logic Patterns:
● Service Design Pattern
● Business Rules Patterns: integrity, computation,
workflow rules.
3
Agenda
○ Business Logic Implementation
■ (3) Domain Model Implementation:
● Domain Entities and Aggregates
● Domain Supporting Services
■ (4) Business Logic Implementation:
● Business Services
○ Computation Services, Validation Services
○ Workflow Services, Logging/Audit Services
● Implementation Strategies
○ Facade Strategy
○ AOP Strategy
○ Event-based Strategy
4
PoEAA: Domain Model
in Domain Logic Patterns
5
PoJEE: Business Object Model
in Business Tier Patterns
6
PoDDD: Layers
7
(1) PoDDD: Domain Model Patterns
● Domain Model Patterns:
○ Entities, value-objects, aggregates
● Domain Entity Support Services
○ Factories and repositories
8
PoDDD: Domain Model
and Domain Services
9
PoDDD: Domain Model Design Patterns:
Entities and Value Objects
● Principle/Scope:
○ isolate business data structures.
● Pattern Elements:
○ Entities are domain objects with identity (lifecycle
constant) and states (lifecycle workflow). Entity
properties could be:
■ value objects;
■ associations with other entities (references to
other entities);
○ Value Objects are domain objects without identity,
without distinct life cycle states (immutable).
10
PoDDD: Entities and Value Objects
Class Structural Diagram
11
PoDDD: Domain Model
Aggregates Design Pattern
13
PoDDD: Factory Design Pattern
14
PoDDD: Entity Factory Design Pattern
● Principle/Scope:
○ provide persistent data container/collection context for
each type of entity/aggregate that needs global access;
○ encapsulate and hide specific persistence logic;
○ provide operations to:
■ manage persistent state of entities (update, delete) or
entity-aggregates;
■ produce entity collections starting from specific
queries and query criteria.
● Pattern Elements
○ Client
○ Repository
○ Database
16
PoDDD: Factory and Repository
Collaboration Structural Diagram
17
(2) Business Logic Patterns:
Services to enable business-logic rules
18
PoEAA: Service Related Patterns
Transaction Script, Service Layer
19
PoJEE: Service related patterns:
Application Service, Session Facade
21
PoDDD: Domain Service Pattern
● Principle/Scope:
○ Services operation/operations transcend Entities or ValueObjects
behaviour.
○ Services interfaces imply elements from domain model.
○ Not preserving any meaningful state related to other domain
model elements (e.g. Entites or ValueObjects references): a
domain-service is stateless.
● Pattern Elements
○ Client
○ Service
○ Other domain elements: entities, VOs, aggregates, factories,
repositories, services.
● Domain Services could be acknowledged as Domain
Logic Services.
22
Business Rules Patterns
Operational Rules
● Computation Rules
○ Entity Field Computation Rules
○ Entity Computation Rules
23
Business Logic Service Types
From Business Rules Types
24
(3) Domain Model Implementation*
● Entity Pattern Implementation
○ JPA Entity Annotation: @Entity, @Table, @Id
○ JPA Field Annotation: @Column, @Transient
○ JPA Inheritance Strategy Annotation: @Inheritance
● Value Object Pattern Implementation
○ Java Enum Type: @Enumerated
○ JPA User Data Type Annotation: @Convert..@Converter
● Aggregate (relationship) Implementation
○ JPA Relationship Annotation: @OneToMany(cascade),
@ManyToOne(mappedBy)
● Entity Support Services Implementation
○ Entity Factory (Facade) Service
○ Repository (Facade) Service
[See extensive discussion in next Course about Data Access Components: T2.C5]
25
Study Case
Domain model overview: Entities
26
Study Case: Domain Model (PoEAA)
Entities and Value Objects (PoDDD)
Project Aggregate (PoDDD)
27
Study Case: Domain Model (PoEAA)
Entities and Value Objects (PoDDD)
Team Aggregate (PoDDD)
28
Study Case: for Domain Model (PoEAA)
Entities and Value Objects (PoDDD)
Sprint Aggregate (PoDDD)
29
Study Case: Domain Aggregates
Project Aggregate Aggregate package
org.scrum.domain.project
Aggregate Root
Project
Aggregate Components
Feature, Release
Sprint Aggregate Aggregate package
org.scrum.domain.sprint
Aggregate Root
Sprint
Aggregate Components
Task, TaskCategory, TaskStatus
Team Aggregate Aggregate package
org.scrum.domain.team
Aggregate Root
Team
Aggregate Components
Member, ProjectManager
30
(4) Business Logic Implementation
Business Service Types
31
Business Services and Integration
Implementation Strategies
● Simple (Business) Facade Implementation Strategy.
32
Implementation Platform: Spring 5
● Spring Core Modules
○ Spring Beans & DI
○ Spring AOP
Module
● Spring Data Modules
○ Spring JDBC
○ Spring JPA
● Spring Web Modules
○ Spring MVC
○ Spring REST
Services
● Spring Security Module
33
Spring Framework Support Features
for Business Logic Implementation
34
Spring Dependency Injection
Facade Strategy
● Spring Facade
○ Spring Service Component (review)
■ Service Interface Declaration
■ Service Bean Class Implementation
35
Spring Aspect Oriented Programming
AOP Concepts
36
Spring Aspect Oriented Programming
Architecture
39
JEE JavaBean Validation Rules
Implementation
● “Existentials”
○ @NotNull, @NotEmpty
● Numeric constraints:
@Max, @Min, @Digits, @Range
● String processing constraints:
○ @Pattern, @Size, @Email, @URL, @Length
● Date/Time Constraints
○ @Future, @Past
● Boolean Constraints
○ @AssertTrue, @AssertFalse
● Collection processing constraints
○ @Size, @NotEmpty
41
JEE JavaBean Validation
Constraint Violation Handling
42
Spring Validation Services Support
Implementation Strategies
● S1: Use org.springframework.validation.Validator
interface:
○ by overriding validate(Object target, Errors errors)
method;
○ and by enabling validation process through
org.springframework.validation.ValidationUtils ::
invokeValidator() method.
43
Study Cases: Business Services
Business Service Type Service Implementation Implementation
Strategy
Entity Factory Service ProjectEntityFactoryBase Simple Facade Strategy
44
Study Case:
Entity Support Services
45
Study Case:
Computation Services
46
Study Case:
Business Workflow Service
47
Study Case:
Entity Audit Service
● Project Audit
○ Service: AuditingPlanningProjectBusinessWorkflowServiceImpl
implements IAuditingPlanningProjectBusinessWorkflowService
■ Business Logic: Auditing
IPlanningProjectBusinessWorkflowService
○ Strategy: Spring.AOP
○ Context: Test_AuditingApplicationService
■ test1_AuditWorkflowService()
■ test2_AuditWorkflowService()
■ test3_AuditWorkflowService()
48
Study Case:
Validation Rules + Validation Service
49
COURSE REFERENCES
● Design Patterns
○ [Evans, 2004] Eric Evans, Domain-Driven Design: tackling complexity in the heart of
software, Addison-Wesley, 2004 [PoDDD]
○ [Fowler et a., 2002] Martin Fowler, David Rice, Matthew Foemmel, Edward Hieatt,
Robert Mee, Randy Stafford, Patterns of Enterprise Application Architecture, Addison
Wesley, 2002 [PoEAA]
○ [Yener&Theedom, 2015] Murat Yener, Alex Theedom, Professional Java® EE Design
Patterns, John Wiley & Sons, Inc., 2015
○ [Alur et al., 2003] Deepak Alur, John Crupi, Dan Malks, Core J2EE Patterns. Best
Practices and Design Strategies, 2nd Edition, Prentice Hall, 2003 [PoJEE]
● JEE
○ [Goncalves, 2013] Antonio Goncalves, Beginning Java EE 7, Apress Media, LLC,
2013
● Spring
○ [Cosmina et.al.,2017] Iuliana Cosmina, Rob Harrop, Chris Schaefer, Clarence Ho, Pro
Spring 5: An In-Depth Guide to the Spring Framework and Its Tools, Apress, 2017
50
Misc.Refs: OnLine
● PoEAA
○ https://martinfowler.com/eaaCatalog/
● DDD
○ https://martinfowler.com/tags/domain%20driven%20design.html
○ https://www.thoughtworks.com/insights/blog/domain-driven-design-services-architectur
e
○ http://dddcommunity.org/
○ https://dzone.com/refcardz/getting-started-domain-driven
○ https://www.codeproject.com/Articles/339725/Domain-Driven-Design-Clear-Your-Conc
epts-Before-Yo
● PoJEE
○ http://www.corej2eepatterns.com/
○ http://www.oracle.com/technetwork/java/patterns-139816.html
○ https://www.oreilly.com/ideas/modern-java-ee-design-patterns
● Business Logic
○ MSFT: https://msdn.microsoft.com/en-us/library/ee658103.aspx
○ https://ramj2ee.blogspot.ro/2013/12/all-design-patterns-links.html
● DIP
○ https://dzone.com/articles/design-patterns-explained-dependency-injection-wit
○ https://martinfowler.com/articles/dipInTheWild.html
○ http://www.labri.fr/perso/clement/enseignements/ao/DIP.pdf
51
Refs.Spring 5
● https://howtodoinjava.com/spring-5-tutorial/
● https://www.baeldung.com/bootstraping-a-web-applicati
on-with-spring-and-java-based-configuration
● https://www.logicbig.com/tutorials/spring-framework/spri
ng-core.html
● https://dzone.com/articles/ioc-vs-di
● https://mobiarch.wordpress.com/2013/01/11/spring-di-a
nd-cdi-comparative-study/
● https://dzone.com/articles/cdi-10-vs-spring-31-feature
52
Refs.JEE
● https://dzone.com/articles/weld-junit-easy-testing-of-cdi-beans
● https://github.com/weld/weld-junit/blob/master/junit5/README.
md
● http://mjremijan.blogspot.com/2018/01/bootstrap-cdi-20-in-java
-se.html
● https://www.javacodegeeks.com/2018/01/bootstrap-cdi-2-0-jav
a-se.html
● https://aboullaite.me/cdi-20-java-se/
● https://www.baeldung.com/java-ee-cdi
● https://dzone.com/articles/an-overview-of-cdi-events
53
T2. Enterprise Architecture and
Components [C5]
Course_5
Agenda
3
Clean Architecture
4
(1) Domain Model Patterns
● Domai Model Patterns:
○ Entities, value-objects, aggregates.
● Entity Support Services
○ Factories and repositories.
5
PoDDD: Domain Model (review)
Entities and Value Objects
● Principle/Scope:
○ isolate business data structures;
● Pattern Elements
○ Entities are domain objects with identity (lifecycle
constant) and states (lifecycle workflow). Entity
properties could be:
■ associations with other entities (references to
other entities);
■ value objects;
○ Value Objects are domain objects without identity,
without distinct life cycle states (immutable).
6
PoDDD: Domain Model (review)
Aggregates
● Principle/Scope:
○ encapsulate all access and mapping logic to data
source;
○ manage data source (database) connection;
○ implement access mechanism (protocol) required by
data source.
● Pattern Elements:
○ business object;
○ data access object;
○ data source;
○ value object.
9
PoJEE: Data Access Object
Class Structural Diagram
10
PoEAA: Data Access Object
Sequence Behavioral Diagram
11
PoDDD: Entity Factory (review)
● Principle/Scope:
○ Provide data container/collection context for each type of
entity/aggregate that needs global access;
○ Encapsulate and hide specific persistence logic;
○ Provide operations:
■ To manage persistent state of entities (update, delete)
or entity-aggregates;
■ To produce entity collections starting from query and
query criteria.
● Pattern Elements
○ Client
○ Repository
○ Database
13
PoDDD: Factory and Repository
Collaboration Structural Diagram
14
(3) Persistent Domain Entities
Implementation with JPA Support
15
Java Persistence API Standard
16
JEE.Java Persistence API: JPA.ORM
Object Relational Mapping
17
JPA.ORM Rules
To Map Object Data Structures
19
JPA.ORM Rules
To Map 1 – 1 associations
● Unidirectional case:
○ Source class owning the association attribute will be annotated
with the following directives:
■ @OneToOne
■ @JoinColumn(name = “FK column name”)
● Bidirectional case:
○ Destination class owning the corresponding association attribute
will have the following directives:
■ @OneToOne
● (mappedBy = “association attribute name from
associated entity class”)
● SQL.Relational result: foreign key column into source table.
20
JPA.ORM Rules
To Map M – M associations
21
JPA.ORM Rules
To Map M – M associations
22
JPA.ORM Rules
To Map M – M associations(cont.)
23
JPA.ORM Rules
To Map 1→ M unidirectional associations
24
JPA.ORM Rules
To Map 1→ M aggregate associations
@OneToMany(
mappedBy="<componentAssociationName>",
cascade = CascadeType.ALL,
fetch = EAGER,
orphanRemoval = true)
private List<ComponentType> components;
25
JPA.ORM Mapping strategies for Inheritance
Hierarchies of Generalization/Specialization
26
JPA-ORM rules for inheritance hierarchies:
SINGLE_TABLE Strategy
27
JPA-ORM rules for inheritance hierarchies:
JOIN Strategy
32
JEE.JPA Support Infrastructure for
Entity Repository with SQL Databases
● EntityManager component
● Query objects
● Transaction objects
33
JEE.JPA Session Management:
EntityManager function: populating entity-cache
34
JEE.JPA Session Management:
EntityManager function: populating entity-cache
35
JEE.JPA Session Management:
EntityManager function: cleaning entity-cache
36
JEE.JPA transaction management
@OneToMany(
mappedBy="<componentAssociationName>",
cascade = CascadeType.ALL,
fetch = EAGER,
orphanRemoval = true)
private List<ComponentType> components;
38
JEE.JPA EntityRepository Support for Queries:
JPA Query Workflow
query.setParameter(“paramName”, paramValue);
39
JEE.JPA Java Persistence Query Language
JPQL
SELECT <select_expression>
FROM <from_clause> [JOIN <join_clase>]
[WHERE <conditional_expression>]
[ORDER BY <order_by_clause>]
[GROUP BY <group_by_clause>]
40
JEE.JPA: JPQL Query Result Type handling
41
JEE.JPA: JPQL Query Result Type handling
42
JEE.JPA: JPQL Query Result Type handling
String sql =
"SELECT c.codcl, c.dencl FROM Client c WHERE c.codcl =101";
43
JEE.JPA: JPQL Joins and Navigations
44
JEE.JPA: JPQL Filters
○ Sub-query:
SELECT DISTINCT p FROM Project p JOIN p.releases r
WHERE EXISTS (SELECT f FROM Feature f WHERE
f.release = r)
45
JEE.JPA: JPQL Parameterized Filters
String jpql =
"SELECT p.projectNo, p.name FROM Project p WHERE p.projectNo
= :p_cod";
List<Object[]> objects =
em.createQuery(jpql).setParameter("p_cod", 101)
.getResultList();
46
JEE.JPA: JPQL Aggregations and Groups
47
JEE.JPA EntityListeners
Business Rules and Entity Repositories
48
Spring 5 Platform
Spring Support for Data Access
49
Spring Data JPA configuration
1st Strategy: Java Bean Class Configuration
● (Prerequisite) Configuration Class will be annotated with:
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "org.scrum.services.sdi")
● Configuration Class will use some strategy (like to enable
@Bean producer methods) for:
○ DataSource Bean Configuration;
○ LocalEntityManagerFactoryBean Configuration with:
■ Entity-Components scan Configuration;
■ JpaVendorAdapter setting (JPA Provider);
■ Additional properties settings like:
● hibernate.dialect;
● hibernate.hbm2ddl.auto;
● javax.persistence.validation.mode;
○ PlatformTransactionManager Bean Configuration.
50
Spring Data JPA configuration: 2nd Strategy
Beans.XML Files & Java Bean Configuration
51
Spring Data JPA configuration: 3rd Strategy
Persistence.XML File & Java Bean Cfg.
52
Spring Data JPA configuration: 4th Strategy
Persistence.XML File & Java Bean Cfg.
53
Spring Support for Data Access:
Declarative Transaction Management
54
Spring Support for Data Access:
Declarative Transaction Management
56
Spring Support for Data Access:
Declarative Transaction Management
REQUIRED None T1
(default)
T1 T1
REQUIRES_NEW None T1
T1 T2
T1 T1
T1 T1
57
Spring Support for Data Access:
Declarative Transaction Management
T1 None
T1 Exception
NESTED None T1
T1 Savepoint + T1
58
Data Access Components
Implementation Strategies
59
(S1) Facade Repository with specific
interface and specific implementation
● Repository/DAO Standard Interface: ● Repository/DAO Specific Extension
EntityRepository<T> ○ interface
○ simple CRUD: IProjectEntityRepository
■ T getById(Object id); ■ extends
■ T add(T entity); EntityRepository<Project>
■ Collection<T>
● Repository/DAO Specific
addAll(Collection<T> entities);
■ remove(T entity); Implementation:
■ removeAll(Collection<T> entities); ProjectEntityRepositoryJPA
■ T refresh(T entity); ○ implements
○ simple QBExample: IProjectEntityRepository
■ Collection<T> get(T
entitySample);
■ Collection<T> toCollection();
■ T[] toArray();
■ int size();
60
(S2) Facade Repository with
Generic interface and implementation
● EntityRepository
interface
● EntityRepositoryBase
generic implementation
61
Study Case: Facade Repository
with Generic Repository Interface
● JUnit test class
○ TestProjectEntityRepositoryBase
■ Specialized from
ProjectEntityRepositoryBase
○ TestEntityRepositoryBase
■ Generic from EntityRepositoryBase
62
Study Case: EntityRepositoryBase class
● Repository Methods:
○ Repository/DAO Interface (pattern version);
● JPA Persistence Logic encapsulation
○ EntityManager management
■ Dependency Injection of JTA Source for @PersistenceContext;
○ EntityManager methods invocation;
■ entity type genericity;
■ query by example approach;
■ CRUD operation implementation;
○ declarative transaction management;
● Aggregate management with dedicated EntityRepository
○ transaction propagation to aggregate components by using
@OneToMany(cascade) annotation
63
(S3) Facade strategy with
Spring Data JPA Entity Repositories
● Spring Data modules extends JPA:
○ providing support to create simple JPA Repositories:
■ as simple as extending specific Spring (provided)
repository interfaces;
■ by injection of repository reference into Spring/JEE
business components/services.
● Spring Data JPA repository interfaces:
■ package org.springframework.data.jpa.repository →
● CrudRepository<E, K>
● JpaRepository<E, K>
64
Spring Support for Data Access:
JPA Extensions
● Repository abstraction for persistence operations
[org.springframework.data.jpa.repository]:
○ CrudRepository interface:
■ save(S);
■ delete(S);
■ findOne(ID);
■ findAll();
■ exists(ID);
■ count();
○ JpaRepository interface
■ extending CrudRepository:
● saveAndFlush(); flush();
● deleteInBatch(Interable<ID>); deleteAllInBatch();
■ extending QueryByExampleExecutor:
● findOne(Example<S>);
● findAll(Example<S>);
● count((Example<S>);
65
Spring Support
for Data Access:
JPA Extensions
66
Study Case: Facade Repository
with Spring Data JPA Interface
● Spring Data JPA configuration :
○ JPA persistence.xml strategy.
● IProjectRepositorySpringData extending
JpaRepository interface with additional (query)
operations:
○ findBy<PropertyName>() format;
○ @Query(<jpql>) finByCriteria(...) format.
67
COURSE REFERENCES
● Design Patterns
○ [Evans, 2004] Eric Evans, Domain-Driven Design: tackling complexity in the heart of
software, Addison-Wesley, 2004 [PoDDD]
○ [Fowler et a., 2002] Martin Fowler, David Rice, Matthew Foemmel, Edward Hieatt,
Robert Mee, Randy Stafford, Patterns of Enterprise Application Architecture, Addison
Wesley, 2002 [PoEAA]
○ [Yener&Theedom, 2015] Murat Yener, Alex Theedom, Professional Java® EE Design
Patterns, John Wiley & Sons, Inc., 2015
○ [Alur et al., 2003] Deepak Alur, John Crupi, Dan Malks, Core J2EE Patterns. Best
Practices and Design Strategies, 2nd Edition, Prentice Hall, 2003 [PoJEE]
● Spring and JEE
○ [Cosmina et.al.,2017] Iuliana Cosmina, Rob Harrop, Chris Schaefer, Clarence Ho, Pro
Spring 5: An In-Depth Guide to the Spring Framework and Its Tools, Apress, 2017
○ [Goncalves, 2013] Antonio Goncalves, Beginning Java EE 7, Apress Media, LLC,
2013
68
Resources: JPA Online
69
Resources: DDD, JEE, EAA Online
● PoEAA
○ https://martinfowler.com/eaaCatalog/
● DDD
○ https://martinfowler.com/tags/domain%20driven%20design.html
○ https://www.thoughtworks.com/insights/blog/domain-driven-design-services-architectur
e
○ http://dddcommunity.org/
○ https://dzone.com/refcardz/getting-started-domain-driven
○ https://www.codeproject.com/Articles/339725/Domain-Driven-Design-Clear-Your-Conc
epts-Before-Yo
● PoJEE
○ http://www.corej2eepatterns.com/
○ http://www.oracle.com/technetwork/java/patterns-139816.html
○ https://www.oreilly.com/ideas/modern-java-ee-design-patterns
● Business Logic
○ MSFT: https://msdn.microsoft.com/en-us/library/ee658103.aspx
○ https://ramj2ee.blogspot.ro/2013/12/all-design-patterns-links.html
● DIP
○ https://dzone.com/articles/design-patterns-explained-dependency-injection-wit
○ https://martinfowler.com/articles/dipInTheWild.html
○ http://www.labri.fr/perso/clement/enseignements/ao/DIP.pdf
70
T2. Enterprise Architecture and
Components [C6]
Course_6
Agenda
3
DDD Layers and Services
4
Business Services Flavours
● Domain Services
● Application Services
● Orchestration Services
● Composite Services
5
PoJEE: Session Facade [Review]
● Principle/Scope:
○ client access control (restrict dependencies) to
business objects from business domain.
● Pattern Elements:
○ Session Facade;
○ Business Component:
■ business object;
■ data access object;
■ application service.
6
PoJEE: Session Facade
Class Structural Diagram
7
PoJEE: Application Service
● Principles/Scope:
○ centralized coordination of business logic: component/tier
integration, persistence services, transaction
management etc.;
○ complementary to business facade: BF decouples
presentation components from business components.
● Pattern Elements:
○ Client (e.g. presentation client);
○ Application Services;
○ Business Objects, services, data access objects etc.
8
PoJEE: Application Service
Class Structural Diagram
9
PoJEE: Application Service
Sequence Behavioral Diagram
10
Facade Application Services
Implementation Strategies
11
DTO Data Transfer/Transport Object
● Principle/Scope:
○ data transfer between architectural layers;
○ layer context delimitation: remove internal data
dependencies between layers;
○ data transfer optimization within distributed
environments.
● Pattern Elements:
○ x-Tier Internal Components;
○ Data Transport Objects.
13
PoJEE: Data Transfer Object
Class Structural Diagram
14
PoJEE: Data Transfer Object
Sequence Behavioral Diagram
15
Domain Model-based DTOs
Implementation Strategies
● Structural Strategies:
○ (i) Generate DTOs from entity structures: use Entity
Types to define also the DTO Types;
○ (ii) Generate DTOs from additional structures, like
EntityViews: use EntityView Types as a distinct typing
system to define DTO structures.
● Factory Strategies
○ Method Factory - implemented within Entity classes;
○ Class Factory.
16
APPLICATION SERVICES
Enterprise Components Implementation
17
Spring Remote Services
● Spring Services Types:
○ RMI based Services
○ HTTP based Services
○ Web Services: HTTP RESTFul Services
● Spring Service Architectural Components:
○ Facade Interface
○ Service Implementation Component
○ Service Exporter of Business -tier:
■ e.g. RmiServiceExporter
■ e.g. HttpInvokerServiceExporter
○ Service Invoker of Client-tier:
■ e.g. RmiProxyFactoryBean
■ e.g. HttpInvokerProxyFactoryBean
18
Spring Remote Services
Service Implementation Components
● Spring Service Architectural Components:
○ Facade Interface
■ Simple Service Java Interface - no special
dependencies or annotations;
○ Service Implementation Component
■ Service Class implements Facade Interface;
■ Marked as @Service("ServiceName");
■ Marked as @Transactional (optional).
19
Spring Remote Services
[Server-exporter side]
20
Spring Remote Services
[Client-proxy side]
21
Spring RMI Remote Services
Service Exporter
● org.springframework.remoting.rmi.RmiServiceExporter
○ setServiceName(): to complete remote service URL;
○ setServiceInterface(): with Facade Interface Type;
○ setService(): with Service implementation instance.
URL: rmi://localhost:1099/serviceName
22
Spring RMI Remote Services
Client Invoker
● org.springframework.remoting.rmi.RmiProxyFactoryBean
○ setServiceInterface(): with Facade Interface Type;
○ setServiceUrl(): with Service generated URL from Spring
Container hosting Remote Service implementation.
URL: rmi://localhost:1099/serviceName
23
Spring HTTP Remote Services
Service Exporter HTTP
● org.springframework.remoting.httpinvoker.HttpInvokerService
Exporter:
○ setServiceInterface(): with Facade Interface Type;
○ setService(): with Service implementation instance.
URL: http://localhost:8080/spring/invoker/httpInvoker/service
-> Spring MVC App base path: http://localhost:8080/spring
-> HttpInvokerServiceExporter @Bean path: /httpInvoker/service
24
Spring HTTP Remote Services
Spring MVC App Configuration
● Class WebInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer
○ getRootConfigClasses(): AppJPAConfig
○ getServletConfigClasses(): HttpInvokerConfig
○ getServletMappings() : "/invoker/*"
● Class @Configuration AppPersistenceEMFConfig
○ @ComponentScan
○ @EnableJpaRepositories
● Class @Configuration HttpInvokerConfig
○ @Bean for HttpInvokerServiceExporter
25
Spring HTTP Remote Services
Client Invoker HTTP
● org.springframework.remoting.httpinvoker.HttpInvokerProxy
FactoryBean
○ setServiceInterface(): with Facade Interface Type;
○ setServiceUrl(): with Service generated URL from Spring
Container hosting Remote Service implementation.
URL: http://localhost:8080/spring/invoker/httpInvoker/service
26
Practice: SPRING
Spring Data Service Implementation Workflow
27
COURSE REFERENCES
● PoEAA
○ [Evans, 2004] Eric Evans, Domain-Driven Design: tackling complexity in the heart of
software, Addison-Wesley, 2004 [PoDDD]
○ [Fowler et a., 2002] Martin Fowler, David Rice, Matthew Foemmel, Edward Hieatt,
Robert Mee, Randy Stafford, Patterns of Enterprise Application Architecture, Addison
Wesley, 2002 [PoEAA]
● PoJEE
○ [Yener&Theedom, 2015] Murat Yener, Alex Theedom, Professional Java® EE Design
Patterns, John Wiley & Sons, Inc., 2015
○ [Alur et al., 2003] Deepak Alur, John Crupi, Dan Malks, Core J2EE Patterns. Best
Practices and Design Strategies, 2nd Edition, Prentice Hall, 2003 [PoJEE]
● JEE
○ [Goncalves, 2013] Antonio Goncalves, Beginning Java EE 7, Apress Media, LLC,
2013
● Spring
○ [Cosmina et.al.,2017] Iuliana Cosmina, Rob Harrop, Chris Schaefer, Clarence Ho, Pro
Spring 5: An In-Depth Guide to the Spring Framework and Its Tools, Apress, 2017 28
Misc.Refs: OnLine
● PoEAA
○ https://martinfowler.com/eaaCatalog/
● DDD
○ https://martinfowler.com/tags/domain%20driven%20design.html
○ https://www.thoughtworks.com/insights/blog/domain-driven-design-services-architecture
○ http://dddcommunity.org/
○ https://dzone.com/refcardz/getting-started-domain-driven
○ https://www.codeproject.com/Articles/339725/Domain-Driven-Design-Clear-Your-Concepts
-Before-Yo
● PoJEE
○ http://www.corej2eepatterns.com/
○ http://www.oracle.com/technetwork/java/patterns-139816.html
○ https://www.oreilly.com/ideas/modern-java-ee-design-patterns
● Business Logic
○ MSFT: https://msdn.microsoft.com/en-us/library/ee658103.aspx
○ https://ramj2ee.blogspot.ro/2013/12/all-design-patterns-links.html
● DIP
○ https://dzone.com/articles/design-patterns-explained-dependency-injection-wit
○ https://martinfowler.com/articles/dipInTheWild.html
○ http://www.labri.fr/perso/clement/enseignements/ao/DIP.pdf
29
Refs: Design Patterns
30
References: Spring Data JPA and Spring
Remote Services
● Install Tomcat 9
○ Step-by-step Guide
■ Eclipse > tomcat-users.xml:
● Roles > manager-scripts, manager-gui
○ Debug Startup 404
■ Server Location: Use Tomcat Installation
● Maven Tomcat Plugin
○ https://www.dev2qa.com/how-to-deploy-a-maven-pr
oject-to-tomcat-from-eclipse/
■ use tomcat7-maven-plugin v2.2
● configuration (deployment) URL
○ http://localhost:8080/manager/text
T3. SOA&WS
Service Oriented Architectures &
Web Services [C7]
Course_7
Agenda Chapter 3
4
Service Oriented Computing elements
5
SOA Design principles
1) Service contracts
2) Service loose coupling
3) Service abstraction
4) Service reusability
5) Service autonomy
6) Service statelessness
7) Service discoverability
8) Service composability
6
SOA Design principles
7
Service Contracts
Standardization and Design
● Service contracts will establish:
○ Terms of engagement.
○ Technical constraints and requirements.
● Service contract consists in:
○ Service descriptions: technical and non-technical
● Services share standardized contracts
○ “Services within the same service inventory are in
compliance with the same contract design standards.”*
● Goals:
○ Achieve a meaningful level of interoperability.
○ Service capability to be intuitively understood.
*Reference: Erl, Thomas, SOA: principles of service design, PRENTICE HALL, 2008
8
Service Loose Coupling
Intra-Service and Consumer Dependencies
9
Service Abstraction
Information Hiding and Meta Abstraction Types
10
Service Reusability
Commercial and Agnostic Design
11
Service Autonomy
Processing boundaries and control
12
Service Statelessness
Stateless Design
13
Service Discoverability
Interpretability and Communication
15
Common Service Types
within Service Oriented Architectures
16
Service Types
17
Study-Case: Business Services Collaboration
[Project: msd.t2_c7.spring_soa_services]
● Collaboration Design:
○ PlanningProjectBusinessWorkflowService [Composed Service]
○ ConsolidatingProjectCurrentReleaseViewDomainService [Task
Service]
○ AuditingPlanningProjectBusinessWorkflowService [Task
Service]
○ ProjectEntityRepository [Entity Service]
○ ProjectEntityFactory [Entity Service]
○ IAuditingPlanningProjectBusinessWorkflowService[Utility Service]
● Practical Implementation Strategies:
○ Case_1: Local Facade Collaboration
○ Case_2: Remote-HTTP Facade Collaboration (as HTTP
Spring Services)
18
Common Service Styles
● Architectural Styles:
○ RPC API: Remote Processing Call.
○ Resource API: Resource Management.
○ Messaging API: Asynchronous Communication.
● Implementation Styles:
○ HTTP|RMI Remote communication (Spring Services Style)
○ HTTP messages (REST* - style).
○ Simple Object Access Protocol (SOAP) messages.
○ Java Messaging Services (JMS) messages.
○ Simple Mail Transfer Protocol (SMTP) messages.
19
Web Services Styles
● SOAP: Simple Object Access Protocol
● REST: Representational State Transfer
20
3.2 REST Web Services as HTTP APIs
21
REST Web Services as HTTP APIs
23
Architectural Principles of
REST Web Services
● Connectedness:
○ resources dependencies (functional or data-composition
dependencies) should be described as a linking graph with
HTTP-URIs;
○ public accessible representations should cover all links to
other related resources: the graph-localization API.
● Uniform Interface:
○ Resources and services has to managed in the same way by
an uniform interface: using the HTTP protocol elements.
● Statelessness:
○ The server should not manage client-side sessions: resource
states reside on server and they will be shared by clients so
that the application-session states remain on the client
responsibility.
24
REST Principles vs. SOA Principles
SOA Principles REST Principles
26
DTO Data Transfer/Transport Object
Design Pattern for REST Architecture
27
PoJEE: Data Transport Object
Class Structural Diagram
28
Domain Model-based DTO
Implementation Strategies
● Structural Strategies:
○ Generate DTOs from entity structures - use Entity Types
to define DTO Types.
○ Generate DTOs using dedicated EntityView/EntityDTO
structures - Use EntityView/EntityDTO Types as a distinct
typing system to define DTO structures.
● Factory Strategies
○ Method Factory - DTO producing methods implemented
statically within Entity classes;
○ Class Factory (alongside Entity Factories) to host DTO
producing methods.
● Document Builders
○ Convert DTO instances into XML/JSON formats using
JAXB/JSON libraries.
29
REST Resources and Web Clients
REST Web Service
REST Resource
DELETE
GET JSON/XML
Data Entities
DELETE
GET JSON/XML RestURL
Data Entities REST Resource
PUT POST
PUT
POST
DELETE
GET JSON/XML
Data Entities
URL Requests
PUT
POST
REST Resources as
JSON/XML documents 30
REST Web Backend
REST Web Service
java-method java-method
REST Resource
RS mapping
RESTService-Class
DELETE
GET JSON/XML
Data Entities
java-method java-method
RestURL
REST Resource
PUT POST
DELETE
RestURL JSON/XML JPA Entity
GET
Data Entities
REST Resource
PUT
POST
JPA Entity
DELETE
GET JSON/XML
Data Entities
31
Refs: SOA Resources
32
COURSE REFERENCES
● Design Patterns
○ [Evans, 2004] Eric Evans, Domain-Driven Design: tackling complexity in the heart of
software, Addison-Wesley, 2004 [PoDDD]
○ [Fowler et a., 2002] Martin Fowler, David Rice, Matthew Foemmel, Edward Hieatt,
Robert Mee, Randy Stafford, Patterns of Enterprise Application Architecture, Addison
Wesley, 2002 [PoEAA]
○ [Yener&Theedom, 2015] Murat Yener, Alex Theedom, Professional Java® EE Design
Patterns, John Wiley & Sons, Inc., 2015
○ [Alur et al., 2003] Deepak Alur, John Crupi, Dan Malks, Core J2EE Patterns. Best
Practices and Design Strategies, 2nd Edition, Prentice Hall, 2003 [PoJEE]
● Spring and JEE
○ [Cosmina et.al.,2017] Iuliana Cosmina, Rob Harrop, Chris Schaefer, Clarence Ho, Pro
Spring 5: An In-Depth Guide to the Spring Framework and Its Tools, Apress, 2017
○ [Goncalves, 2013] Antonio Goncalves, Beginning Java EE 7, Apress Media, LLC,
2013
33
Misc:
● Architectures
○ REST Oriented Computing
○ REST Oriented Architecture
● RESTful API Description Languages
○ OpenAPI Specification (formerly Swagger) – specification
for defining interfaces
○ OData – Protocol to define REST APIs
○ RAML - RESTful API Modeling Language
○ RSDL (RESTful Service Description Language)
● RESTful Query Languages
○ RSQL (link1)
○ Spring Query DSL (link2, link3)
○ GraphQL
○ RESTSQL
34
Misc
35
T3. SOA&WS
Service Oriented Architectures &
Web Services [C8]
Course_8
Agenda
3
(1) HTTP protocol
● HTTP [HyperText Transport Protocol]:
○ represents a transport protocol for web-based hypermedia
information systems;
○ became the foundation of data transport/communication for the
Web: data-views as web-resources identified by URLs.
● HTTP as an application protocol:
○ HTTP action types (request methods):
■ GET, POST, PUT, (PATCH), DELETE
● to manipulate accessed web-resources;
■ HEAD
● to communicate metadata with headers;
● not having body messages included;
■ OPTIONS
● to negotiate communication parameters/formats.
4
HTTP protocol as an application protocol
● HTTP (text) messages:
○ request messages (lines):
■ request line + headers + (empty line) + body;
○ response messages (lines):
■ status-line + headers + (empty line) + body
● HTTP (communication) status codes:
○ normal status (examples):
■ 200 : OK;
■ 204 : OK with no-content;
○ error status codes (examples):
■ 400: Bad Request;
■ 401: Unauthorized;
■ 402: Forbidden;
■ 404: Not Found;
■ 408: Request Timeout;
■ ... 5
HTTP protocol as an application protocol
8
Java/Jakarta EE Web and REST
Frameworks
● Data Components
○ Entities Classes
○ Entity Repositories
● Service Components
○ Business Services
○ REST Controllers
● Configuration Components
○ WebInitializer
(AbstractAnnotationConfigDispatcherServletInitializer)
○ WebConfig (WebMvcConfigurer) with XML Mapping Configuration
○ ApplicationConfiguration
● Spring Deployment Components: maven-plugins for
○ Apache Tomcat Web Server
Spring MVC RESTful Architecture
URL Mappings - Path annotations
● http://localhost:8080/<spring-mvc-app-name>/<spring-
servlet-mapping>/<spring-rest-controller-mapping>
http://localhost:8080/scrum/data/projects
○ <spring-mvc-app-name> from pom.xml file,
<tomcat7-maven-plugin> configuration <path> parameter;
○ <spring-servlet-mapping> from WebInitializer class
(extending AbstractAnnotationConfigDispatcher
ServletInitializer), returned by getServletMappings()
configuration method;
○ <spring-rest-controller-mapping> from spring-service-class
marked with @RestController and declared by
@RequestMapping annotation (with value parameter).
Spring MVC RESTful Architecture
HTTP Action Mappings
● REST Service implementation class will be annotated as:
○ @RestController @RequestMapping("/path")
● Methods from REST Service implementation class will be
annotated as:
○ GET Action Mapping
■ @RequestMapping(method = RequestMethod.GET)
■ @ResponseBody
○ POST Action Mapping
■ @RequestMapping(method = RequestMethod.POST)
■ @RequestBody and @ResponseBody
○ PUT Action Mapping
■ @RequestMapping(method = RequestMethod.PUT)
■ @RequestBody and @ResponseBody
○ DELETE Action Mapping
■ @RequestMapping(method = RequestMethod.DELETE)
■ @ResponseBody
Spring MVC RESTful Architecture
HTTP Action Mappings
17
JAXB Annotation API
javax.xml.bind.annotation
● @XmlRootElement
■ @XmlAccessorType(FIELD|PROPERTY|NONE)
■ @XmlType(propOrder={mapped-fld-list})
○ @XmlAttribute
■ (name = “attribute-explicit-name”)
○ @XmlElement
■ (name = “element-tag-name”)
○ @XmlElements ({@XmlElement
■ (name=”element-tag-name”
■ type=EntityType.class)});
○ @XmlElementWrapper(name = "wrapper-tag-name")
■ @XmlElement(name = "element-tag-name")
○ @XmlTransient
■ to skip fields/attribute from mapping processing;
18
JAXB Mapping process:
CLASS and MEMBERS
From Java beans to XML document: mapping steps
19
JAXB Mapping process: RELATIONS
From Java class to XML document: mapping relations
● Inheritance:
○ inherited fields or properties will be included in xml
document structure of subclass marked with
@XmlRootElement.
● Reference relationships (entity associations):
○ as simple associations (ManyToOne, OneToOne):
■ referenced entity marked with @XmlRootElement
will be included in the xml-document generated
from main entity/class;
○ as collection-based associations (OneToMany,
ManyToMany)... (see next page)
20
JAXB Mapping process: RELATIONS
From Java class to XML document: mapping relations
26
Spring MVC RESTful Architecture
XML and JSON Provider Configuration
● Spring automatically register the Jackson/Jackson2 providers.
● To use the same JAXB Mapping rules applied in JAX-RS case
(based on @Xml annotations), WebConfig class (extending
WebMvcConfigurer) has to provide some supplementary settings:
@ComponentScan("org.scrum.services.rest")
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer{
// Default Web MVC enabling and detection of Jackson and JAXB2
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
final MappingJackson2XmlHttpMessageConverter conv =
new MappingJackson2XmlHttpMessageConverter();
conv.setObjectMapper(createXmlMapper());
converters.add(conv);
converters.add(new MappingJackson2HttpMessageConverter());
}
private XmlMapper createXmlMapper() {
final XmlMapper mapper = new XmlMapper();
mapper.registerModule(new JaxbAnnotationModule());
return mapper;
}
}
REST Ready Repositories
● URL: http://localhost:8080/SCRUM/data/projects/1002
pom.xml
Controller class
Controller class
WebInitializer class
S2. Define the Web API: RESTful App
protocol: URLs and HTTP actions map
45
Refs: SOA Resources
46
References: JAXB
Tutorials
● JAXB - Tutorial
● Introduction to JAXB
● JAXB Annotations Tutorial
● Using JAXB
● Others:
○ http://www.vogella.com/tutorials/REST/article.html
○ http://howtodoinjava.com/resteasy/jax-rs-2-0-resteas
y-3-0-2-final-client-api-example/
● RESTful Web services: The basics
● Understanding RPC Vs REST For HTTP APIs
● Jersey.Moxy Rest Flavour
47
References: Spring RESTful services
Documentation
● https://www.baeldung.com/rest-with-spring-series
○ https://www.baeldung.com/building-a-restful-web-service-with
-spring-and-java-based-configuration
● https://dzone.com/articles/building-rest-api-jaxb-spring
● http://appsdeveloperblog.com/return-xml-json-spring-mvc/
● https://howtodoinjava.com/spring-restful/spring-rest-hello-world-x
ml-example/
● Testing HTTP
○ https://www.baeldung.com/integration-testing-a-rest-api
■ https://www.baeldung.com/jackson-collection-array
■ https://www.baeldung.com/jackson-xml-serialization-and-
deserialization
■ https://www.baeldung.com/httpclient-post-http-request
Reference Jackson XML/JSON Mapping
@Json Annotations
● http://tutorials.jenkov.com/java-json/jackson-annotations.ht
ml
● http://tutorials.jenkov.com/java-json/index.html
● https://www.baeldung.com/jackson-map
● https://www.baeldung.com/jackson-object-mapper-tutorial
● https://springframework.guru/jackson-annotations-json/
● https://www.codesmell.ninja/jackson-supporting-jaxb-annota
tions/
References
Deploy Spring Web App on Tomcat (classical)
● Install Tomcat 9
○ Step-by-step Guide
■ Eclipse > tomcat-users.xml:
● Roles > manager-scripts, manager-gui
○ Debug Startup 404
■ Server Location: Use Tomcat Installation
● Maven Tomcat Plugin
○ https://www.dev2qa.com/how-to-deploy-a-maven-pr
oject-to-tomcat-from-eclipse/
■ use tomcat7-maven-plugin v2.2
● configuration (deployment) URL
○ http://localhost:8080/manager/text
References: Spring RESTful services
Documentation
● Deploying
○ https://www.baeldung.com/bootstraping-a-web-application-with-spri
ng-and-java-based-configuration
● Spring Boot war to Tomcat
○ https://www.baeldung.com/spring-boot-war-tomcat-deploy
● Simple Spring war to Tomcat
○ https://www.baeldung.com/tomcat-deploy-war
○ https://dzone.com/articles/deploying-spring-apps-to-tomcat-without-
webxml
○ https://docs.spring.io/spring-boot/docs/current/reference/html/howto
-traditional-deployment.html
○ http://www.avajava.com/tutorials/lessons/how-do-i-deploy-a-maven-
web-application-to-tomcat.html
Spring Data JPA and Spring REST
● Model
○ @RestResource
○ @RestResourceRepository
● Links
○ https://dzone.com/articles/easy-access-to-data-with-spring-rest-data
○ https://codeboje.de/spring-data-rest-tutorial/
○ https://www.programmersought.com/article/20695123901/
○ http://progressivecoder.com/exposing-repositories-as-rest-resources-usi
ng-spring-boot/
○ https://softwarehut.com/blog/tech/spring-data-rest-quick-easy-rest-jpa
○ https://docs.spring.io/spring-data/rest/docs/current/reference/html/#refer
ence
○ https://spring.io/guides/tutorials/react-and-spring-data-rest/
○ https://auth0.com/blog/spring-data-rest-tutorial-developing-rest-apis-with-
ease/
T3. SOA&WS
Service Oriented Architectures &
Web Services [C9]
Course_9
To update:
DDD Patterns and Implementations
● DDD Patterns:
○ Bounded Context
○ Mapping Bounded Context Strategy
● Delimitate Microservices around Bounded Contexts
● Interoperate Microservices around Mapping Strategies
3
Agenda
4
3.4 Microservice Oriented Architectures
MSA Definitions
● Software apps “deployed independently, scaled
independently, and tested independently and that has a
single responsibility” [J.Thönes]
● Service-components with “greater modularity, loose
coupling, and reduced dependencies all hold promise in
simplifying the integration task” [Galen Gruman, Alan
Morrison]
● MSA describes “a particular way of designing software
applications as suites of independently deployable
services” [Fowler]
● Microservices are “small, autonomous services that
work together. Small, and focused on doing one thing
well” [Sam Newman]
5
Microservices [MSA] vs. Monoliths *
* Galen Gruman, Alan Morrison, Microservices: The resurgence of SOA principles and an alternative to the monolith,
Technology Forecast: Rethinking integration Issue 1, 2014, www.pwc.com/technologyforecast
SOA vs MSA*
● autonomy: “The golden rule: can you make a change to a service and
deploy it by itself without changing anything else?”;
● technology heterogeneity:
● resilience: single-component failure does not break down (tear apart)
the whole system;
● (fine-grained) service scaling: scaling individual service by
node-sharding;
● ease of deployment: deploy each service independently by the rest of
the system;
● organizational alignment: smaller teams to better alignment to a
distributed architecture;
● composability: as SOA attribute for reuse of functionality;
● optimizing for replaceability: “small in size, the cost to replace them
with a better implementation, or even delete them altogether, is much
easier to manage“.
* Sam Newman, Building microservices, O’Reilly Media 2015
Microservice Architecture [MSA]
Platforms
● Spring Framework
○ SpringBoot
● Java EE/Jakarta Enterprise Edition
○ Eclipse Microprofile implementations:
■ Swarm, Thorntail V2 (Wildfly)
■ Quarkus
■ Open Liberty
■ Payara Micro
■ Apache TomEE Microprofile
■ Kumuluz EE
■ Helidon MP
10
3.5 Spring Boot Applications
● Configuration
○ @SpringBootConfiguration annotation subsumes
■ @EnableAutoConfig
■ @Configuration
■ @ComponentScan
● Deployment
○ Use maven to run app from project :
■ spring-boot-maven-plugin
● spring-boot:run
■ tomcat7-maven-plugin
● mvn tomcat7:deploy -P TomcatDeployment
○ Use maven to build and run app with java -jar
■ mvn package
■ java -jar springbootapp-name.jar --server.port=8080
11
Spring Boot Framework
● Spring Boot tries to simplify and to streamline the
Spring specific development process:
○ by eliminating most of the necessary configurations
using the so-called Spring Boot auto-managing
features;
○ by managing more efficiently the dependency
system activated by the different Spring modules to
be invoked.
12
Spring Boot Project Configuration
Dependency Management
● A maven project will be created as a sub-project of
spring-provided spring-boot-starter-parent template project.
● Only the dependencies to the spring-boot-starter modules that
are necessary to cover the Spring App features required by the
app-project will be added, such as:
○ spring-boot-starter
○ spring-boot-starter-data-jpa
○ spring-boot-starter-web
○ spring-boot-starter-test
● Other minimal dependencies will be explicitly added(not
imported from spring-boot-starter-parent template project) such
as:
○ JDBC drivers (ojdbc, postgresql-jdbc).
13
SpringBoot Project Configuration
Parent project reference
14
SpringBoot Project
Configuration
Dependency
Management
15
SpringBoot Project Configuration
Main Configuration Class
16
@SpringBootApplication
● Marking the main application with @SpringBootApplication
annotation means that for the default configuration this could be
the only annotation required. This annotation
covers/includes/subsumes 3 sub-sequent configuration
annotations:
○ @Configuration means that the annotated class will be also the
spring configuration class.
○ @ComponentScan means that from the annotated class package
will start the scanning process for all Spring components.
○ @EnableAutoConfig will automatically try to configure different
architectural components as:
■ EntityManager for @JpaRepositories - this way there is no
need for a configuration class of JPA aspects;
■ Web context for @RestControllers - this way there is no need
for WebConfig and WebInitializer configuration classes.
17
@SpringBootApplication
● However, the SpringBootApplication could contain bean-factory
methods, as the following, necessary to initialize other
complementary components, as the JAXB-jackson mapper for
XML documents:
@Bean
public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {
return (mapperBuilder) ->
mapperBuilder.modulesToInstall(new JaxbAnnotationModule());
}
18
@SpringBootApplication
19
Spring Boot Application configuration file:
resources/application.properties
20
SpringBoot Application configuration file:
resources/application.properties
21
SpringBoot Project Deployment
As MICROSERVICE-standalone-app
● The pom.xml file should contain spring-boot-maven-plugin
specification:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
● A Spring Boot application could be started as an autonomous
application using this maven command:
○ mvn spring-boot:run
● The Eclipse distribution of SpringTools Suite contains a Boot
Dashboard console that:
○ will detect the existing SpringBoot apps;
○ could start the existing SpringBoot apps.
22
SpringTools Suite
Boot Dashboard
23
SpringBoot Project Deployment
As MICROSERVICE-standalone-app
● Maven project: pom.xml with plugins:
○ Compile: maven-compiler-plugin
○ Package
■ jar: maven-jar-plugin
● Shell/Command line Run configurations:
○ [shell command to start service 8080]
java -jar demo-service-0.0.1-SNAPSHOT.jar
○ [shell command to start service 8090]
java -jar demo-service-0.0.1-SNAPSHOT.jar --server.port=8090
● or:
java -jar -Dserver.port=8090 demo-service-0.0.1-SNAPSHOT.jar
24
SpringBoot Project Deployment
As a Spring-Web Tomcat Hosted App
● Into a specific profile of the main maven pom.xml file
○ the spring-boot-starter-tomcat could be registered as a
dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
○ The tomcat7-maven-plugin should also be registered in the
profile build section
<build><finalName>${project.artifactId}</finalName><plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>${tomcat7-maven-plugin.version}</version>
<configuration>...<configuration>
<plugin>
<plugins><build>
25
26
SpringBoot Project Deployment
As a Spring-Web Tomcat Hosted App
27
SpringBoot Project Test
Strategies
● S1. JUnit with Spring Rest Template
○ SpringBoot service and JUnit test will be initialized in
different runtimes.
● S2. JUnit as @SpringBootTest Application
○ SpringBoot service and JUnit test will be initialized in
the same runtime.
● S2. JUnit with Apache HTTP Client
○ SpringBoot service and JUnit test will be initialized in
different runtimes.
28
(S1) SpringBoot Project Test
Using Spring Template in JUnit
● Use a regular JUnit Client App
○ with simple @Test annotations to test-methods.
● JUnit Client architecture
○ org.springframework.web.client.RestTemplate it is used to
exchange() resources to/from client - to/from
server-backend-RESTful service (to send HTTP requests);
○ org.springframework.http.HttpEntity should be used wrap-up the
client message to be exchange via HTTP with
server-backend-RESTful service.
○ org.springframework.http.ResponseEntity<T> should be used to
manage server response to RestTemplate exchanged-http-request
containing DTOs of type T.
○ ParameterizedTypeReference<T> mechanism should be used to
generically parametrize the ResponseEntity::getBody() method to
extract the DTOs of type T from response (for collections of type T).
29
SpringBoot Project Test
Using Spring Template in JUnit
● RestTemplate initialization
private RestTemplate restTemplate = new RestTemplate();
● RestTemplate :: exchange()
○ parameters
■ String serviceURL,
■ HttpMethod method,
■ HttpEntity requestEntity,
■ Class<T> responseType
○ Returns DTOs packaged within
■ ResponseEntity<T>
30
SpringBoot Project Test
Using Spring Template in JUnit
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestRESTDataServiceSpring{
private static String serviceURL = "http://localhost:8080/app/data/entities";
private RestTemplate restTemplate = new RestTemplate();
@Test
public void test() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", MediaType.APPLICATION_XML_VALUE);
ResponseEntity<RootEntity> responseEntity
= this.restTemplate.exchange(
serviceURL,
HttpMethod.GET,
new HttpEntity<>(headers),
new ParameterizedTypeReference<String>() {}
);
}
... ... }
31
SpringBoot Project Test
Using Spring Template in JUnit
32
SpringBoot Project Test
Using Spring Template in JUnit
33
(S2) SpringBoot Project Test
Using @SpringBootTest as JUnit App
36
Refs for Microservices [MSA]
38
Refs for Spring Boot
● https://howtodoinjava.com/spring-boot-tutorials/
● https://www.tutorialspoint.com/spring_boot/index.htm
● https://www.baeldung.com/spring-boot
● https://howtodoinjava.com/spring-5-tutorial/
● https://spring.io/guides
● https://www.baeldung.com/spring-5
● https://www.baeldung.com/spring-boot-war-tomcat-deploy
39
T3. SOA&WS
Service Oriented Architectures &
Web Services [C10]
Course_11
Agenda
3
3.6 Spring Security for Spring Boot
● Activation:
○ maven dependencies
○ configuration
○ annotations
● Spring Security Framework Overview
● Use Cases: default and customization
○ JUnit test cases
4
Spring 5 Framework
● Spring Core Modules
○ Spring Beans & DI
○ Spring AOP Module
● Spring Data Modules
○ Spring JDBC
○ Spring JPA
● Spring Web Modules
○ Spring MVC
○ Spring REST
Services
● Spring Security
Module
5
SpringBoot Security Activation
with Default Configuration
return authProvider;
}
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.authenticationProvider(authenticationProvider());
}
SpringBoot Security
Customized Authentication Provider
● Postman:
○ Authorization Tab
■ Type: BasicAuth
■ Username/Password form
Strategy_2: SpringBoot Security Test
Apache HTTP Client Test Code
assertThat(statusCode, equalTo(HttpStatus.SC_OK));
Strategy_3: SpringBoot Security Test
SpringBoot Test Code with RestTemplate
@Override
public void configureRepositoryRestConfiguration(
RepositoryRestConfiguration config, CorsRegistry cors) {
// to expose JPA entity ids in REST DTOs
config.exposeIdsFor(
entityManager.getMetamodel().getEntities().stream()
.map(Type::getJavaType)
.toArray(Class[]::new));
}
}
(2) Development Model
● Collection Resource
● Item Resource
● Association Resource
● Search Resource to describe
○ Query Resources
Rest Resource Profiling
URL:
http://localhost:8080/scrum/data/api/projects
Item Resource
URL:
http://localhost:8080/scrum/data/api/projects/1
Association Resources
● SpringBoot security
○ https://www.baeldung.com/spring-boot-security-autoconfiguration
○ https://www.baeldung.com/java-config-spring-security
○ https://www.codejava.net/frameworks/spring-boot/spring-boot-security-auth
entication-with-jpa-hibernate-and-mysql
○ https://www.baeldung.com/spring-security-authentication-with-a-database
● Test
○ https://www.baeldung.com/httpclient-4-basic-authentication
○ https://www.baeldung.com/how-to-use-resttemplate-with-basic-authenticati
on-in-spring
References
Spring Data Rest
● Documentation
○ https://docs.spring.io/spring-data/rest/docs/current/reference/html/#intro-chapter
○ Projections-spring.io
○ https://docs.spring.io/spring-data/rest/docs/current/reference/html/
#reference
● Tutorials
○ https://www.baeldung.com/spring-data-rest-intro
○ https://www.baeldung.com/spring-data-rest-relationships
○ SpringBootTutorials (postman-crud)
● Test
○ https://www.baeldung.com/spring-boot-testing
○ https://www.springboottutorial.com/unit-testing-for-spring-boot-rest-services