Wednesday, May 25, 2022

Http Client: RestTemplate, Java11-HttpClient, Apache-HttpClient, WebClient

 HTTPClient replaces the legacy HttpUrlConnection class present in the JDK since the early versions of Java.

Some of its features include:

  1. Support for HTTP/1.1, HTTP/2, and Web Socket.
  2. Support for synchronous and asynchronous programming models.
  3. Handling of request and response bodies as reactive streams.
  4. Support for cookies.
Use of HttpClient is preferred if our application is built using Java 11 and above.

sendAsync VS send


Apache HttpClient


Spring WebClient is an asynchronous, reactive HTTP client introduced in Spring 5 in the Spring WebFlux project to replace the older RestTemplate for making REST API calls in applications built with the Spring Boot framework. It supports synchronous, asynchronous, and streaming scenarios.


If you call Block- then it became synchronous. 

Spring WebClient is the preferred choice for Spring Boot applications more importantly if we are using reactive APIs.

WebClient client = WebClient.create();

  client
  .get()
  .uri(URLConstants.URL)
  .header(URLConstants.API_KEY_NAME, URLConstants.API_KEY_VALUE)
  .retrieve()
  .bodyToMono(String.class)
  .subscribe(result->System.out.println(result));


WebClient client = WebClient.create();

    String result = client
            .post()
            .uri("https://reqbin.com/echo/post/json")
            .body(BodyInserters.fromValue(prepareRequest()))
            .exchange()
            .flatMap(response -> response.bodyToMono(String.class))
            .block();
    System.out.println("result::" + result);




CloseableHttpAsyncClient client = 
      HttpAsyncClients.createDefault();) {
   client.start();
    
    final SimpleHttpRequest request = 

CloseableHttpClient httpClient = HttpClients.createDefault();
      
      CloseableHttpResponse response = httpClient.execute(httpPost)


HttpClient client = HttpClient.newBuilder()
      .version(Version.HTTP_2)
      .followRedirects(Redirect.NORMAL)
      .build();
  
  HttpRequest request = HttpRequest.newBuilder()
     .uri(new URI(URLConstants.URL))
     .GET()
     .header(URLConstants.API_KEY_NAME, URLConstants.API_KEY_VALUE)
     .timeout(Duration.ofSeconds(10))
     .build();
  
  
  client.sendAsync(request, BodyHandlers.ofString())
    .thenApply(HttpResponse::body)
    .thenAccept(System.out::println)
    .join();

Tuesday, May 24, 2022

Simple REST API using Spring Webflux, WebClient and Junit

 Dear Java Developers,

we will look into an sample REST API created using Spring Boot, Spring Webflux (Reactive) and integrated with another API using Webclient. 

Also we will add unit test cases to test Controller, Service and Webclient classes. 


OrderService - Receives inputs and checks inventory and create order.

InventoryService checks and confirms products available in inventory. Secured with JWT Token. 


@ResponseStatus



Thursday, August 5, 2021

Spring and Kafka : KafkaListenerEndpointRegistry and MessageListenerContainer

 Hi All,

Section 1: 

The message queues exist for long time and we have been using this for last 15 years. We have used Active MQ, JBoss MQ, Tomcat with Active MQ, JBoss MQ (HornetQ) and WebSphere MQ.

We have been using them a standalone MQ server or server provided MQs like WebSphereMQ and JBOSS MQ.

Now for the last 5 years we have started using RabbitMQ and Kafka which replaced all the above one.

Lets look into them in detail.

Section 2: 

2.1 Sample code for Spring Reactive Kafka Producer and Listener

2.2 Sample code for KafkaListenerEndpointRegistry and MessageListenerContainer



Rabbit MQ: VS Kafka

 

  Rabbit MQ

  Kafka

 Support for Distributed MQ

 

 

 Scalable

 

 

 Support Languages

 

 

 Publisher                                

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


Wednesday, July 28, 2021

Design : Domain Driven Design Concepts and a sample DDD Document

What is Domain Driven Design?

From Martin Fowler's blog : Driven Design is an approach to software development that centers the development on programming a domain model, that has a rich understanding of the processes and rules of domain. 

Any enterprise system can be built on Domain Driven Model comprised of multiple complex domains, so the developer need to understand them well in the language of Business people. 

Lets look into the main terms and definitions: 

  • Context  
    •  means the circle in which a word or domain decides its meaning. 
    • Ex: Inventory, Sales, Billing are different contexts. 
  • Domain 
    •  is a subject area to which the developer applies program. 
    • Ex Order Management, Sales Management, Billing Management 
  • Model
    • Core Model - is the part of your model where the most business value lies and distill it into the highest priority context.
    • The Domain Model is your organized and structured knowledge of the problem. The Domain Model should represent the vocabulary and key concepts of the problem domain and it should identify the relationships among all of the entities within the scope of the domain. 
    • A model in DDD can be represented in a variety of formats such as post-it notes or code. Anything that shows domain concepts, relationships, rules, and so on.
    • The Domain Model itself could be a diagram, code examples or even written documentation of the problem. The important thing is, the Domain Model should be accessible and understandable by everyone who is involved with the project.
    • Examples are a Class Diagram conceptualize the whole domain, for example the class diagram of Order Management System, Insurance Claim Processing System
  • Sub-domain
    • Domain and Subdomain can be used interchangeably. All domain are child of another domain in real scenario. 
    • When we model our domain we might need to split them into sub-domains for easy management
  • Bounded Context
    • Define boundaries around domain areas (objects) and reflect them in software.
    • Any organization serves a main business but has multiple operational divisions like procurement, processing, making, packaging, finance etc., 
    • Similarly we separate and group our models into a limit or boundary, they are called as Bounded Context. 
    • It makes the modelling easy and makes the management better.
    • For example in an divide and Order Management System into Customer, Product, Order, Payment, Billing, Package. 
  • Context Mapping 
    • Model of the different bounded contexts of the system
    • Is a tool that allows you to identify the relationship between bounded contexts and the relationship between the teams that are responsible for them.
    • In most of  real scenarios, two different teams working on different bounded contexts might need to create a model which will be same in set of goals.
    • There are 7 different ways to do context mapping 
      • Partnership - If two models are aligned and dependent on same set of goals, then two teams can mutually understand each other and partner.
      • Shared kernel - Two or more models can share same models. It can be a piece of code, API, library.
      • Customer Supplier - If two bounded contexts found and have some common model may be one of them would be a supplier and another one would be consumer. Like upstreaming and down-streaming. This can be determined by the discussion between the two different teams.
      • Conformist - This is same as Customer Supplier but the upstream BC has no interest in supporting downstream BC, but the downstream BC has to conform the whatever the upstream provides. Example if an organization build a last API system and the downstream is utilizing only one.
      • Anticorruption Layer - Another upstream and downstream bounded contexts, but the downstream BC implements a layer between itself and the upstream. The layer interprets the model according to downstream. Use ubiquitous language in this layer. So whenever new changes are made at upstream, the ACL need to be updated without making any changes to downstream BC. 
      • Open Host ServicePublished Language - Same as upstream and downstream where the upstream will provide a well written document. The downstream will use them, but the upstream does not need the same from downstream.
  • Ubiquitous Language
    • It is nothing but the common language used for documentation and discussion, between developers and domain experts. 
    • It is mandatory to use domain model terms and words instead of developer words. Mix of both business and developer terms can be evolved.
  • Entity 
    • Similar to objects in classic object-oriented design but with a focus on identity over time.
    • An object defined by thread of continuity and identity.
    • A train seat in Ticket Booking Service, an order in Order Services examples of entities.
    • If two entities have same properties, but different identities, then they are different.
  • Value Object
    • Immutable entity identified by its attributes.
    • It is similar to entity but the difference is  they are immutable and defined by attributes rather than identity. 
    • Example if we purchase a water bottle in a shop, all water bottles are same by properties and does not have identity. 
    • If two objects have similar properties, they can be considered equal objects.
  • Aggregate
    • Encapsulates multiple entities and value objects.
    • It is nothing but a (parent object) cluster or group of different objects (child entities). 
    • The parent  which holds the child entities, called as Aggregate Root 
  • Domain Event
    • It is nothing but an change in state happened in domain. 
    • Any domain event must be captured, persisted in event store and need to be communicated for further processing.
    • Domain events may happen with in a bounded context or across multiple bounded context. When an event occurred in a domain it can be informed to other bounded context to complete a eventual business process. 
  • Service
    • Stateless object which encapsulates domain logic that cannot reasonably put on an entity or value object.
    • In DDD services are used to perform domain operations and business rules. 
    • When concepts of the model would distort any Entity or Value Object, a Service is appropriate.
    • From Evans’ DDD, a good Service has these characteristics:
      • The operation relates to a domain concept that is not a natural part of an Entity or Value Object
      • The interface is defined in terms of other elements in the domain model
      • The operation is stateless
  • Repository
    • Library for obtaining access to aggregates.
    • In DDD, repository is an object that participates in domain but really abstracts away the storage (persistence) and infrastructure details.
    • They perform lookup and save, and they are not same as Factory Patterns. In other words they are conceptual set like a collection with fetch and save. 
    • Example : NoSQL Repository, SQL Repository
  • Factory
    • This is a GoF pattern for creating the domain objects. Better implement different Factory objects if we need to create different set of objects
  • Module 
    • Structure objects on a higher level to reduce cognitive overload.
  • Model Integrity Patterns 
    •  Ways to model the connections between multiple bounded contexts
  • CQRS
    • When we decompose a big monolithic applications or building microservices, it is recommended to separate the query services (which fetch data from storage) and command services (which create, modify and delete data in storage). 
    • When the two or more services separated and using single database, we need to check how to scale out database and also share the database across them.