Wednesday, 5 June 2024

Building a GET API with Javalin: A Step-by-Step Guide

Using Javalin.get() method, we can model a GET api.

Signature

public Javalin get(@NotNull String path, @NotNull Handler handler)

Adds a GET request handler for the specified path to the instance.

 

public Javalin get(@NotNull String path, @NotNull Handler handler, @NotNull RouteRole... roles)

Adds a GET request handler with the given roles for the specified path to the instance. Requires an access manager to be set on the instance.

 

Example

javalin.get("/hello", (ctx) -> {
	ctx.result("Hello World");
});

 

Follow below step-by-step procedure to build complete working application.

 

Step 1: Create new maven project ‘javalin-get-api’.

 

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>javalin-get-api</artifactId>
	<version>1.0.0</version>

	<properties>
		<packaging>jar</packaging>
		<jdk.version>17</jdk.version>
		<release.version>17</release.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>io.javalin</groupId>
			<artifactId>javalin</artifactId>
			<version>5.3.2</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-simple</artifactId>
			<version>2.0.3</version>
		</dependency>

	</dependencies>

	<build>
		<plugins>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.10.1</version>
				<configuration>
					<source>17</source>
					<target>17</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>2.6</version>
				<configuration>
					<descriptorRefs>
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
					<archive>
						<manifest>
							<addClasspath>true</addClasspath>
							<mainClass>com.sample.app.App</mainClass>
						</manifest>
					</archive>
				</configuration>
				<executions>
					<execution>
						<id>assemble-all</id>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>

 

Step 3: Define main application class.

 

App.java

 

package com.sample.app;

import io.javalin.Javalin;

public class App {
	public static void main(String[] args) {
		Javalin javalin = Javalin.create();

		javalin.get("/", (ctx) -> {
			ctx.result("Welcome to Javalin programming!!!!");
		});
		
		javalin.get("/hello", (ctx) -> {
			ctx.result("Hello World");
		});

		javalin.start(8080);
	}
}

Total project structure looks like below.


Build the project

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

 

Upon successful command execution, you can see a ‘javalin-get-api-1.0.0-jar-with-dependencies.jar’ file.

$ls ./target/
archive-tmp
classes
generated-sources
generated-test-sources
javalin-get-api-1.0.0-jar-with-dependencies.jar
javalin-get-api-1.0.0.jar
maven-archiver
maven-status
test-classes

Run the application

Execute below command to run the application.

java -jar ./target/javalin-get-api-1.0.0-jar-with-dependencies.jar

$java -jar ./target/javalin-get-api-1.0.0-jar-with-dependencies.jar
[main] INFO io.javalin.Javalin - Starting Javalin ...
[main] INFO org.eclipse.jetty.server.Server - jetty-11.0.13; built: 2022-12-07T20:47:15.149Z; git: a04bd1ccf844cf9bebc12129335d7493111cbff6; jvm 17.0.5+9-LTS-191
[main] INFO org.eclipse.jetty.server.session.DefaultSessionIdManager - Session workerName=node0
[main] INFO org.eclipse.jetty.server.handler.ContextHandler - Started i.j.j.@30ee2816{/,null,AVAILABLE}
[main] INFO org.eclipse.jetty.server.AbstractConnector - Started ServerConnector@26a7b76d{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
[main] INFO org.eclipse.jetty.server.Server - Started Server@1fc2b765{STARTING}[11.0.13,sto=0] @640ms
[main] INFO io.javalin.Javalin - 
       __                  ___          ______
      / /___ __   ______ _/ (_)___     / ____/
 __  / / __ `/ | / / __ `/ / / __ \   /___ \
/ /_/ / /_/ /| |/ / /_/ / / / / / /  ____/ /
\____/\__,_/ |___/\__,_/_/_/_/ /_/  /_____/

       https://javalin.io/documentation

[main] INFO io.javalin.Javalin - Listening on http://localhost:8080/
[main] INFO io.javalin.Javalin - You are running Javalin 5.3.2 (released January 22, 2023).
[main] INFO io.javalin.Javalin - Javalin started in 335ms \o/

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




Open the url ‘http://localhost:8080/hello’ in browser, you will see below kind of screen.

 


You can download this application from this link.


 

Previous                                                    Next                                                    Home

Saturday, 1 June 2024

Getting Started with Javalin: Creating a Hello World Application

Prerequisite

Java17

 

Step 1: Create new maven project ‘javalin-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>javalin-hello-world</artifactId>
	<version>1.0.0</version>

	<properties>
		<packaging>jar</packaging>
		<jdk.version>17</jdk.version>
		<release.version>17</release.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>io.javalin</groupId>
			<artifactId>javalin</artifactId>
			<version>5.3.2</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-simple</artifactId>
			<version>2.0.3</version>
		</dependency>

	</dependencies>

	<build>
		<plugins>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.10.1</version>
				<configuration>
					<source>17</source>
					<target>17</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>2.6</version>
				<configuration>
					<descriptorRefs>
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
					<archive>
						<manifest>
							<addClasspath>true</addClasspath>
							<mainClass>com.sample.app.App</mainClass>
						</manifest>
					</archive>
				</configuration>
				<executions>
					<execution>
						<id>assemble-all</id>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>

Step 3: Define main application class.

 

App.java

package com.sample.app;

import io.javalin.Javalin;

public class App {
	public static void main(String[] args) {
		Javalin app = Javalin.create(/* config */)
				.get("/", ctx -> ctx.result("Hello World"))
				.start(8080);
	}
}

Total project structure looks like below.


 

Build the project

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

 

Upon successful command execution, you can see a ‘javalin-hello-world-1.0.0-jar-with-dependencies.jar’ file.

$ls ./target/
archive-tmp
classes
generated-sources
generated-test-sources
javalin-hello-world-1.0.0-jar-with-dependencies.jar
javalin-hello-world-1.0.0.jar
maven-archiver
maven-status
test-classes

Run the application

Execute below command to run the application.

$java -jar ./target/javalin-hello-world-1.0.0-jar-with-dependencies.jar 
[main] INFO io.javalin.Javalin - Starting Javalin ...
[main] INFO org.eclipse.jetty.server.Server - jetty-11.0.13; built: 2022-12-07T20:47:15.149Z; git: a04bd1ccf844cf9bebc12129335d7493111cbff6; jvm 17.0.5+9-LTS-191
[main] INFO org.eclipse.jetty.server.session.DefaultSessionIdManager - Session workerName=node0
[main] INFO org.eclipse.jetty.server.handler.ContextHandler - Started i.j.j.@29626d54{/,null,AVAILABLE}
[main] INFO org.eclipse.jetty.server.AbstractConnector - Started ServerConnector@1a8a8f7c{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
[main] INFO org.eclipse.jetty.server.Server - Started Server@b7dd107{STARTING}[11.0.13,sto=0] @393ms
[main] INFO io.javalin.Javalin - 
       __                  ___          ______
      / /___ __   ______ _/ (_)___     / ____/
 __  / / __ `/ | / / __ `/ / / __ \   /___ \
/ /_/ / /_/ /| |/ / /_/ / / / / / /  ____/ /
\____/\__,_/ |___/\__,_/_/_/_/ /_/  /_____/

       https://javalin.io/documentation

[main] INFO io.javalin.Javalin - Listening on http://localhost:8080/
[main] INFO io.javalin.Javalin - You are running Javalin 5.3.2 (released January 22, 2023).
[main] INFO io.javalin.Javalin - Javalin started in 268ms \o/

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


You can download this application from this link.


  

Previous                                                    Next                                                    Home

Javalin tutorial

Javalin is a lightweight web framework for Java and Kotlin, designed to be simple and developer-friendly. It is often likened to frameworks like Express.js in the JavaScript ecosystem because of its minimalist and straightforward approach. Here are some key features and characteristics of Javalin:

 

a.   Ease of Use: Javalin offers a very straightforward API, making it easy to set up and start developing web applications quickly.

b.   Java and Kotlin Support: Although it is a Java library, Javalin is designed with Kotlin in mind, providing first-class support for Kotlin features.

c.    Lightweight: Javalin is designed to be lightweight, avoiding unnecessary features and focusing on speed and efficiency.

d.   Flexible: Despite its simplicity, Javalin is versatile enough to support a wide range of web applications, from small REST APIs to full-scale web applications.

      Javalin: Hello world application
      Javalin: GET API example
      Javalin: post api example
      Javalin: Read request body as string
      Javalin: read request body as array of bytes
      Javalin: read request body as input stream
      Javalin: Map request body to a java object
      Javalin: Map request body stream to an object
      Javalin: Validate request payload
      Javalin: File upload example
      Javalin: Read multiple uploaded files with same name
      Javalin: read uploaded files as a list
      Javalin: read uploaded files as a map
      Javalin: read a form parameter by name
      Javalin: validate form parameters
      Javalin: Get all the form parameters mapped to a name
      Using Javalin to Retrieve Form Parameters as a Map
      Javalin: Get the value mapped to this path parameter
      Javalin: Validate path parameter
      How to Retrieve All Path Parameters as a Map in Javalin?
      How to Read Basic Authentication Credentials in Javalin?
      Setting and Retrieving request attributes in Javalin
Previous                                                    Next                                                    Home

Mapping Result Sets to Lists with DBUtils' BeanListHandler

In this post, I am going to explain how to map result set to a list of objects.

 

To demonstrate the example, I am using below employee table.

mysql> describe employee;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int         | YES  |     | NULL    |       |
| name  | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.18 sec)

Let’s define a POJO, where the field names are matched to column names of employee table.

 

public class Employee {

  private Integer id;
  private String name;
}

Define an instance of BeanListHandler. BeanListHandler converts a ResultSet into a List of beans

 

private static ResultSetHandler<List<Employee>> empHandler = new BeanListHandler<Employee>(Employee.class);

 

Execute the query using the empHandler defined above.

List<Employee> emps = queryRunner.query(connection, query, empHandler);

 

Find the below working application.

 

Employee.java

package com.sample.app.model;

public class Employee {

  private Integer id;
  private String name;

  public Employee() {
  }

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

  public Integer getId() {
    return id;
  }

  public String getName() {
    return name;
  }

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

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

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

}

MapResultToPojoDemo.java

package com.sample.app;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.sample.app.model.Employee;

public class MapResultToPojoDemo {

  private static ResultSetHandler<List<Employee>> empHandler = new BeanListHandler<Employee>(Employee.class);

  public static void main(String[] args) {
    // Database connection parameters
    String url = "jdbc:mysql://localhost:3306/sample";
    String username = "root";
    String password = "tiger";

    // Create a QueryRunner
    QueryRunner queryRunner = new QueryRunner();

    try (Connection connection = DriverManager.getConnection(url, username, password)) {

      // Define a SQL query
      String query = "SELECT * FROM employee";

      // Execute the query and retrieve the result
      List<Employee> emps = queryRunner.query(connection, query, empHandler);

      emps.forEach(System.out::println);

    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
}

Output

Employee [id=1, name=Hari Krishna]
Employee [id=3, name=Sudhir]

Previous                                                    Next                                                    Home

Enhancing Database Efficiency with Asynchronous Queries Using DBUtils

To handle long running operations, we can consider utilizing the AsyncQueryRunner for executing tasks asynchronously. The AsyncQueryRunner class has the same methods as the QueryRunner calls; however, the methods return a Callable.

Define AsyncQueryRunner.
ExecutorService executorService = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
AsyncQueryRunner queryRunner = new AsyncQueryRunner(executorService);

Execute a query and get the result as a Future.

Future<List<Object[]>> resultFuture = queryRunner.query(connection, query, handler); 

Find the below working application.

 

RunQueriesAsynchronously.java

package com.sample.app;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

import org.apache.commons.dbutils.AsyncQueryRunner;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class RunQueriesAsynchronously {

  private static ResultSetHandler<List<Object[]>> handler = new ResultSetHandler<List<Object[]>>() {

    public List<Object[]> handle(ResultSet rs) throws SQLException {
      // Initialize the list to hold rows
      List<Object[]> rows = new ArrayList<>();

      // Get the metadata of the result set
      ResultSetMetaData meta = rs.getMetaData();
      int columnCount = meta.getColumnCount();

      // Iterate through the result set
      while (rs.next()) {
        // Create an array to hold column values for the current row
        Object[] result = new Object[columnCount];

        // Populate the array with column values
        for (int i = 0; i < columnCount; i++) {
          result[i] = rs.getObject(i + 1);
        }

        // Add the row to the list
        rows.add(result);
      }

      // Return the list of rows
      return rows;
    }
  };

  public static void main(String[] args) throws InterruptedException, ExecutionException {
    // Database connection parameters
    String url = "jdbc:mysql://localhost:3306/sample";
    String username = "root";
    String password = "tiger";

    // Create a AsyncQueryRunner
    ExecutorService executorService = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS,
        new LinkedBlockingQueue<Runnable>());
    AsyncQueryRunner queryRunner = new AsyncQueryRunner(executorService);

    try (Connection connection = DriverManager.getConnection(url, username, password)) {

      // Define a SQL query
      String query = "SELECT * FROM employee";

      // Execute the query and retrieve the result
      Future<List<Object[]>> resultFuture = queryRunner.query(connection, query, handler);

      List<Object[]> result = resultFuture.get();

      for (Object[] row : result) {
        for (Object column : row) {
          System.out.print(column + " ");
        }
        System.out.println();
      }

    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
}

Output

1 Hari Krishna 
3 Sudhir 

 

Previous                                                    Next                                                    Home