Tuesday, 20 June 2023

Micronaut: Map multiple uris to a controller method

All the Micronaut routing annotations (@Delete, @Get, @Head, @Options, @Patch, @Put, @Post, @Trace) support multiple URI templates.

 

Example

@Get(uris = { "/{employeeId}", "/by-id/{employeeId}" })
public Employee byId(@NonNull @PathVariable(name = "employeeId") final Integer empId) {
	return employeeService.byId(empId);
}

Find the below working application.

 

Step 1: Create new maven project ‘micronaut-rest-multiple-uris’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>micronaut-rest-multiple-uris</artifactId>
	<version>0.1</version>
	<packaging>jar</packaging>

	<parent>
		<groupId>io.micronaut</groupId>
		<artifactId>micronaut-parent</artifactId>
		<version>3.7.4</version>
	</parent>

	<properties>
		<packaging>jar</packaging>
		<jdk.version>11</jdk.version>
		<release.version>11</release.version>
		<micronaut.version>3.7.3</micronaut.version>
		<micronaut.runtime>netty</micronaut.runtime>
		<exec.mainClass>com.sample.app.App</exec.mainClass>
	</properties>

	<repositories>
		<repository>
			<id>central</id>
			<url>https://repo.maven.apache.org/maven2</url>
		</repository>
	</repositories>

	<dependencies>
		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-inject</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-validation</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-http-client</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-http-server-netty</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-jackson-databind</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>jakarta.annotation</groupId>
			<artifactId>jakarta.annotation-api</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>io.micronaut.test</groupId>
			<artifactId>micronaut-test-junit5</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-api</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-engine</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>io.micronaut.build</groupId>
				<artifactId>micronaut-maven-plugin</artifactId>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<!-- Uncomment to enable incremental compilation -->
					<!-- <useIncrementalCompilation>false</useIncrementalCompilation> -->

					<annotationProcessorPaths
						combine.children="append">
						<path>
							<groupId>io.micronaut</groupId>
							<artifactId>micronaut-http-validation</artifactId>
							<version>${micronaut.version}</version>
						</path>
					</annotationProcessorPaths>

				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

Step 3: Define Employee model class.

 

Employee.java

package com.sample.app.model;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Positive;

import io.micronaut.core.annotation.NonNull;

public class Employee {

	@NonNull
	@Positive
	private Integer id;

	@NotBlank
	private String name;

	@NonNull
	@Positive
	private Integer age;

	public Employee() {
	}

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

	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;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", age=" + age + "]";
	}

}

Step 4: Define EmployeeService class.

 

EmployeeService.java

package com.sample.app.service;

import java.util.ArrayList;
import java.util.List;

import com.sample.app.model.Employee;

import jakarta.inject.Singleton;

@Singleton
public class EmployeeService {
	private static final List<Employee> emps = new ArrayList<>();
	private static final Employee EMP_NOT_FOUND = new Employee();

	private static int counter = 4;

	static {
		Employee emp1 = new Employee(1, "Sunil", 23);
		Employee emp2 = new Employee(2, "Shetty", 31);
		Employee emp3 = new Employee(3, "Ram", 43);
		Employee emp4 = new Employee(4, "Akansha", 21);

		emps.add(emp1);
		emps.add(emp2);
		emps.add(emp3);
		emps.add(emp4);

	}

	public List<Employee> all() {
		return emps;
	}

	public Employee add(final Employee emp) {
		emp.setId(counter);
		counter++;

		emps.add(emp);
		return emp;
	}

	public Employee byId(Integer id) {
		for (Employee emp : all()) {
			if (id.equals(emp.getId())) {
				return emp;
			}
		}
		return EMP_NOT_FOUND;
	}
}

Step 5: Define EmployeeController class.

 

EmployeeController.java

package com.sample.app.controller;

import com.sample.app.model.Employee;
import com.sample.app.service.EmployeeService;

import io.micronaut.core.annotation.NonNull;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.PathVariable;
import jakarta.inject.Inject;

@Controller("/employees")
public class EmployeeController {

	@Inject
	private EmployeeService employeeService;

	@Get(uris = { "/{employeeId}", "/by-id/{employeeId}" })
	public Employee byId(@NonNull @PathVariable(name = "employeeId") final Integer empId) {
		return employeeService.byId(empId);
	}
}

Step 6: Define main application class.

 

App.java

package com.sample.app;

import io.micronaut.runtime.Micronaut;

public class App {

	public static void main(String[] args) {
		Micronaut.run(App.class);
		
		// Use this if you want the beans to be initialized eagerly
		/*Micronaut.build(args)
        .eagerInitSingletons(true) 
        .mainClass(App.class)
        .start();*/
	}
}

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-rest-multiple-uris-0.1.jar’ in project target folder.

$ls ./target/
classes
generated-sources
generated-test-sources
maven-archiver
maven-status
micronaut-rest-multiple-uris-0.1.jar
original-micronaut-rest-multiple-uris-0.1.jar
surefire-reports
test-classes

Execute below command to run the application.

java -jar ./target/micronaut-rest-multiple-uris-0.1.jar

Open the url ‘http://localhost:8080/employees/by-id/1’ in browser, you will see below screen.



Open the url ‘http://localhost:8080/employees/1’ in browser, you will see below screen.



You can download this application from this link.


 

Previous                                                    Next                                                    Home

Supported HTTP Methods or verbs in Micronaut

 

Below table summarizes the HTTP methods supported in Micronaut.

 

HTTP Method

Annotation

DELETE

@Delete

GET

@Get

HEAD

@Head

OPTIONS

@Options

PATCH

@Patch

PUT

@Put

POST

@Post

TRACE

@Trace

 

Previous                                                    Next                                                    Home

PlantUML: Add connecting notes on several entities in class diagram

Define a note using note keyword.

note "Human body parts" as HBP

 

Connect this note to other objects using .. symbol.

Human .. HBP
HBP .. Brain
HBP .. Lungs
HBP .. Liver
HBP .. Heart
HBP .. Stomach
HBP .. Kidney
HBP .. Bladder

 

connectingNotes.txt

@startuml

title "Class Composition"

class Human

Class Brain
class Lungs
class Liver
class Heart
class Stomach
class Kidney
class Bladder

class Frontal
class Parietal
class Temporal
class Occipital

Human *-- Brain
Human *-- Lungs
Human *-- Liver
Human *-- Heart
Human *-- Stomach
Human *-- Kidney
Human *-- Bladder

Brain *-- Frontal
Brain *-- Parietal
Brain *-- Temporal
Brain *-- Occipital

note "Human body parts" as HBP
Human .. HBP
HBP .. Brain
HBP .. Lungs
HBP .. Liver
HBP .. Heart
HBP .. Stomach
HBP .. Kidney
HBP .. Bladder

@enduml

 

Above snippet generate below diagram.

 


 

 

Previous                                                    Next                                                    Home

Monday, 19 June 2023

PlantUML: Add notes to the entities in a class diagram

Notes to the entities is defined using below keywords.

a.   note left of

b.   note right of

c.    note top of

d.   note bottom of

 

Example

note top of List : An ordered collection

note left of AbstractList : implements List interface

note right of ArrayList : Resizable-array implementation \n of the List interface

note bottom of Serializable : Serializability of a class is enabled \n by the class implementing this

 

 

notes.txt

@startuml

interface List{
	
}

abstract class AbstractList implements List{
	
}

interface Serializable{
	
}

class ArrayList extends AbstractList implements Serializable{
	
}

note top of List : An ordered collection 
note left of AbstractList : implements List interface
note right of ArrayList : Resizable-array implementation \n of the List interface
note bottom of Serializable : Serializability of a class is enabled \n by the class implementing this

@enduml

Above snippet generate below diagram.



You can define notes on last defined class using below keywords.

 

a.   note left

b.    note right

c.    note top

d.   note bottom

 

notes2.txt

 

@startuml

interface List{
	
}
note top: An ordered collection 


abstract class AbstractList{
	
}
note left: implements List interface


interface Serializable{
	
}
note bottom : Serializability of a class is enabled \n by the class implementing this


class ArrayList{
	
}
note right: Resizable-array implementation \n of the List interface

List <|.. AbstractList
AbstractList <|-- ArrayList
Serializable <|.. ArrayList

@enduml

 

Above snippet generate below diagram.


 

 

Previous                                                    Next                                                    Home

PlantUML: Add stereotypes to the class

Stereo types are defined with << and  >>

 

stereotypes.txt

@startuml

enum Gender << enum >> {
	MALE
	FEMALE
}

class OrderService << highly_available >> {
	
}

class WebClient <<generate_stub>>{
	
}

class Person <<Metaclass>>{
	
}

@enduml

Above snippet generate below diagram.



 

 

Previous                                                    Next                                                    Home

Sunday, 18 June 2023

PlantUML: Use separators to define custom ordering of fields and methods

By default, methods and fields are automatically regrouped by PlantUML.

 

defaultOrdering.txt

@startuml

class Employee{
	' public static fields
	+ {static} AtomicInteger TOTAL_EMPLOYEE_COUNT

	'private instance fields
	- Integer id
	- String name
	- Integer age

	' public static methods
	+ {static} List<Employee> list(Employee... emps)

	' public instance methods
	+ Integer getId()
	+ String getName()
	+ Integer getAge()
	+ String aboutMe()
	+ void setId(Integer id)
	+ void setName(String name)
	+ void setAge(Integer age)

	' private instance methods
	- String lowerName()
}

@enduml

 

Above snippet generate below diagram.

 

 


We can use separators to define our own way of ordering fields and method.

 

Following separators are supported.

 

a.   --

b.   ..

c.    ==

d.   __

 

customordering.txt

@startuml

class Employee{
	-- public static fields --
	+ {static} AtomicInteger TOTAL_EMPLOYEE_COUNT

	.. private instance fields ..
	- Integer id
	- String name
	- Integer age

	== public static methods ==
	+ {static} List<Employee> list(Employee... emps)

	__ public instance getter methods __
	+ Integer getId()
	+ String getName()
	+ Integer getAge()

	__ public instance setter methods __
	+ void setId(Integer id)
	+ void setName(String name)
	+ void setAge(Integer age)

	__ public utility methods __
	+ String aboutMe()

	.. private instance methods ..
	- String lowerName()
}

@enduml

 

Above snippet generate below diagram.


 

Previous                                                    Next                                                    Home