Wednesday, 17 August 2022

Accessing ElasticSearch in TestContainer


During the Unit test or Integration test, it may need to verify if a document having been persisted successfully.  


Using UI tool



Using command

docker ps to list all containers, and find out elastic container port(exposure port) number

ac8dec5773de   docker.elastic.co/elasticsearch/elasticsearch:8.1.3   "/bin/tini -- /usr/l…"   4 days ago       Up 4 days       0.0.0.0:64595->9200/tcp, 0.0.0.0:64596->9300/tcp   vigilant_pike




List all index                                

Sunday, 7 August 2022

Kubernetes

Terms

Cluster: a set of nodes.

Node:  a virtual machine(VM) or physical machine. 

Master node: managing working workers.

Worker node: running applications.

Pod: a pod is the smallest deployable unit in K8s and not containers. A pod enclose containers and volumes(used for sharing data among containers). A pod has a unique IP address. 


Run K8 locally

Minikube:  installing docker + minikube


Kubectl

K8 command line tool,  providing commands to gain your cluster residing in the minikube

then we may deploy, inspect, edit resources, debug, and view logs.


minikube start > start the k8

kubectl get nodes> showing all nodes running in the k8

kubectl get pods -A > showing all pods in all namespaces


creating k8 deployment.yml VC.

kubectl apply -f deployment.yml


kubectl get svc>  get service(defined in deployment YAML file service section)

minikube service myapp : access service port


start tunnel for service myapp via URL








Thursday, 4 August 2022

Thread Resources

 A Java thread uses 20M memory space and needs about 10ms to launch it. 

So for a laptop having 16G memory, it can host about 800 threads. 


Tuesday, 19 July 2022

Mock Test


You use mocking in order to “fool” a Java object to think that it communicates with other real objects. Meaning that we may emulate class's dependencies, but not instantiating real ones. By such a way, we may decouple a focus class from its dependencies.

When mocking dependencies, the inputs of test become much more controllable, and test outputs can be easily asserted. Or, in some cases, the dependencies are not available, then we may still implement test by mocking them.

In my impression, smart + lazy = efficient; So, choose a Java mock framework, like Mockito. It gives human-like syntax. Actually, it has been included in Spring boot test starter.

I think the mocking test is able to decouple the dependencies, and making a unit test possible.
Certainly, in another way around, we may need to see how classes together to interact with each other, i.e. an integrated test. In such a case, we may need to see the server on, at least a simulated servlet container (or servlet dispatcher), database connections. We may simulate an Http request and then trigger the servlet service on, fetching data set from the database, running the business logic, and making an HTTP response. By this way, we may confirm that for instance, a rest API may work as supposed when it moves to the production.


How to create static mock:

Mockito must be higher than 3.4; must include mockito-inline and mockito-core both;  

<dependency>
<artifactId>mockito-core</artifactId>
<groupId>org.mockito</groupId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<scope>test</scope>
</dependency>

How to create Static Partial Mock: 


Optional Answer to be used with mock(Class, Answer)
Answer can be used to define the return values of unstubbed invocations.
This implementation can be helpful when working with legacy code. When this implementation is used, unstubbed methods will delegate to the real implementation. This is a way to create a partial mock object that calls real methods by default.

try(var mockedInstant = Mockito.mockStatic(Instant.class, Mockito.CALLS_REAL_METHODS)){
counter = 0;
mockedInstant.when(Instant::now).thenAnswer(
new Answer<>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
counter++;
switch (counter)
{
case 1,2,3 -> {
return AutomatedActionTestData.instants[counter - 1];
}
default -> {
return invocation.callRealMethod();
}
}
}
});



The most widely used annotation in Mockito is @Mock. We can use @Mock to create and inject mocked instances without having to call Mockito.mock manually.

The MockStatic returns a closable resource, so we put it inside try-with-resource block, so as to automatically close it afterwards. Don't forget to put a full assignment here, otherwise you will see a compiling error. 

@Before: running the annotated method, before each test method. We need to enable Mockito annotations before each test method. 

Alternatively, we can enable Mockito annotations programmatically by invoking MockitoAnnotations.initMocks():

@Before
public void init() {
    MockitoAnnotations.initMocks(this);
}

Sunday, 19 June 2022

What is a saga?

A saga is a sequence of local transactions, across several services, which maintain their own database. it, therefore, leads to a challenge to keep distributing data states consistently. 

There are two ways of coordinating sagas. 

  1. Choreography(Event-based):  each local transaction publishes domain events that trigger local transactions in other services.
  2. Orchestration(Command-based):  an orchestrator(object) tells the participants what local transaction to execute. 

Choreography:

All services are linked by a message queue. Service A launches a local transaction for A operation and then sends a message to trigger Service B, and then Service B launches a local transaction B for B operation. Service B may send a message back to service A to report Service A the results.

Service A is an initiator of a business flow, which consists of several independent local transactions.

When a local transaction fails, an initiator is informed, and then the implemented local transactions are rolled back.  




Orchestration:

Orchestrator service is the centre of all services, and it supervises the entire flow of services to carry a business logic dynamically. If one service fails, then the orchestrator may ask for rolling back implemented distributed local transactions. 



Tuesday, 20 July 2021

SpringBoot Output JPA Queries

Output SQL queries

The simplest way to output SQL queries, but it is not recommended. it directly uploads to standard output without any optimizations of a logging framework. Moreover, it doesn't log the parameters of prepared statements.

spring.jpa.show-sql=true

spring.jpa.properties.hibernate.format_sql=true


Output SQL queries via loggers

The hibernate logs will be sent to the configured appender. By default, Spring Boot uses Logback with a standard out appender. 

logging.level.org.hibernate.SQL=DEBUG 

logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE


Insert OffsetDateTime into PostgreSQL

 The SQL standard differentiates timestamps with time zone and without time zone literals by the presence of a "+" or "-" symbol and time zone offset after the time. Hence, according to the standard,

Without time-zone

'1999-01-08 04:05:06'                        

With time-zone

'1999-01-08 04:05:06 -8:00'




Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...