Thursday, 1 May 2025

Using Javalin to Retrieve Form Parameters as a Map

Context#formParamMap() method read all the form parameters as a map.

Example 

Map<String, List<String>> formParamsMap = ctx.formParamMap();

Find the below working application.

 

Step 1: Create new maven project ‘javalin-read-form-params-as-a-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-form-params-as-a-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 java.io.IOException;

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

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

	public static <T> T unmarshal(Class<T> clazz, String json)
			throws JsonParseException, JsonMappingException, IOException {
		ObjectMapper mapper = new ObjectMapper();
		return (T) mapper.readValue(json, clazz);
	}
}

 

Step 4: Define main application class.

 

App.java

 

package com.sample.app;

import java.util.List;
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("/form-params-demo", (ctx) -> {
			Map<String, List<String>> formParamsMap = ctx.formParamMap();

			ctx.result(JsonUtil.marshal(formParamsMap)).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-form-params-as-a-map-1.0.0-jar-with-dependencies.jar’ file. 

$ls ./target/
archive-tmp
classes
generated-sources
generated-test-sources
javalin-read-form-params-as-a-map-1.0.0-jar-with-dependencies.jar
javalin-read-form-params-as-a-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-form-params-as-a-map-1.0.0-jar-with-dependencies.jar

$java -jar ./target/javalin-read-form-params-as-a-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.@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] @397ms
[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 265ms \o/

Test the api

Execute below command to test the api.

curl --location --request POST 'http://localhost:8080/form-params-demo' \
--form 'hobbies="chess"' \
--form 'hobbies="cricket"' \
--form 'name="Krishna"' \
--form 'age="34"'

$curl --location --request POST 'http://localhost:8080/form-params-demo' \
> --form 'hobbies="chess"' \
> --form 'hobbies="cricket"' \
> --form 'name="Krishna"' \
> --form 'age="34"'
{"hobbies":["chess","cricket"],"name":["Krishna"],"age":["34"]}

 You can download this application from this link.

 

Previous                                                    Next                                                    Home

Understanding Potential Harms of Generative AI

 

Generative AI is a revolutionized technology, offering immense potential to transform industries, enhance productivity, and spark creativity. However, as with any powerful tool, it comes with its own set of risks and challenges.

 

1. Hallucinations or Fabrications

GenAI systems can create content that looks believable but is completely made up or doesn’t make sense.

·      Nonsensical Responses: The model may produce incoherent text due to insufficient context or ambiguous prompts.

·      Factual Errors: Models can confidently provide incorrect information due to a lack of access to accurate or updated data.

·      Contradictions in Responses: GenAI can contradict itself, especially in lengthy conversations.

·      Irrelevant Information: irrelevant or tangential answers may arise if the input lacks clarity or if the AI "misunderstands."

 

References

https://scet.berkeley.edu/why-hallucinations-matter-misinformation-brand-safety-and-cybersecurity-in-the-age-ofgenerative-ai/

 

2. LLM Can Produce Harmful Content

Large language models (LLMs) may unintentionally generate harmful content if not properly guided or filtered.

·      Instructions Encouraging Self-Harm: This is a recognized risk and why safety mitigations are necessary.

·      Hateful or Demeaning Content: Biases in training data can lead to harmful outputs.

·      Guiding or Planning Violent Acts: There is potential for misuse if safety measures fail.

·      Instructions for Illegal Content/Acts: AI models may inadvertently provide guidance on illicit activities if prompted inappropriately.

·      Sexually Explicit Content: This is another critical area that requires content moderation.

 

References

https://towardsdatascience.com/unconstrained-chatbots-condone-self-harm-e962509be2fa

 

3. Lack of Fairness

Fairness and bias mitigation are crucial in GenAI. Let’s analyze your point:

Fairness Definition (Free from Bias/Discrimination): Fairness in AI ensures equitable outcomes, particularly when generating content or making predictions. Biases can manifest in text or image generation if training data reflects societal prejudices.

 

Mitigation Process

Developers incorporate techniques like reinforcement learning with human feedback (RLHF) and content moderation to minimize these risks.

 

Ongoing Challenges

Ensuring fairness and preventing harmful content is an ongoing challenge, as no dataset is entirely free from bias or harmful content.

Previous                                                    Next                                                    Home

Key Characteristics of Foundation Models

 

Foundation models possess several key characteristics that make them distinct and powerful in modern artificial intelligence. Here are the main characteristics:

 

1. Pretrained: Foundation models are trained on vast datasets in advance, using self-supervised learning or other techniques. The training involves general-purpose tasks without being fine-tuned for specific applications initially.

 

2. Adaptable (Generalizable): These models can adapt to a wide variety of tasks and domains with little or no additional training, often requiring just a few examples (few-shot learning) or fine-tuning.

 

3. Large: Foundation models are extremely large in terms of:

·      Parameters: Often billions or even trillions of trainable parameters.

·      Data Size: Trained on diverse and massive datasets (text, images, audio, etc.) sourced from the internet or other repositories.

 

4. Multimodal Capabilities: Many foundation models can process and generate data across multiple modalities, such as text, images, audio, video, and even structured data.

Examples:

·      GPT-4 Vision (text and images).

·      DALL·E (text-to-image generation).

·      Whisper (audio transcription and translation).

 

5. Self-Supervised Learning: Foundation models are trained using self-supervised techniques, where the model learns from unlabelled data by predicting parts of the data (e.g., masked words in text or missing pixels in images)

 

6. Contextual Understanding: They excel at understanding and reasoning based on the context of the input.

 

Examples:

·      Language models can maintain a conversation's context over multiple turns.

·      Multimodal models can understand the relationship between text and images.

 

7. Zero-Shot, Few-Shot, and Fine-Tuning Capabilities

·       Zero-Shot Learning: Perform tasks they haven’t been explicitly trained for, using only general patterns learned during pretraining.

·       Few-Shot Learning: Require only a few examples to learn and perform new tasks.

·       Fine-Tuning: Can be specialized for specific domains or tasks with additional, smaller-scale training.

 

8. Probabilistic and Generative: Foundation models are generative by nature, meaning they can create new data, such as text, images, or code, based on patterns they’ve learned.

 

Examples:

·      Text generation (e.g., story writing, summarization).

·      Image synthesis (e.g., DALL·E, MidJourney).

 

9. Domain-Agnostic Training: Initial training is not specific to any single domain, making them useful across diverse fields. They can later be fine-tuned for domain-specific tasks (e.g., medical diagnosis, legal text summarization).

 

10. Ethical Challenges and Risks: While powerful, foundation models carry risks due to their training on internet-scale data.

 

Examples:

·      Bias: Can exhibit harmful stereotypes present in the training data.

·      Misinformation: Risk of generating incorrect or misleading content.

·      Ethical Concerns: Misuse for disinformation or malicious applications.

 

11. Task-Independent Architecture: Foundation models are built on architectures like Transformers, which are not tied to a single type of data or task.

 

Example: Transformers can handle sequence data like text, images, and time series with appropriate adaptations.

 

12. Few or No Domain-Specific Assumptions: They make minimal assumptions about the structure of the input data, allowing them to handle diverse and complex data types.

 

Example: A foundation model trained on general text can adapt to medical or legal text without retraining the base model.

 

13. Scalability: Training on more data or with more parameters generally improves performance, making these models highly scalable.

 

Previous                                                    Next                                                    Home

Exploring the Diverse Categories of Foundation Models: From Text to Multimodal AI

 

Foundation models can be categorized based on the data modality they are trained on or the tasks they are designed to perform. These categories reflect their specialization, such as processing text, images, audio, or multimodal data. Below is a breakdown of the different categories.

 

Data modality refers to the type or form of data that a model processes, understands, or generates. Each modality represents a distinct kind of information with its own structure and characteristics. For example, text, images, audio, and video are different modalities of data.

 

1. Large Language Models (LLMs)

·       Modality: Text

·       Description: Models specialized in understanding and generating human language. These are trained on massive amounts of text data.

·       Capabilities:

o   Text generation, summarization, translation

o   Question answering, sentiment analysis

o   Chatbots and virtual assistants

·       Examples: GPT-4, PaLM, LLaMA, BLOOM, T5

 

2. Vision Models

·       Modality: Images/Videos

·       Description: Models trained to interpret visual data, such as images or videos.

·       Capabilities:

o   Image classification, object detection

o   Image generation, segmentation

o   Video analysis, facial recognition

·       Examples: DALL·E (image generation), Vision Transformer (ViT), YOLO (object detection), Stable Diffusion, DeepMind's Perceiver IO

 

3. Audio Models

·       Modality: Audio/Speech

·       Description: Models trained to process sound, including speech and environmental audio.

·       Capabilities:

o   Speech recognition, text-to-speech (TTS)

o   Speaker identification, audio classification

o   Music generation, sound synthesis

·       Examples: Whisper (speech-to-text), Wav2Vec (speech recognition), Jukebox (music generation)

 

4. Multimodal Models

·       Modality: Text + Images + Audio + Video (combined)

·       Description: Models trained on multiple types of data, enabling them to understand and generate outputs across modalities.

·       Capabilities:

o   Image captioning, visual question answering (VQA)

o   Text-to-image generation, text-to-video generation

o   Cross-modal search (e.g., search images by text)

·       Examples: CLIP (text-image alignment), GPT-4 Vision (text and images), Flamingo (text and images), DeepMind's Gemini

 

5. Code Models

·       Modality: Programming Code

·       Description: Models trained to understand and generate programming code in various languages.

·       Capabilities:

o   Code completion, generation, and translation

o   Bug detection, debugging suggestions

o   Code explanation and documentation

·       Examples: Codex (basis for GitHub Copilot), CodeT5, AlphaCode

 

6. Scientific and Domain-Specific Models

·       Modality: Scientific Data (text, molecular structures, biological sequences, etc.)

·       Description: Foundation models designed for specific domains like medicine, biology, or physical sciences.

·       Capabilities:

o   Protein structure prediction

o   Genomic analysis and drug discovery

o   Domain-specific text analysis (e.g., legal or medical documents)

·       Examples: AlphaFold (protein structures), BioGPT (biomedical NLP), Galactica (scientific papers)

 

7. Reinforcement Learning Models

·       Modality: Game environments, simulations

·       Description: Models trained via reinforcement learning to make decisions in dynamic environments.

·       Capabilities:

o   Autonomous navigation

o   Game-playing (e.g., Chess, Go)

o   Real-time decision-making in robotics

·       Examples: AlphaGo, MuZero, OpenAI Five, DeepMind's AlphaStar

 

8. Robotics and Control Models

·       Modality: Sensor Data (Lidar, radar, cameras, etc.)

·       Description: Models designed for interpreting sensor data and enabling robotic control.

·       Capabilities:

o   Path planning, obstacle avoidance

o   Object manipulation and scene understanding

o   Autonomous vehicle navigation

·       Examples: Tesla's Autopilot Model, OpenAI's Robotics Frameworks, DeepMind's Gato

 

9. Audio-Visual Models

·       Modality: Combined Audio and Video

·       Description: Models specialized in integrating sound and visual data.

·       Capabilities:

o   Lip-reading, video captioning

o   Audio-visual synchronization

o   Understanding context in videos with sound

·       Examples: AVATAR (audio-visual analysis), Google’s Audio-Visual Speech Enhancement model

 

10. Generative Models

·       Modality: Varied (Text, Image, Audio, Video, etc.)

·       Description: Models focused on generating creative outputs, including text, images, music, and videos.

·       Capabilities:

o   Generative art, story writing, music composition

o   Deepfake generation, video synthesis

o   Creative content for marketing and entertainment

·       Examples: GANs (e.g., StyleGAN), Stable Diffusion, Jukebox, GPT-based generators

 

11. Geospatial Models

·       Modality: Satellite imagery, geographic data

·       Description: Models trained to analyze spatial data for earth observation and mapping.

·       Capabilities:

o   Land cover classification, urban planning

o   Climate monitoring, disaster prediction

o   Geographic object detection

·       Examples: Google Earth Engine models, DeepMind's Perceiver IO for geospatial tasks

 

12. Time-Series Models

·       Modality: Sequential Data (e.g., financial data, weather data)

·       Description: Models trained to process and predict sequential patterns in data.

·       Capabilities:

o   Forecasting (e.g., stock prices, weather)

o   Anomaly detection in sequences

o   Predictive maintenance

·       Examples: Temporal Fusion Transformer (TFT), Prophet (for time series forecasting)

 

In Summary, Foundation models are broadly classified by the data they process (e.g., text, images, audio) and their target applications. Each category includes specialized models fine-tuned to excel in their domain, making them suitable for diverse industries like healthcare, robotics, finance, and entertainment.

 

References

https://blogs.nvidia.com/blog/what-are-foundation-models/

Previous                                                    Next                                                    Home