Wednesday, 10 April 2024

Discover and load the implementations of a service using ServiceLoader in Java

The java.util.ServiceLoader class in Java provides a simple mechanism for discovering and loading implementations of a service interface from the classpath. It is part of the Java Standard Library and is often used in modular or plugin-based applications where different implementations of a service interface may be available.

 


Here's how ServiceLoader works:

 

1. Service Provider Interface

First, you define a service interface that represents a contract or API. This interface defines the methods or behaviour that implementations must adhere to.

                                    

To demonstrate the example, I defined a log-service project, and it has LogService interface.

 

LogService.java

package com.sample.app.log.service;

public interface LogService {
	void log(String msg);
}

 

2. Service Provider Implementations

Next, you create one or more implementations of the service interface. These implementations are typically packaged as JAR files and made available in the classpath.

To demonstrate the example, I defined two libraries sdk1, and sdk2 which implement LogService interface.

 

Example

 

public class Sdk1Logger implements LogService {

	@Override
	public void log(String msg) {
		System.out.println("From Sdk1Logger " + new Date() + " : " + msg);
	}

}

 

3. Service Configuration File

Include a special file named META-INF/services/{fully-qualified-service-interface-name} in the JAR files containing the implementations. This file lists the fully qualified class names of the service provider implementations, one per line.

 

com.sample.app.log.service.LogService

com.sample.app.sdk1.log.service.Sdk1Logger

 


4. Service Loading

At runtime, you use the ServiceLoader class to dynamically load implementations of the service interface. The ServiceLoader class reads the service configuration files from the classpath and instantiates the service provider implementations.

ServiceLoader<LogService> logServicesLoader = ServiceLoader.load(LogService.class);

5. Iterating Over Implementations

You can then iterate over the loaded service provider implementations using the iterator() method of ServiceLoader. This returns an iterator that provides access to the instantiated service provider objects.

Iterator<LogService> logServiceIterator = logServicesLoader.iterator();

while (logServiceIterator.hasNext()) {
	LogService logService = logServiceIterator.next();
	logService.log("Hello World");
}

Find the below step-by-step procedure to build the working application.

 

log-service project setup

Create new maven project ‘log-service’ and update pom.xml like below.

 

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>log-service</artifactId>
	<version>1.0.0</version>

	<build>
		<plugins>


			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>3.0.0-M6</version>
			</plugin>


			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-release-plugin</artifactId>
				<version>2.5.3</version>
				<configuration>
					<localCheckout>true</localCheckout>
					<autoVersionSubmodules>true</autoVersionSubmodules>
				</configuration>
			</plugin>

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

Define LogService interface.

 

LogService.java

package com.sample.app.log.service;

public interface LogService {
	void log(String msg);
}

Setup sdk1

Create sdk1 maven project and update pom.xml like below.

 

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>sdk1</artifactId>
	<version>1.0.0</version>

	<dependencies>

		<dependency>
			<groupId>com.sample.app</groupId>
			<artifactId>log-service</artifactId>
			<version>1.0.0</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>


			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>3.0.0-M6</version>
			</plugin>


			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-release-plugin</artifactId>
				<version>2.5.3</version>
				<configuration>
					<localCheckout>true</localCheckout>
					<autoVersionSubmodules>true</autoVersionSubmodules>
				</configuration>
			</plugin>

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

Define Sdk1Logger class.

 

Sdk1Logger.java

package com.sample.app.sdk1.log.service;

import java.util.Date;

import com.sample.app.log.service.LogService;

public class Sdk1Logger implements LogService {

	@Override
	public void log(String msg) {
		System.out.println("From Sdk1Logger " + new Date() + " : " + msg);
	}

}

Create a file 'com.sample.app.log.service.LogService' in src/main/resources/META-INF/services folder of sdk1 project.

 

com.sample.app.log.service.LogService

com.sample.app.sdk1.log.service.Sdk1Logger

sdk2 project setup

Create a new maven project sdk2 and 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>sdk2</artifactId>
	<version>1.0.0</version>

	<dependencies>

		<dependency>
			<groupId>com.sample.app</groupId>
			<artifactId>log-service</artifactId>
			<version>1.0.0</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>


			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>3.0.0-M6</version>
			</plugin>


			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-release-plugin</artifactId>
				<version>2.5.3</version>
				<configuration>
					<localCheckout>true</localCheckout>
					<autoVersionSubmodules>true</autoVersionSubmodules>
				</configuration>
			</plugin>

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

Define Sdk2Logger class.

 

Sdk2Logger.java

package com.sample.app.sdk2.log.service;

import com.sample.app.log.service.LogService;

public class Sdk2Logger implements LogService {

	@Override
	public void log(String msg) {
		System.out.println("From Sdk2Logger : " + msg);
	}

}

Create a file 'com.sample.app.log.service.LogService' in src/main/resources/META-INF/services folder of sdk2 project.

 

com.sample.app.log.service.LogService

com.sample.app.sdk2.log.service.Sdk2Logger

Main project setup

Create new maven project ‘service-loader-demo’. 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>service-loader-demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>

		<dependency>
			<groupId>com.sample.app</groupId>
			<artifactId>sdk1</artifactId>
			<version>1.0.0</version>
		</dependency>

		<dependency>
			<groupId>com.sample.app</groupId>
			<artifactId>sdk2</artifactId>
			<version>1.0.0</version>
		</dependency>


	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<version>3.2.0</version> <!-- Use the latest version -->
				<configuration>
					<archive>
						<manifest>
							<addClasspath>true</addClasspath>
							<mainClass>com.sample.app.App</mainClass>
						</manifest>
					</archive>
				</configuration>
			</plugin>
		</plugins>
	</build>


</project>

Define main application class.

 

App.java

package com.sample.app;

import java.util.Iterator;
import java.util.ServiceLoader;

import com.sample.app.log.service.LogService;

public class App {
	public static void main(String[] args) {

		ServiceLoader<LogService> logServicesLoader = ServiceLoader.load(LogService.class);

		Iterator<LogService> logServiceIterator = logServicesLoader.iterator();

		while (logServiceIterator.hasNext()) {
			LogService logService = logServiceIterator.next();
			logService.log("Hello World");
		}
	}

}

Build log-service artifact

Navigate to pom.xml file of log-service and execute below command.

mvn package

 

Build sdk1 artifact

Navigate to pom.xml file of sdk1 and execute below command.

mvn package

 

Build sdk2 artifact

Navigate to pom.xml file of sdk2 and execute below command.

mvn package

 

Build service-loader-demo project

Navigate to pom.xml file of service-loader-demo and execute below command.

mvn package

 

Copy all the jar files to a folder and run service-loader-demo-0.0.1-SNAPSHOT.jar file to test the application.

$ java -jar service-loader-demo-0.0.1-SNAPSHOT.jar 
From Sdk1Logger Wed Apr 10 20:09:20 IST 2024 : Hello World
From Sdk2Logger : Hello World

You can download this application from this link.



 

You may like

Miscellaneous

How to Get Client Certificate from HttpServletRequest

Programmatically import certificate to cacerts file in Java

Command to check CPU temperature in Mac

Quick guide to Java DecimalFormat class

Compress and decompress a string in Java

Tuesday, 9 April 2024

PlantUML: Highlight some parts of the yaml document

Using #highlight directive, we can highlight some parts of the yaml document.

Example

#highlight "name" : Highlight name property

#highlight "address" / "city" : Highlight city property in address yaml document

#highlight "hobbies" / "1" : Highlight second hobby, here indexing starts from 0.

#highlight "emails" / "0" / "id": Highlight id property of first email object

highlightYaml.txt

@startyaml

#highlight "name"
#highlight "address" / "city"
#highlight "hobbies" / "1"
#highlight "emails" / "0" / "id"

id: 1
name: Krishna
address:
  state: Karnatka
  city: Bnagalore
  country: India
hobbies:
- Playing cricket
- blogging

@endyaml

Above snippet generate below diagram.




 

 

Previous                                                    Next                                                    Home

PlantUML: working with yaml document

We can visualize the yaml document using PlantUML.

 

helloworld.txt

@startyaml

id: 1
name: Krishna
address:
  state: Karnatka
  city: Bnagalore
  country: India
hobbies:
- Playing cricket
- blogging

@endyaml

Above snippet generate below diagram.



 

  

Previous                                                    Next                                                    Home

PlantUML: Customize style or rendering of json document using style tag

Using <style> tag, we can customize the font color, styles, arrow color and styles etc.,

styleTag.txt

@startjson

<style>
jsonDiagram {
	node {
		BackGroundColor silver
		LineColor red
		FontName Helvetica
		FontColor blue
		FontSize 12
		FontStyle italic
		RoundCorner 5
		LineThickness 1
		LineStyle 10;5
		separator {
			LineThickness 0.5
			LineColor brown
			LineStyle 1;5
		}
	}

	arrow {
		BackGroundColor lightblue
		LineColor green
		LineThickness 2
		LineStyle 2;5
	}

	highlight {
		BackGroundColor green
		FontColor white
		FontStyle italic
	}
}
</style>

#highlight "name"
#highlight "address" / "city"
#highlight "hobbies" / "1"
#highlight "emails" / "0" / "id"

{
	"id" : 1,
	"name" : "Krishna",
	"address" : {
		"state" : "Karnatka",
		"city" : "Bnagalore",
		"country" : "India"
	},
	"hobbies" : [
		"Playing cricket",
		"blogging"
	],
	"emails" : [
		{
			"id" : "demo@demo1.com",
			"type" : "personal"
		},
		{
			"id" : "demo@demo2.com",
			"type" : "official"
		}
	]
}

@endjson

 

Above snippet generate below diagram.

 


 

 

  

Previous                                                    Next                                                    Home

Convert multidimensional arrays to a string in Java

The Arrays.deepToString() method is a utility method provided in the java.util package in Java. It's used to generate a string representation of nested arrays.

 

When you pass a multidimensional array to Arrays.deepToString(), If an element e is an array of a primitive type, it is converted to a string as by invoking the appropriate overloading of Arrays.toString(e). If an element e is an array, then deepToString() is recursively called on those arrays until all elements are converted into their string representations.

 

DeepToStringDemo.java

package com.sample.app;

import java.util.Arrays;

public class DeepToStringDemo {
	
	public static void main(String[] args) {
		
		int[][] matrix1 = {
				{1, 2, 3}, 
				{4, 5, 6}, 
				{7, 8, 9}
		};
		String matrixString = Arrays.deepToString(matrix1);
		System.out.println("matrix1 : " + matrixString);
		
		int[][][] matrix2 = {
				{
					{1, 2, 3}, 
					{4, 5, 6}, 
					{7, 8, 9}
				},
				
				{
					{10, 11, 12}, 
					{13, 14, 15}, 
					{16, 17, 18}
				}
				
				
		};
		 matrixString = Arrays.deepToString(matrix2);
		System.out.println("matrix2 : " + matrixString);

	}

}

Output

matrix1 : [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix2 : [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 11, 12], [13, 14, 15], [16, 17, 18]]]



Previous                                                 Next                                                 Home

Monday, 8 April 2024

Implementing a Stack Data Structure in Java Using ArrayList

 

A stack is a fundamental data structure in computer science that follows the Last In, First Out (LIFO) principle. Imagine a stack of plates where you can only add or remove the top plate. Similarly, in a stack data structure, elements are added and removed from the top, allowing for efficient last-in, first-out access.

 

Key operations of Stack

a.   Push Operation: The push operation adds an element to the top of the stack. When you push an element onto a stack, it becomes the new top element.

b.   Pop Operation: The pop operation removes the top element from the stack. It returns the removed element and updates the stack's top pointer to the next element.

c.    Size Operation: The size operation returns the number of elements currently present in the stack.


 

Use Cases of Stack

Stacks is used in various areas of computer science and software development:

 

1.   Function Call Stack: In programming languages like Java, C++, and Python, a function call stack is used to manage function calls and local variables.

2.   Expression Evaluation: Stacks are commonly used to evaluate arithmetic expressions, postfix, and infix expressions.

3.   Undo Mechanisms: Many applications use stacks to implement undo functionality, where each operation performed is pushed onto the stack, allowing users to undo their actions in reverse order.

4.   Browser History: Web browsers use a stack to store the history of visited web pages, enabling users to navigate back and forth.

5.   Backtracking Algorithms: Stack-based backtracking algorithms are used to solve problems such as maze traversal, graph traversal, and puzzle solving.

 

Implementing a Stack using ArrayList in Java:

Below is a simple implementation of a stack data structure using the ArrayList class in Java:

 

ArrayStack.java 

package com.sample.app.util;

import java.util.ArrayList;

public class ArrayStack<T> {

	private final ArrayList<T> stack;

	public ArrayStack() {
		stack = new ArrayList<>();
	}

	public ArrayStack(int initSize) {
		stack = new ArrayList<T>(initSize);
	}

	public void push(T obj) {
		stack.add(obj);
	}

	public T pop() {
		if (isEmpty()) {
			throw new IllegalStateException("Stack is empty");
		}
		return stack.remove(stack.size() - 1);
	}

	public boolean isEmpty() {
		return stack.isEmpty();
	}

	public int size() {
		return stack.size();
	}

	public void clear() {
		stack.clear();
	}

	public void print() {
		System.out.println("\nElements in the stack are");
		for (int i = stack.size() - 1; i >= 0; i--) {
			System.out.println(stack.get(i));
		}
	}

}

 

ArrayStackDemo.java

package com.sample.app;

import com.sample.app.util.ArrayStack;

public class ArrayStackDemo {
	
	public static void main(String[] args) {
		ArrayStack<Integer> stack = new ArrayStack<> ();
		
		stack.push(1);
		stack.push(2);
		stack.push(3);
		stack.push(4);
		stack.push(5);
		
		stack.print();
		
		System.out.println("\nPop two elements from stack");
		
		stack.pop();
		stack.pop();
		
		stack.print();
		
		System.out.println("\nAdd an element 6 to the stack");
		stack.push(6);
		stack.print();
		
	}

}

 

Output

Elements in the stack are
5
4
3
2
1

Pop two elements from stack

Elements in the stack are
3
2
1

Add an element 6 to the stack

Elements in the stack are
6
3
2
1

 

You may like


Pandas: pivot: Reshape the dataframe

In this post, I am going to explain how to reshape the dataframe using pivot method.

 

Signature

DataFrame.pivot(index=None, columns=None, values=None)’

 

Following table summarize the parameters of pivot method.

 

Parameter

Description

index

Specify the column(s) to use as the new DataFrame index.

columns

The column(s) to use as the new DataFrame columns.

values

The column(s) to use as the values in the new DataFrame.

 

Let’s try to experiment with below dataset.

       Name  Age       City  Gender      Education
0   Krishna   34  Bangalore    Male       Graduate
1     Sailu   35  Hyderabad  Female  Post Graduate
2      Joel   29  Hyderabad    Male            PHD
3     Chamu   35    Chennai  Female       Graduate
4  Jitendra   52  Bangalore    Male       Graduate
5   Krishna   34    Chennai    Male   Intermediate

Let’s reshape the data frame by setting

a.   ['Education', 'Age'] columns as index columns

b.   ['City', 'Gender'] as column headers

c.    ['Name'] as column values

 

new_df = df.pivot(index=['Education', 'Age'], columns=['City', 'Gender'], values = ['Name'])

 

new_df points to below data set.

                        Name                                 
City              Bangalore Hyderabad       Chennai         
Gender                 Male    Female  Male  Female     Male
Education     Age                                           
Graduate      34    Krishna       NaN   NaN     NaN      NaN
              35        NaN       NaN   NaN   Chamu      NaN
              52   Jitendra       NaN   NaN     NaN      NaN
Intermediate  34        NaN       NaN   NaN     NaN  Krishna
PHD           29        NaN       NaN  Joel     NaN      NaN
Post Graduate 35        NaN     Sailu   NaN     NaN      NaN

 

Find the below working application.

 

pivot.py
import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Krishna"],
        'Age': [34, 35, 29, 35, 52, 34],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male'],
        'Education': ['Graduate', 'Post Graduate', 'PHD', 'Graduate', 'Graduate', 'Intermediate']}
df = pd.DataFrame(data)
print('Original DataFrame')
print(df)

new_df = df.pivot(index=['Education', 'Age'], columns=['City', 'Gender'], values = ['Name'])
print('\nnew_df\n',new_df)

Output

Original DataFrame
       Name  Age       City  Gender      Education
0   Krishna   34  Bangalore    Male       Graduate
1     Sailu   35  Hyderabad  Female  Post Graduate
2      Joel   29  Hyderabad    Male            PHD
3     Chamu   35    Chennai  Female       Graduate
4  Jitendra   52  Bangalore    Male       Graduate
5   Krishna   34    Chennai    Male   Intermediate

new_df
                        Name                                 
City              Bangalore Hyderabad       Chennai         
Gender                 Male    Female  Male  Female     Male
Education     Age                                           
Graduate      34    Krishna       NaN   NaN     NaN      NaN
              35        NaN       NaN   NaN   Chamu      NaN
              52   Jitendra       NaN   NaN     NaN      NaN
Intermediate  34        NaN       NaN   NaN     NaN  Krishna
PHD           29        NaN       NaN  Joel     NaN      NaN
Post Graduate 35        NaN     Sailu   NaN     NaN      NaN

 

 

Previous                                                 Next                                                 Home