Thursday, 26 January 2023

Micronaut: replace default implementation of an interface

@DefaultImplementation annotation is applied on an interface to indicate which implementation is the default implementation.

 

But there are cases, where you might need to replace the default implementation of the interface due to visibility restrictions of the class.

@DefaultImplementation(FileDataSource.class)
public interface DataSource {

}

@Singleton
class FileDataSource implements DataSource {
	public String toString() {
		return "MySQLDataSource";
	}

}

@Singleton
@Replaces(DataSource.class)
public class MySQLDataSource implements DataSource {

	@Override
	public String toString() {
		return "MySQLDataSource";
	}

}

In the above example, the MySQLDataSource replaces the FileDataSource because the DefaultImplementation annotation points to the FileDataSource.

 

Find the below working application.

 

Step 1: Create new maven project ‘micronaut-default-implementation-demo’.

 

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-default-implementation-demo</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 DataSource interface.

 

DataSource.java

package com.sample.app.interfaces;

import io.micronaut.context.annotation.DefaultImplementation;
import jakarta.inject.Singleton;

@DefaultImplementation(FileDataSource.class)
public interface DataSource {

}

@Singleton
class FileDataSource implements DataSource {
	public String toString() {
		return "FileDataSource";
	}

}

Step 4: Define MySQLDataSource class.

 

MySQLDataSource.java

package com.sample.app.interfaces.impl;

import com.sample.app.interfaces.DataSource;

import io.micronaut.context.annotation.Replaces;
import jakarta.inject.Singleton;

@Singleton
@Replaces(DataSource.class)
public class MySQLDataSource implements DataSource {

	@Override
	public String toString() {
		return "MySQLDataSource";
	}

}

Step 5: Define main application class.

 

App.java

package com.sample.app;

import com.sample.app.interfaces.DataSource;

import io.micronaut.context.ApplicationContext;

public class App {

	public static void main(String[] args) {
		try (ApplicationContext applicationContext = ApplicationContext.run()) {
			DataSource dataSource = applicationContext.getBean(DataSource.class);
			
			System.out.println(dataSource);
		}
	}
}

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-default-implementation-demo-1-jar-with-dependencies.jar’ in project target folder.

$ ls ./target/
archive-tmp
classes
generated-sources
maven-archiver
maven-status
micronaut-default-implementation-demo-1-jar-with-dependencies.jar
micronaut-default-implementation-demo-1.jar
test-classes

Execute below command to run the application.

java -jar ./target/micronaut-default-implementation-demo-1-jar-with-dependencies.jar
$ java -jar ./target/micronaut-default-implementation-demo-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.
MySQLDataSource

You can download this application from this link.



Previous                                                    Next                                                    Home

PlantUML: Add secondary group label

You can specify a secondary label to the group by placing the text between [].

 

Syntax

group label [secondaryLabel]

 

secondaryGroupLabel.txt

@startuml

title "User login flow"
header "User login"
footer %page% of %lastpage%

Client -> LoginServer: Enter user name
Client -> LoginServer: Enter password
Client -> LoginServer: Submit the form 
LoginServer -> ADServer: Check the credentials

alt#green #lightblue login successful
	ADServer -> LoginServer: Login Successful
	LoginServer -> Client: Login Successful

else Server not accessible

	group#silver "Retry to connect the server" [Login retry]
		loop #00FFF8 "three times"
			LoginServer -> ADServer: Check the credentials
		end
	end

else #gold username is not exists
	ADServer -> LoginServer: Username not found
	LoginServer -> Client: User is not registered with the website

else #red invalid credentials
	ADServer -> LoginServer: Credentials mismatch
	LoginServer -> Client: Invalid username or password

end

@enduml

 

Above snippet generates below diagram.

 


 

 

Previous                                                    Next                                                    Home

PlantUML: Group the statements

‘group’ keyword is used to group the statements.

 

group.txt

@startuml

title "User login flow"
header "User login"
footer %page% of %lastpage%

Client -> LoginServer: Enter user name
Client -> LoginServer: Enter password
Client -> LoginServer: Submit the form 
LoginServer -> ADServer: Check the credentials

alt#green #lightblue login successful
	ADServer -> LoginServer: Login Successful
	LoginServer -> Client: Login Successful

else Server not accessible

	group#silver "Retry to connect the server"
		loop #00FFF8 "three times"
			LoginServer -> ADServer: Check the credentials
		end
	end

else #gold username is not exists
	ADServer -> LoginServer: Username not found
	LoginServer -> Client: User is not registered with the website

else #red invalid credentials
	ADServer -> LoginServer: Credentials mismatch
	LoginServer -> Client: Invalid username or password

end

@enduml

 

Above snippet generates below diagram.


 

Previous                                                    Next                                                    Home

PlantUML: loop: Specify the recurring instructions

‘loop’ keyword specify the recurring instructions.

 

loop.txt

@startuml

title "User login flow"
header "User login"
footer %page% of %lastpage%

Client -> LoginServer: Enter user name
Client -> LoginServer: Enter password
Client -> LoginServer: Submit the form 
LoginServer -> ADServer: Check the credentials

alt#green #lightblue login successful
	ADServer -> LoginServer: Login Successful
	LoginServer -> Client: Login Successful

else Server not accessible

	group "Retry to connect the server"
		loop "three times"
			LoginServer -> ADServer: Check the credentials
		end
	end

else #gold username is not exists
	ADServer -> LoginServer: Username not found
	LoginServer -> Client: User is not registered with the website

else #red invalid credentials
	ADServer -> LoginServer: Credentials mismatch
	LoginServer -> Client: Invalid username or password

end

@enduml

 

Above snippet generates below diagram.


 

 

Previous                                                    Next                                                    Home

Tuesday, 24 January 2023

Quick guide to format code snippets in Javadoc

In this post, I am going to explain how to format various code snippets in Javadoc.

 

a.   Using <pre> tag

b.   Using <code> tag

c.    Using {@code}

d.   Using <pre> + {@code}

 

Using <pre> tag

<pre> tag defines the preformatted text, the content in <pre> tag preserves both spaces and line break.

 

Example

/**
 * Resource module provides a method to get a Resource instance.
 * 
 * <pre>
 * 	Resource resource = Resource.create();
 * 	resource.text();
 * 	resource.close();
 * </pre>
 * 
 * @author Krishna
 *
 */
public interface Resource extends AutoCloseable {

}

Above snippet generate below Javadoc.



Using <code> tag

Indentation and line breaks are lost in the <code> block. Special characters like '@', '<' and '>' have to be escaped with HTML codes.

/**
 * Resource module provides a method to get a Resource instance.
 * 
 * <code>
 * 	Resource resource = Resource.create();
 * 	resource.text();
 * 	resource.close();
 * </code>
 * 
 * @author Krishna
 *
 */
public interface Resource extends AutoCloseable {

}

Above snippet generate below Javadoc.



 

Using {@code}

{@code} tag is introduced in Java1.5 to document the code snippets.  Code embedded inside {@code} tag will display correctly, but the indentation and line breaks will be lost.

 

/**
 * Resource module provides a method to get a Resource instance.
 * 
 * {@code
 * 	Resource resource = Resource.create();
 * 	resource.text();
 * 	resource.close();
 * }
 * 
 * @author Krishna
 *
 */
public interface Resource extends AutoCloseable {

}

 

Above snippet generate below Javadoc.

 

 


Using <pre> + {@code}

By combining <pre> + {@code} we can

a.   Keep line breaks and spaces

b.   Keep special characters

 

/**
 * Resource module provides a method to get a Resource instance.
 * 
 * <pre>
 * {@code
 * 	Resource resource = Resource.create();
 * 	resource.text();
 * 	resource.close();
 * }
 * </pre>
 * @author Krishna
 *
 */
public interface Resource extends AutoCloseable {

}

Above snippet generate below javadoc.

 


 

 

Points to note

a.   Use <pre>...</pre> for multi-line java code snippets

b.   Use {@code} for inline code snippets

c.    Use <pre>{@code ... }</pre>, when you have some markup code like XML, HTML etc.,

 

 

Previous                                                 Next                                                 Home

Monday, 23 January 2023

Micronaut : replace one or more factory methods but retain the rest?

By applying the @Replaces annotation on the method(s) and denote the factory to apply to, we can replace one or more factory methods and retain the rest.

@Factory
public class BooksBeanFactoryV2 {

	@Singleton
	@Named("java_tutorial_1")
	@Replaces(value = Book.class, factory = BooksBeanFactoryV1.class, named = "java_tutorial_1")
	public Book javaBook() {
		Book book1 = new Book("Programming for beginners (https://self-learning-java-tutorial.blogspot.com)");
		return book1;
	}
}

Find the below working application.

 

Step 1: Create new maven project ‘micronaut-replace-factory-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-replace-factory-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 Book class.

 

Book.java

package com.sample.app.beans;

public class Book {

	private String title;

	public Book(String title) {
		this.title = title;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	@Override
	public String toString() {
		return "Book [title=" + title + "]";
	}

}

Step 4: Define factory classes.

 

BooksBeanFactoryV1.java

package com.sample.app.bean.factories;

import com.sample.app.beans.Book;

import io.micronaut.context.annotation.Factory;
import jakarta.inject.Named;
import jakarta.inject.Singleton;

@Factory
public class BooksBeanFactoryV1 {
	
	@Singleton
	@Named("java_tutorial_1")
	public Book javaBook1() {
		Book book1 = new Book("Complete reference to Java");
		return book1;
	}
	
	@Singleton
	@Named("java_tutorial_2")
	public Book javaBook2() {
		Book book1 = new Book("Java for beginners");
		return book1;
	}
	
	@Singleton
	@Named("c_tutorial")
	public String cBook() {
		return new String("Let us C");
	}

}

BooksBeanFactoryV2.java

package com.sample.app.bean.factories;

import com.sample.app.beans.Book;

import io.micronaut.context.annotation.Factory;
import io.micronaut.context.annotation.Replaces;
import jakarta.inject.Named;
import jakarta.inject.Singleton;

@Factory
public class BooksBeanFactoryV2 {

	@Singleton
	@Named("java_tutorial_1")
	@Replaces(value = Book.class, factory = BooksBeanFactoryV1.class, named = "java_tutorial_1")
	public Book javaBook() {
		Book book1 = new Book("Programming for beginners (https://self-learning-java-tutorial.blogspot.com)");
		return book1;
	}
}

Step 5: Define main application class.

 

App.java

package com.sample.app;

import com.sample.app.beans.Book;

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()) {
			Book javaTutorial1 = applicationContext.getBean(Book.class, Qualifiers.byName("java_tutorial_1"));
			Book javaTutorial2 = applicationContext.getBean(Book.class, Qualifiers.byName("java_tutorial_2"));
			String cTutorial = applicationContext.getBean(String.class, Qualifiers.byName("c_tutorial"));

			System.out.println(javaTutorial1);
			System.out.println(javaTutorial2);
			System.out.println(cTutorial);

		}
	}
}

 

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-replace-factory-methods-1-jar-with-dependencies.jar’ in project target folder.

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

 

Execute below command to run the application

java -jar ./target/micronaut-replace-factory-methods-1-jar-with-dependencies.jar
$ java -jar ./target/micronaut-replace-factory-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.
Book [title=Programming for beginners (https://self-learning-java-tutorial.blogspot.com)]
Book [title=Java for beginners]
Let us C

You can download this application from this link.




 

Previous                                                    Next                                                    Home