Friday, 27 January 2023

PlantUML: Add notes to the messages in a sequence diagram

Using ‘note left’, ‘note right’ keywords we can add notes the messages in a sequence diagram.

 

notes.txt

@startuml

Client -> LoginServer: Enter user name
Client -> LoginServer: Enter password
note left: Input from the user \n should be taken by client

Client -> LoginServer: Submit the form 
note right: User details are validated \n against login server

LoginServer -> ADServer: Check the credentials
ADServer -> LoginServer: Login Successful
LoginServer -> Client: Login Successful

@enduml

Above snippet generates below diagram.



 

 

Previous                                                    Next                                                    Home

Thursday, 26 January 2023

Micronaut: Publish and listen on custom events

In this post, I am going to explain how to publish and listen on custom events in Micronaut.

 

Define an event class.

public class ConnectionCreateEvent {
	private String message;

	public ConnectionCreateEvent(String message) {
		this.message = message;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
}

 

Define a publisher bean that emit the ConnectionCreateEvent messages.

@Singleton
public class ConnectionCreateEventPublisher {
	
	@Inject
	ApplicationEventPublisher<ConnectionCreateEvent> eventPublisher;

	public void publishEvent(String message) {
		eventPublisher.publishEvent(new ConnectionCreateEvent(message));
	}
}

Define a listener for ConnectionCreateEvents. To listen to an event, register a bean that implements ApplicationEventListener where the generic type is the type of event.

@Singleton
public class ConnectionCreateEventListener implements ApplicationEventListener<ConnectionCreateEvent> {

	@Override
	public void onApplicationEvent(ConnectionCreateEvent event) {
		System.out.println("message : '" + event.getMessage() + "'");
	}

}

Find the below working application.

 

Step 1: Create new maven project ‘micronaut-publish-listen-events’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>micronaut-publish-listen-events</artifactId>
	<version>1</version>

	<properties>
		<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
		<micronaut.version>3.7.1</micronaut.version>
		<slf4j.version>2.0.3</slf4j.version>

		<maven.compiler.target>15</maven.compiler.target>
		<maven.compiler.source>15</maven.compiler.source>
	</properties>

	<dependencies>

		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-inject-java</artifactId>
			<version>${micronaut.version}</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-simple</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>

			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
				<configuration>
					<archive>
						<manifest>
							<mainClass>com.sample.app.App</mainClass>
						</manifest>
					</archive>
					<descriptorRefs>
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
				</configuration>

				<executions>
					<execution>
						<id>make-assembly</id>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>

		</plugins>
	</build>
</project>

Step 3: Define ConnectionCreateEvent class.

 

ConnectionCreateEvent.java

package com.sample.app.event;

public class ConnectionCreateEvent {
	private String message;

	public ConnectionCreateEvent(String message) {
		this.message = message;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
}

Step 4: Define event publisher.

 

ConnectionCreateEventPublisher.java

package com.sample.app.event.publishers;

import com.sample.app.event.ConnectionCreateEvent;

import io.micronaut.context.event.ApplicationEventPublisher;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;

@Singleton
public class ConnectionCreateEventPublisher {
	
	@Inject
	ApplicationEventPublisher<ConnectionCreateEvent> eventPublisher;

	public void publishEvent(String message) {
		eventPublisher.publishEvent(new ConnectionCreateEvent(message));
	}
}

Step 5: Define event listener.

 

ConnectionCreateEventListener.java

package com.sample.app.event.listeners;

import com.sample.app.event.ConnectionCreateEvent;

import io.micronaut.context.event.ApplicationEventListener;
import jakarta.inject.Singleton;

@Singleton
public class ConnectionCreateEventListener implements ApplicationEventListener<ConnectionCreateEvent> {

	@Override
	public void onApplicationEvent(ConnectionCreateEvent event) {
		System.out.println("message : '" + event.getMessage() + "'");
	}

}

Step 6: Define main application class.

 

App.java

package com.sample.app;

import com.sample.app.event.publishers.ConnectionCreateEventPublisher;

import io.micronaut.context.ApplicationContext;

public class App {

	public static void main(String[] args) {
		try (ApplicationContext applicationContext = ApplicationContext.run()) {
			ConnectionCreateEventPublisher connectionCreateEventPublisher = applicationContext.getBean(ConnectionCreateEventPublisher.class);

			connectionCreateEventPublisher.publishEvent("Connection1 created");
			connectionCreateEventPublisher.publishEvent("Connection2 created");
			connectionCreateEventPublisher.publishEvent("Connection3 created");
		}

	}
}

Total project structure looks like below.




Build the project using mvn package command.

Navigate to the folder where pom.xml is located and execute the command ‘mvn package’.

Upon command successful execution, you can see the jar file ‘micronaut-publish-listen-events-1-jar-with-dependencies.jar’ in project target folder.

$ ls ./target/
archive-tmp
classes
generated-sources
maven-archiver
maven-status
micronaut-publish-listen-events-1-jar-with-dependencies.jar
micronaut-publish-listen-events-1.jar
test-classes

Execute below command to run the application.

java -jar ./target/micronaut-publish-listen-events-1-jar-with-dependencies.jar
$ java -jar ./target/micronaut-publish-listen-events-1-jar-with-dependencies.jar
message : 'Connection1 created'
message : 'Connection2 created'
message : 'Connection3 created'

You can download this application from this link.



Previous                                                    Next                                                    Home

Micronaut: Bean life cycle methods

Micronaut support following annotations to get a notification, when the bean is constructed, bean is destroyed.

 

@PostConstruct

The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This  method must be invoked before the class is put into service.

 

@PreDestroy

@PreDestroy annotation is used on a method as a callback notification to signal that the instance is in the process of being removed by the container. The method annotated with PreDestroy is typically used to release resources that it has been holding.

@Singleton
public class DataSource {

	public DataSource() {
		System.out.println("Datasource constructor called");
	}

	@PreDestroy
	public void close() {
		System.out.println("DataSource closed");
	}

	@PostConstruct
	public void initialize() {
		System.out.println("DataSource initialized");
	}
}

You can even specify the PreDestroy method for factory beans at the time of definition.

@Bean(preDestroy = "stop")
@Named("my_connection1")
public Connection connection1() {
	return new Connection();
}

Find the below working application.

 

Step 1: Create new maven project ‘micronaut-bean-life-cycle-methods’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>micronaut-bean-life-cycle-methods</artifactId>
	<version>1</version>

	<properties>
		<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
		<micronaut.version>3.7.1</micronaut.version>

		<maven.compiler.target>15</maven.compiler.target>
		<maven.compiler.source>15</maven.compiler.source>
	</properties>

	<dependencies>

		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-inject-java</artifactId>
			<version>${micronaut.version}</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>

			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
				<configuration>
					<archive>
						<manifest>
							<mainClass>com.sample.app.App</mainClass>
						</manifest>
					</archive>
					<descriptorRefs>
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
				</configuration>

				<executions>
					<execution>
						<id>make-assembly</id>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>

		</plugins>
	</build>
</project>

Step 3: Define Connection and DataSource classes.

 

Connection.java

package com.sample.app.beans;

public class Connection {

	public Connection() {
		System.out.println("\nConnection constructor called\n");
	}

	public void stop() {
		System.out.println("Connection stopped");
	}

	public void destroy() {
		System.out.println("Connection destroyed");
	}
}

DataSource.java

package com.sample.app.beans;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.inject.Singleton;

@Singleton
public class DataSource {

	public DataSource() {
		System.out.println("\nDatasource constructor called");
	}

	@PreDestroy
	public void close() {
		System.out.println("DataSource closed");
	}

	@PostConstruct
	public void initialize() {
		System.out.println("DataSource initialized");
	}
}

Step 4: Define main application class.

 

App.java

package com.sample.app;

import com.sample.app.beans.Connection;
import com.sample.app.beans.DataSource;

import io.micronaut.context.ApplicationContext;
import io.micronaut.inject.qualifiers.Qualifiers;

public class App {

	public static void main(String[] args) {
		try (ApplicationContext applicationContext = ApplicationContext.run()) {
			applicationContext.getBean(DataSource.class);
			
			applicationContext.getBean(Connection.class, Qualifiers.byName("my_connection1"));
			
			applicationContext.getBean(Connection.class, Qualifiers.byName("my_connection2"));
		}

		System.out.println("about to terminate the app");
	}
}

Total project structure looks like below.




Build the project using mvn package command.

Navigate to the folder where pom.xml is located and execute the command ‘mvn package’.

 

Upon command successful execution, you can see the jar file ‘micronaut-bean-life-cycle-methods-1-jar-with-dependencies.jar’ in project target folder.


$ ls ./target/
archive-tmp
classes
generated-sources
maven-archiver
maven-status
micronaut-bean-life-cycle-methods-1-jar-with-dependencies.jar
micronaut-bean-life-cycle-methods-1.jar
test-classes

Execute below command to run the application.

java -jar ./target/micronaut-bean-life-cycle-methods-1-jar-with-dependencies.jar

$ java -jar ./target/micronaut-bean-life-cycle-methods-1-jar-with-dependencies.jar
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

Datasource constructor called
DataSource initialized

Connection constructor called


Connection constructor called

Connection destroyed
DataSource closed
Connection stopped
about to terminate the app

You can download this application from this link.


 

Previous                                                    Next                                                    Home