Tuesday, 7 February 2023

Micronaut: Introduction to Bean introspection api

In this post, let’s quickly discuss how to introspect a bean in Micronaut.

 

Step 1: Annotate the bean with @Introspected annotation.

@Introspected
public class Person {

	private Integer id;

	private String name;

	public Person(Integer id, String name) {
		this.id = id;
		this.name = name;
	}

	............
	............
}

 

Step 2: Retrieve the introspection data using BeanIntrospection class.

try (ApplicationContext applicationContext = ApplicationContext.run()) {
	final BeanIntrospection<Person> introspection = BeanIntrospection.getIntrospection(Person.class);
	Person person = introspection.instantiate(1, "Krishna");
	
	System.out.println("id : " + person.getId());
	System.out.println("name : " + person.getName());

	final BeanProperty<Person, String> property = introspection.getRequiredProperty("name", String.class); 
	property.set(person, "Ram"); //
	String name = property.get(person);

	System.out.println("\nname : " + name);	
	System.out.println("\nid : " + person.getId());
	System.out.println("name : " + person.getName());

}

 

Find the below working application.

 

Step 1: Create new maven project ‘micronaut-bean-introspection-hello-world’.

 

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-introspection-hello-world</artifactId>
	<version>1</version>

	<properties>
		<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
		<micronaut.version>3.7.2</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>io.micronaut</groupId>
			<artifactId>micronaut-runtime</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 Person class.

 

Person.java

package com.sample.app.model;

import io.micronaut.core.annotation.Introspected;

@Introspected
public class Person {

	private Integer id;

	private String name;

	public Person(Integer id, String name) {
		this.id = id;
		this.name = name;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

Step 4: Define main application class.

 

App.java

package com.sample.app;

import com.sample.app.model.Person;

import io.micronaut.context.ApplicationContext;
import io.micronaut.core.beans.BeanIntrospection;
import io.micronaut.core.beans.BeanProperty;

public class App {

	public static void main(String[] args) {
		try (ApplicationContext applicationContext = ApplicationContext.run()) {
			final BeanIntrospection<Person> introspection = BeanIntrospection.getIntrospection(Person.class);
			Person person = introspection.instantiate(1, "Krishna");
			
			System.out.println("id : " + person.getId());
			System.out.println("name : " + person.getName());

			final BeanProperty<Person, String> property = introspection.getRequiredProperty("name", String.class); 
			property.set(person, "Ram"); //
			String name = property.get(person);
		
			System.out.println("\nname : " + name);	
			System.out.println("\nid : " + person.getId());
			System.out.println("name : " + person.getName());

		}

	}
}

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-introspection-hello-world-1-jar-with-dependencies.jar’ in project target folder.

 

$ls ./target/
archive-tmp
classes
generated-sources
generated-test-sources
maven-archiver
maven-status
micronaut-bean-events-demo-1-jar-with-dependencies.jar
micronaut-bean-events-demo-1.jar
micronaut-bean-introspection-hello-world-1-jar-with-dependencies.jar
micronaut-bean-introspection-hello-world-1.jar
test-classes

 

Execute below command to run the application.

$java -jar ./target/micronaut-bean-introspection-hello-world-1-jar-with-dependencies.jar
id : 1
name : Krishna

name : Ram

id : 1
name : Ram

 

You can download this application from application this link.


 

 

Previous                                                    Next                                                    Home

PlantUML: Define diagram title using creol format

You can use creole formatting in the title of a diagram.

 

titleCreol.txt

@startuml

title __Simple__ **client server communication** example

participant client
participant server

client -> server : Send request
server -> client : Send response
client -> server: close connection

@enduml

Above snippet generates below diagram.



  

Previous                                                    Next                                                    Home

How to check whether an alias exists in a keystore file or not?

Below command print the entry with given alias if exists, else throws an Exception.

keytool -list -keystore {my_key_store} -alias {my_alias}

 

All the entries in a keystore

$keytool -list -keystore myKeystore.jks 
Enter keystore password:  
Keystore type: JKS
Keystore provider: SUN

Your keystore contains 2 entries

mykey, 7 Feb 2023, PrivateKeyEntry, 
Certificate fingerprint (SHA-256): 2D:78:CF:F5:62:E7:5D:7F:6B:36:4E:D8:63:55:72:1E:DB:C7:07:34:C9:76:7B:E5:A0:CF:E9:D6:20:3C:43:16
myserverkey, 7 Feb 2023, PrivateKeyEntry, 
Certificate fingerprint (SHA-256): 87:80:F2:94:89:5C:A7:7C:8A:DE:4E:DF:6D:C4:2C:1C:42:1B:45:0E:9A:6F:0B:3E:FC:3A:F5:3A:32:0A:1F:0F

Warning:
The JKS keystore uses a proprietary format. It is recommended to migrate to PKCS12 which is an industry standard format using "keytool -importkeystore -srckeystore myKeystore.jks -destkeystore myKeystore.jks -deststoretype pkcs12".

 

Output of the alias that already exists in a keystore

$keytool -list -keystore myKeystore.jks -alias myserverkey
Enter keystore password:  
myserverkey, 7 Feb 2023, PrivateKeyEntry, 
Certificate fingerprint (SHA-256): 87:80:F2:94:89:5C:A7:7C:8A:DE:4E:DF:6D:C4:2C:1C:42:1B:45:0E:9A:6F:0B:3E:FC:3A:F5:3A:32:0A:1F:0F

Warning:
The JKS keystore uses a proprietary format. It is recommended to migrate to PKCS12 which is an industry standard format using "keytool -importkeystore -srckeystore myKeystore.jks -destkeystore myKeystore.jks -deststoretype pkcs12".

Output of the alias that does not exists in the keystore

$keytool -list -keystore myKeystore.jks -alias myserverkey123
Enter keystore password:  
keytool error: java.lang.Exception: Alias <myserverkey123> does not exist

 

 

 

Previous                                                 Next                                                 Home

Print detailed information of entries in a keystore

Using -v option, we can print detailed information of entries in a keystore.

 

Without -v

$keytool -list -keystore myKeystore.jks 
Enter keystore password:  
Keystore type: JKS
Keystore provider: SUN

Your keystore contains 2 entries

mykey, 7 Feb 2023, PrivateKeyEntry, 
Certificate fingerprint (SHA-256): 2D:78:CF:F5:62:E7:5D:7F:6B:36:4E:D8:63:55:72:1E:DB:C7:07:34:C9:76:7B:E5:A0:CF:E9:D6:20:3C:43:16
myserverkey, 7 Feb 2023, PrivateKeyEntry, 
Certificate fingerprint (SHA-256): 87:80:F2:94:89:5C:A7:7C:8A:DE:4E:DF:6D:C4:2C:1C:42:1B:45:0E:9A:6F:0B:3E:FC:3A:F5:3A:32:0A:1F:0F

Warning:
The JKS keystore uses a proprietary format. It is recommended to migrate to PKCS12 which is an industry standard format using "keytool -importkeystore -srckeystore myKeystore.jks -destkeystore myKeystore.jks -deststoretype pkcs12".

 

With -v

$keytool -v -list -keystore myKeystore.jks 
Enter keystore password:  
Keystore type: JKS
Keystore provider: SUN

Your keystore contains 2 entries

Alias name: mykey
Creation date: 7 Feb 2023
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=krishna, OU=sample.com, O=self learning java, L=Bangalore, ST=Karnataka, C=IN
Issuer: CN=krishna, OU=sample.com, O=self learning java, L=Bangalore, ST=Karnataka, C=IN
Serial number: 15cbcdef
Valid from: Tue Feb 07 10:10:39 IST 2023 until: Mon May 08 10:10:39 IST 2023
Certificate fingerprints:
	 SHA1: 59:7D:45:F0:F7:1A:E7:D8:B5:EE:16:B4:44:64:17:F4:CC:41:B2:8D
	 SHA256: 2D:78:CF:F5:62:E7:5D:7F:6B:36:4E:D8:63:55:72:1E:DB:C7:07:34:C9:76:7B:E5:A0:CF:E9:D6:20:3C:43:16
Signature algorithm name: SHA256withRSA
Subject Public Key Algorithm: 2048-bit RSA key
Version: 3

Extensions: 

#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 7C F8 E5 84 F4 EF 92 84   56 96 6A 51 D1 66 7A 45  ........V.jQ.fzE
0010: 44 51 E6 7F                                        DQ..
]
]



*******************************************
*******************************************


Alias name: myserverkey
Creation date: 7 Feb 2023
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=demo.app.com
Issuer: CN=demo.app.com
Serial number: 2b72fbe1
Valid from: Tue Feb 07 10:33:19 IST 2023 until: Mon May 08 10:33:19 IST 2023
Certificate fingerprints:
	 SHA1: 91:AD:A2:3E:42:32:5A:3A:39:CE:4C:1F:25:EC:F8:D9:9F:92:C0:DB
	 SHA256: 87:80:F2:94:89:5C:A7:7C:8A:DE:4E:DF:6D:C4:2C:1C:42:1B:45:0E:9A:6F:0B:3E:FC:3A:F5:3A:32:0A:1F:0F
Signature algorithm name: SHA256withDSA
Subject Public Key Algorithm: 2048-bit DSA key
Version: 3

Extensions: 

#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 17 BE FD 60 AD CD 97 F2   43 BA 3B DA 66 05 66 10  ...`....C.;.f.f.
0010: E8 F2 3D 62                                        ..=b
]
]



*******************************************
*******************************************



Warning:
The JKS keystore uses a proprietary format. It is recommended to migrate to PKCS12 which is an industry standard format using "keytool -importkeystore -srckeystore myKeystore.jks -destkeystore myKeystore.jks -deststoretype pkcs12".
$

 

 

 

 

Previous                                                 Next                                                 Home

How to delete an entry by alias in keystore?

 Syntax

keytool -delete -alias {entry_alias} -keystore {keystore_file}

 

Example

keytool -delete -alias java-blogspot -keystore myKeystore.jks

$ keytool -delete -alias java-blogspot -keystore myKeystore.jks
Enter keystore password:  

Warning:
The JKS keystore uses a proprietary format. It is recommended to migrate to PKCS12 which is an industry standard format using "keytool -importkeystore -srckeystore myKeystore.jks -destkeystore myKeystore.jks -deststoretype pkcs12".

 

 

 

Previous                                                 Next                                                 Home

Quick guide to java.security.KeyStore class

Java keystore provides a storage to store the keys, certificates. Following are the java supported keystore file formats.

a.   JKS

b.   JCEKS

c.    PKCS#12

d.   DKS

e.   PCKCS#11

 

File format

Store public, private keys

Store certificates

Store secret keys

JKS

Yes

Yes

No

JCEKS

Yes

Yes

Yes

PKCS#12

Yes

Yes

No

 

All the keystores (JKS, JCEKS, PKCS#12) are protected by a password. To provide further security, each private key or secret key that you are going to store in a keystore is protected by another individual password.

 

In this tutorial series, I am going to explain how to work with a keystore using java.secutiry.KeyStore class.

 

Create a keystore

public static KeyStore createEmptyKeyStore(String keyStoreType, String keyStoreFilePath, String keyStorePassword)
        throws Exception {
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);

    char[] pwdArray = keyStorePassword.toCharArray();
    keyStore.load(null, pwdArray);

    try (FileOutputStream fos = new FileOutputStream(keyStoreFilePath)) {
        keyStore.store(fos, pwdArray);
    }
    return keyStore;
}

Print the entries of keystore

public static void printEntries(KeyStore keyStore) throws KeyStoreException {
    Enumeration<String> aliases = keyStore.aliases();

    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        System.out.println(alias);
    }
}

Save symmetric key to the key store

public static void saveSymmetricKey(KeyStore keyStore, SecretKey secretKey, String secretKeyAlias,
        String secretKeyPassword) throws KeyStoreException {
    KeyStore.SecretKeyEntry secret = new KeyStore.SecretKeyEntry(secretKey);
    KeyStore.ProtectionParameter password = new KeyStore.PasswordProtection(secretKeyPassword.toCharArray());
    keyStore.setEntry(secretKeyAlias, secret, password);
}

Load existing keystore

public static KeyStore loadExistingKeystore(String keyStoreType, String keyStoreFilePath, String keyStorePassword)
        throws Exception {
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    char[] pwdArray = keyStorePassword.toCharArray();
    keyStore.load(new FileInputStream(keyStoreFilePath), pwdArray);
    return keyStore;
}

Get the certificate entry by alias

java.security.cert.Certificate certificate = keyStore.getCertificate("certificate-alias");

Get the key by alias and password

Key key = keyStor.getKey("keyAlias", "keyPassword".toCharArray());

Find the below working application.

 

KeystoreUtil.java

package com.sample.app.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.util.Enumeration;

import javax.crypto.SecretKey;

public class KeystoreUtil {

    public static KeyStore createEmptyKeyStore(String keyStoreType, String keyStoreFilePath, String keyStorePassword)
            throws Exception {
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);

        char[] pwdArray = keyStorePassword.toCharArray();
        keyStore.load(null, pwdArray);

        try (FileOutputStream fos = new FileOutputStream(keyStoreFilePath)) {
            keyStore.store(fos, pwdArray);
        }
        return keyStore;
    }

    public static void printEntries(KeyStore keyStore) throws KeyStoreException {
        Enumeration<String> aliases = keyStore.aliases();

        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            System.out.println(alias);
        }
    }

    public static void saveSymmetricKey(KeyStore keyStore, SecretKey secretKey, String secretKeyAlias,
            String secretKeyPassword) throws KeyStoreException {
        KeyStore.SecretKeyEntry secret = new KeyStore.SecretKeyEntry(secretKey);
        KeyStore.ProtectionParameter password = new KeyStore.PasswordProtection(secretKeyPassword.toCharArray());
        keyStore.setEntry(secretKeyAlias, secret, password);
    }

    public static KeyStore loadExistingKeystore(String keyStoreType, String keyStoreFilePath, String keyStorePassword)
            throws Exception {
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        char[] pwdArray = keyStorePassword.toCharArray();
        keyStore.load(new FileInputStream(keyStoreFilePath), pwdArray);
        return keyStore;
    }

}

HelloWorld.java

package com.sample.app;

import java.security.Key;
import java.security.KeyStore;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

import com.sample.app.util.KeystoreUtil;

public class HelloWorld {

    public static void main(String[] args) throws Exception {
        String keyStorePassword = "test123";
        String keyStoreType = "jceks";
        String keyStoreFilePath = "/Users/Shared/demo.jceks";
        String secretKeyAlias = "secretKey1";
        String secretKeyPassword = "test456";

        System.out.println("Creating empty key store : " + keyStoreFilePath);
        KeyStore keyStore = KeystoreUtil.createEmptyKeyStore(keyStoreType, keyStoreFilePath, keyStorePassword);

        System.out.println("Printing the elements of keystore");
        KeystoreUtil.printEntries(keyStore);

        System.out.println("\nAdding new secret key to the keystore");
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128);
        SecretKey secretKey = keyGen.generateKey();
        KeystoreUtil.saveSymmetricKey(keyStore, secretKey, secretKeyAlias, secretKeyPassword);

        System.out.println("\nPrinting the elements of keystore : " + keyStoreFilePath);
        KeystoreUtil.printEntries(keyStore);

        String existingKeyStore = "/Users/Shared/myKeystore.jks";
        KeyStore loadedkeyStore = KeystoreUtil.loadExistingKeystore("jks", existingKeyStore, "test123");
        System.out.println("\nPrinting the elements of keystore : " + existingKeyStore);
        KeystoreUtil.printEntries(keyStore);
        KeystoreUtil.printEntries(loadedkeyStore);

        System.out.println("\nPrint the certificate");
        java.security.cert.Certificate certificate = loadedkeyStore.getCertificate("java-blogspot");
        System.out.println(certificate);

        System.out.println("\nPrint key information");
        Key key = loadedkeyStore.getKey("myserverkey", "test456".toCharArray());
        System.out.println("Algorithm : " + key.getAlgorithm());
    }

}


 

Previous                                                 Next                                                 Home