Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,7 @@
<module>rate-limiting-pattern</module>
<module>fallback</module>
<module>onion-architecture</module>
<module>service-oriented-architecture</module>
</modules>
<repositories>
<repository>
Expand Down
319 changes: 319 additions & 0 deletions service-oriented-architecture/README.md

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
@startuml
package com.iluwatar.soa {
interface Service {
+ name() : String {abstract}
+ handle(request : ServiceRequest) : ServiceResponse {abstract}
}
class ServiceRequest {
+ ServiceRequest(service : String, operation : String, payload : Map<String, Object>, credential : String)
+ ServiceRequest(service : String, operation : String, payload : Map<String, Object>)
+ service() : String
+ operation() : String
+ payload() : Map<String, Object>
+ credential() : String
+ param(key : String, type : Class<T>) : T
}
class ServiceResponse {
+ ServiceResponse(success : boolean, body : Object, message : String)
+ success() : boolean
+ body() : Object
+ message() : String
+ ok(body : Object) : ServiceResponse {static}
+ error(message : String) : ServiceResponse {static}
}
class ServiceRegistry {
- services : Map<String, Service>
+ ServiceRegistry()
+ register(service : Service) : void
+ lookup(name : String) : Optional<Service>
+ serviceNames() : Set<String>
}
class ServiceBus {
- registry : ServiceRegistry
- policy : AccessPolicy
+ ServiceBus(registry : ServiceRegistry)
+ ServiceBus(registry : ServiceRegistry, policy : AccessPolicy)
+ send(request : ServiceRequest) : ServiceResponse
}
class AccessPolicy {
- validCredentials : Set<String>
- protectedServices : Set<String>
+ AccessPolicy(validCredentials : Set<String>, protectedServices : Set<String>)
+ permitAll() : AccessPolicy {static}
+ allows(request : ServiceRequest) : boolean
}
class Customer {
+ Customer(id : String, name : String, email : String)
+ id() : String
+ name() : String
+ email() : String
}
class CustomerService {
+ NAME : String {static}
- customers : Map<String, Customer>
+ CustomerService()
+ CustomerService(customers : Map<String, Customer>)
+ name() : String
+ handle(request : ServiceRequest) : ServiceResponse
}
class InventoryService {
+ NAME : String {static}
- stock : Map<String, Integer>
+ InventoryService()
+ InventoryService(initialStock : Map<String, Integer>)
+ name() : String
+ handle(request : ServiceRequest) : ServiceResponse
}
class PaymentService {
+ NAME : String {static}
- creditLimit : double
- sequence : AtomicInteger
+ PaymentService()
+ PaymentService(creditLimit : double)
+ name() : String
+ handle(request : ServiceRequest) : ServiceResponse
}
class OrderService {
+ NAME : String {static}
- bus : ServiceBus
- sequence : AtomicInteger
+ OrderService(bus : ServiceBus)
+ name() : String
+ handle(request : ServiceRequest) : ServiceResponse
}
class OrderConfirmation {
+ OrderConfirmation(orderId : String, customerName : String, sku : String, quantity : int, paymentReference : String)
+ orderId() : String
+ customerName() : String
+ sku() : String
+ quantity() : int
+ paymentReference() : String
}
class App {
+ App()
+ main(args : String[]) : void
}
}
CustomerService ..|> Service
InventoryService ..|> Service
PaymentService ..|> Service
OrderService ..|> Service
ServiceBus --> ServiceRegistry
ServiceBus --> AccessPolicy
AccessPolicy ..> ServiceRequest
ServiceRegistry --> "*" Service
OrderService --> ServiceBus
OrderService +-- OrderConfirmation
OrderService ..> OrderConfirmation
CustomerService ..> Customer
ServiceBus ..> ServiceRequest
ServiceBus ..> ServiceResponse
App ..> ServiceBus
App ..> ServiceRegistry
App ..> AccessPolicy
@enduml
70 changes: 70 additions & 0 deletions service-oriented-architecture/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--

This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).

The MIT License
Copyright © 2014-2022 Ilkka Seppälä

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.26.0-SNAPSHOT</version>
</parent>
<artifactId>service-oriented-architecture</artifactId>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Comment on lines +46 to +50

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add junit-jupiter-api as a test dependency since the module's tests rely on the JUnit Jupiter API (org.junit.jupiter.api). Without it, compilation and test execution may fail.

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<configuration>
<archive>
<manifest>
<mainClass>com.iluwatar.soa.App</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.soa;

import java.util.Set;

/**
* Decides whether a request may reach a service.
*
* <p>Security is a cross-cutting concern that the {@link ServiceBus} enforces centrally, so the
* services themselves stay free of security code. The model here is deliberately minimal: a set of
* valid credentials and a set of protected service names. In a real SOA this is where the bus would
* authenticate the caller and authorise the operation against a security token service.
*/
public class AccessPolicy {

private final Set<String> validCredentials;
private final Set<String> protectedServices;

/**
* Creates a policy that protects the given services and accepts the given credentials.
*
* @param validCredentials the credentials that unlock protected services
* @param protectedServices the names of the services that require a valid credential
*/
public AccessPolicy(Set<String> validCredentials, Set<String> protectedServices) {
this.validCredentials = Set.copyOf(validCredentials);
this.protectedServices = Set.copyOf(protectedServices);
}

/** Creates a policy that protects nothing. */
public static AccessPolicy permitAll() {
return new AccessPolicy(Set.of(), Set.of());
}

/**
* Checks whether the request may be dispatched.
*
* @param request the request about to be routed
* @return {@code true} when the target service is not protected or the request carries a valid
* credential
*/
public boolean allows(ServiceRequest request) {
if (!protectedServices.contains(request.service())) {
return true;
}
return request.credential() != null && validCredentials.contains(request.credential());
}
}
111 changes: 111 additions & 0 deletions service-oriented-architecture/src/main/java/com/iluwatar/soa/App.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.soa;

import java.util.Map;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;

/**
* Service-Oriented Architecture (SOA) structures an application as a set of loosely coupled,
* reusable services that communicate through well defined, coarse-grained contracts over a shared
* communication backbone.
*
* <p>The building blocks demonstrated here are:
*
* <ul>
* <li>{@link Service}: the contract every provider implements, expressed with interoperable
* {@link ServiceRequest} and {@link ServiceResponse} messages
* <li>{@link ServiceRegistry}: discovery, so consumers locate services by name at runtime
* <li>{@link ServiceBus}: the backbone that routes messages, applies cross-cutting concerns and
* isolates consumers from provider failures
* <li>{@link AccessPolicy}: security as a cross-cutting concern, enforced by the bus so that the
* services themselves contain no security code
* <li>{@link CustomerService}, {@link InventoryService}, {@link PaymentService}: stateless
* enterprise services that each own one business capability
* <li>{@link OrderService}: a composite service that orchestrates the others through the bus
* </ul>
*
* <p>The demo registers the services behind a bus that protects the payment service, places an
* order with a valid credential that succeeds, an order that fails because of insufficient stock,
* addresses a service that does not exist, and finally places an order anonymously, which the bus
* rejects when the order service tries to charge the customer.
*/
@Slf4j
public class App {

private static final String CHECKOUT_CREDENTIAL = "checkout-service-key";

/**
* Program entry point.
*
* @param args command line arguments, not used
*/
public static void main(String[] args) {
LOGGER.info("Bootstrapping the service registry and the service bus");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In a class annotated with @slf4j, Lombok provides a "log" field, not "LOGGER". This will fail compilation. Replace with log.info(...) (and align all other LOGGER usages in this file to log).

var registry = new ServiceRegistry();
var policy = new AccessPolicy(Set.of(CHECKOUT_CREDENTIAL), Set.of(PaymentService.NAME));
var bus = new ServiceBus(registry, policy);

registry.register(new CustomerService());
registry.register(new InventoryService());
registry.register(new PaymentService());
registry.register(new OrderService(bus));
LOGGER.info("Available services: {}", registry.serviceNames());

LOGGER.info("Placing an order with a valid credential, it should succeed");
var accepted =
bus.send(
new ServiceRequest(
OrderService.NAME,
"placeOrder",
Map.of("customerId", "C-1", "sku", "LAPTOP", "quantity", 2, "amount", 899.0),
CHECKOUT_CREDENTIAL));
LOGGER.info("Order outcome: {}", accepted);

LOGGER.info("Placing an order that should be rejected because of stock");
var rejected =
bus.send(
new ServiceRequest(
OrderService.NAME,
"placeOrder",
Map.of("customerId", "C-2", "sku", "PHONE", "quantity", 50, "amount", 499.0),
CHECKOUT_CREDENTIAL));
LOGGER.info("Order outcome: {}", rejected);

LOGGER.info("Addressing a service that is not registered");
var unknown = bus.send(new ServiceRequest("shipping", "ship", Map.of("orderId", "ORD-1")));
LOGGER.info("Bus outcome: {}", unknown);

LOGGER.info("Placing an order anonymously, the bus should deny access to payment");
var denied =
bus.send(
new ServiceRequest(
OrderService.NAME,
"placeOrder",
Map.of("customerId", "C-1", "sku", "LAPTOP", "quantity", 1, "amount", 899.0)));
LOGGER.info("Order outcome: {}", denied);
}
}
Loading
Loading