Friday, 2 May 2025

How to Read Basic Authentication Credentials in Javalin?

Using Context#basicAuthCredentials() method, we can read the basic credentials that are passed with the request.

Find the below working application.

 

Step 1: Create new maven project ‘javalin-read-basic-credentials’.

 

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-read-basic-credentials</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>


		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.14.0</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.14.0</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;
import io.javalin.http.HttpStatus;
import io.javalin.security.BasicAuthCredentials;

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) -> {

			BasicAuthCredentials basicAuthcredentials = ctx.basicAuthCredentials();

			if (basicAuthcredentials == null) {
				ctx.result("Credentials missing").status(HttpStatus.BAD_REQUEST);
				return;
			}

			String username = basicAuthcredentials.getUsername();
			String password = basicAuthcredentials.getPassword();

			if (username == null || !"test".equals(username)) {
				ctx.result("INVALID CREDENTIALS").status(HttpStatus.UNAUTHORIZED);
				return;
			}

			if (password == null || !"test".equals(password)) {
				ctx.result("INVALID CREDENTIALS").status(HttpStatus.UNAUTHORIZED);
				return;
			}

			ctx.result("Good morning!!!!").status(HttpStatus.OK);
		});

		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-read-basic-credentials-1.0.0-jar-with-dependencies.jar’ file. 

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

Run the application

Execute below command to run the application.

java -jar ./target/javalin-read-basic-credentials-1.0.0-jar-with-dependencies.jar

$java -jar ./target/javalin-read-basic-credentials-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] @475ms
[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 331ms \o/

Test the api

Example 1: do not pass credentials.

curl --location --request GET 'http://localhost:8080/hello'

$curl --location --request GET 'http://localhost:8080/hello'
Credentials missing

 

Example 2: Pass wrong credentials.

curl --location --request GET 'http://localhost:8080/hello' \
--header 'Authorization: Basic ZGVtbzpkZW1v'

$curl --location --request GET 'http://localhost:8080/hello' \
> --header 'Authorization: Basic ZGVtbzpkZW1v'
INVALID CREDENTIALS

Example 3: With correct credentials.

curl --location --request GET 'http://localhost:8080/hello' \
--header 'Authorization: Basic dGVzdDp0ZXN0'

$curl --location --request GET 'http://localhost:8080/hello' \
> --header 'Authorization: Basic dGVzdDp0ZXN0'
Good morning!!!!

 You can download this application from this link.

 

Previous                                                    Next                                                    Home

How to Retrieve All Path Parameters as a Map in Javalin?

Context#pathParamMap metho read all the path parameters as a map.

Example 

Map<String, String> pathParamsMap = ctx.pathParamMap();

 

Find the below working application.

 

Step 1: Create new maven project ‘javalin-read-path-params-as-map’.

 

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-read-path-params-as-map</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>


		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.14.0</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.14.0</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 JsonUtil class.

 

JsonUtil.java

package com.sample.app.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {

	public static String getJson(Object obj) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(obj);
	}

}

Step 4: Define main application class.

 

App.java

package com.sample.app;

import java.util.Map;

import com.sample.app.util.JsonUtil;

import io.javalin.Javalin;
import io.javalin.http.HttpStatus;

public class App {

	public static void main(String[] args) {

		Javalin javalin = Javalin.create();

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

		javalin.post("/register-me/{name}/{age}", (ctx) -> {

			Map<String, String> pathParamsMap = ctx.pathParamMap();

			String json = JsonUtil.getJson(pathParamsMap);

			ctx.result(json).status(HttpStatus.CREATED);
		});

		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-read-path-params-as-map-1.0.0-jar-with-dependencies.jar’ file. 

$ls ./target/
archive-tmp
classes
generated-sources
generated-test-sources
javalin-read-path-params-as-map-1.0.0-jar-with-dependencies.jar
javalin-read-path-params-as-map-1.0.0.jar
maven-archiver
maven-status
test-classes

Run the application

Execute below command to run the application.

java -jar ./target/javalin-read-path-params-as-map-1.0.0-jar-with-dependencies.jar

$java -jar ./target/javalin-read-path-params-as-map-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.@3911c2a7{/,null,AVAILABLE}
[main] INFO org.eclipse.jetty.server.AbstractConnector - Started ServerConnector@5bcea91b{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
[main] INFO org.eclipse.jetty.server.Server - Started Server@42607a4f{STARTING}[11.0.13,sto=0] @403ms
[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 282ms \o/

 Test the api

Execute below command to test the api.

 

curl --location --request POST 'http://localhost:8080/register-me/krishna/18'

$curl --location --request POST 'http://localhost:8080/register-me/krishna/18'
{"name":"krishna","age":"18"}

 You can download the application from this link.

 

Previous                                                    Next                                                    Home

Setting up Simple Application to experiment with prompts

Step 1: Install Required Libraries: First, you'll need to install the Hugging Face transformers library and torch for PyTorch support. 

pip install transformers torch

Step 2: Load a Pre-trained Model: You can use Hugging Face's bloom-1b7 model, a popular model to generate human-like text across a wide range of languages. You can use it for creative writing, code generation, and more..

 

Here's a basic script to experiment with it.

 

promptSetup.py

import os
from transformers import BloomForCausalLM, BloomTokenizerFast

# Load the BLOOM model and tokenizer
model_name = "bigscience/bloom-1b7"
model = BloomForCausalLM.from_pretrained(model_name)
tokenizer = BloomTokenizerFast.from_pretrained(model_name)

def generate_response(prompt):
    # Tokenize the prompt
    inputs = tokenizer(prompt, return_tensors="pt")

    # Ensure input_ids are of type LongTensor (for embedding layer)
    input_ids = inputs["input_ids"].long()  # Explicitly cast to LongTensor

    # Generate a response with sampling enabled
    outputs = model.generate(input_ids, 
                             max_length=100, 
                             num_return_sequences=1, 
                             temperature=0.7,   # Temperature for sampling
                             do_sample=True)    # Enable sampling mode
    
    # Decode and return the result
    return tokenizer.decode(outputs[0], skip_special_tokens=True)

# Function to format the conversation output
def format_conversation(response):
    separator = "\n" + "="*50 + "\n"  # You can adjust the separator length
    formatted_conversation = f"BLOOM: {response}\n"
    return formatted_conversation

# Interactive loop
print("Welcome to BLOOM-powered conversation!\n" + "="*50 + "\n")

while True:
    user_input = input("You: ")
    if user_input.lower() == "exit":
        print("\nEnding the conversation. Goodbye!")
        break
    response = generate_response(user_input)
    print(format_conversation(response))
    print("\n" + "-"*50 + "\n")  # Adding spacing between conversations

Execute following command to experiment with the Application.

python3 promptSetup.py

 

Prompt 1: For the input “Once Upon A Time”

You: Once Upon A Time

==================================================
BLOOM: Once Upon A Time In Hollywood (1968) - The first time I've seen a movie in my life, which I will never forget. The movie is a good one, but I can't even remember what it was about. I just remember the music. I just remembered the title and the poster. The film is called The Girl from the Sea, which I thought was a good name for the movie. I got in the car, and I was going to go to this movie. I called the theater

 

Prompt 2: For the input “SQL Stands for Structured”

You: SQL Stands for Structured

==================================================
BLOOM: SQL Stands for Structured Query Language. It is a set of SQL statements. SQL is used to access database. SQL is part of Oracle Database. SQL is a language for creating a query. SQL is a combination of the words Structured Query Language and Language. SQL is used to create queries. SQL is used to connect the database and database server. It is a language used to do database operations. The SQL statement is very powerful. It can create a query and connect to the database.

Prompt 3: For the Input “Tell Me a Joke in English”

You: Tell Me a Joke in English

==================================================
BLOOM: Tell Me a Joke in English (I don't know how to write that in English, so I don't know if that is a joke)
I am a former teacher. I am also a retired teacher. I was a teacher because I wanted to be a teacher. I was a retired teacher because I wanted to be a teacher again. I am also a former teacher because I wanted to be a teacher again.
I would like to thank you for your time and for your comments. I have been thinking

 

Previous                                                    Next                                                    Home