Friday, 7 June 2024

How to Read Request Body as Byte Array in Javalin?

Context.bodyAsBytes() method read the request body as array of bytes.

 

Example

byte[] requestPayoad = ctx.bodyAsBytes();

 

Find the below working application.

 

Step 1: Create new maven project ‘javalin-request-body-as-byte-array’.

 

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-request-body-as-byte-array</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;

public class App {

	public static void main(String[] args) {

		Javalin javalin = Javalin.create();

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

		javalin.post("/echo-file-content", (ctx) -> {

			byte[] requestPayoad = ctx.bodyAsBytes();

			String str = new String(requestPayoad);

			ctx.result(str).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-request-body-as-byte-array-1.0.0-jar-with-dependencies.jar’ file.

 

 

$ls ./target/
archive-tmp
classes
generated-sources
generated-test-sources
javalin-request-body-as-byte-array-1.0.0-jar-with-dependencies.jar
javalin-request-body-as-byte-array-1.0.0.jar
maven-archiver
maven-status
test-classes

Run the application

Execute below command to run the application.

java -jar ./target/javalin-request-body-as-byte-array-1.0.0-jar-with-dependencies.jar

$java -jar ./target/javalin-request-body-as-byte-array-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] @583ms
[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 355ms \o/

Execute below curl command to test the application.

curl --location --request POST 'http://localhost:8080/echo-file-content' \
--header 'Content-Type: application/octet-stream' \
--data-binary '@/Users/krishna/Desktop/demo.txt'

$ curl --location --request POST 'http://localhost:8080/echo-file-content' \
> --header 'Content-Type: application/octet-stream' \
> --data-binary '@/Users/krishna/Desktop/demo.txt'
Hello World
Hi there

You can download this application from this link.




Previous                                                    Next                                                    Home

How to Read Request Body as String in Javalin?

Context.body() method return the request body as string.

Example

String requestPayload = ctx.body();

 

Find the below working application.

 

Step 1: Create new maven project ‘javalin-request-body-as-string’.

 

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-request-body-as-string</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 getJson(Object obj) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(obj);
	}

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

}

 

 

Step 4: Define EmployeeRequestDto class.

 

EmployeeRequestDto.java

 

package com.sample.app.dto;

public class EmployeeRequestDto {

	private String name;
	private Integer age;

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

}

Step 5: Define main application class.

 

App.java

package com.sample.app;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import com.sample.app.dto.EmployeeRequestDto;
import com.sample.app.util.JsonUtil;

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

public class App {
	private static AtomicInteger empIdCounter = new AtomicInteger(1);

	public static void main(String[] args) {

		Javalin javalin = Javalin.create();

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

		javalin.post("/employees", (ctx) -> {

			String requestPayload = ctx.body();

			EmployeeRequestDto employeeRequestDto = JsonUtil.object(EmployeeRequestDto.class, requestPayload);

			Map<String, Object> map = new HashMap<>();
			map.put("id", empIdCounter.getAndIncrement());
			map.put("name", employeeRequestDto.getName());
			map.put("age", employeeRequestDto.getAge());

			String respJson = JsonUtil.getJson(map);

			ctx.res().setHeader("Content-Type", "application/json");
			ctx.result(respJson).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-request-body-as-string-1.0.0-jar-with-dependencies.jar’ file.

$ls ./target/
archive-tmp
classes
generated-sources
generated-test-sources
javalin-request-body-as-string-1.0.0-jar-with-dependencies.jar
javalin-request-body-as-string-1.0.0.jar
maven-archiver
maven-status
test-classes

Run the application

Execute below command to run the application.

java -jar ./target/javalin-request-body-as-string-1.0.0-jar-with-dependencies.jar

$java -jar ./target/javalin-request-body-as-string-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] @762ms
[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 453ms \o/

Execute below curl command to test the api.

curl --location --request POST 'http://localhost:8080/employees' \
--header 'Content-Type: application/json' \
--data-raw '{"name" : "Krishna", "age" : 32}'

$ curl --location --request POST 'http://localhost:8080/employees' \
> --header 'Content-Type: application/json' \
> --data-raw '{"name" : "Krishna", "age" : 32}'
{"name":"Krishna","id":1,"age":32}

You can download this application from this link.


 

Previous                                                    Next                                                    Home

Thursday, 6 June 2024

Understanding and Preventing Spider Traps in Web Crawling

 

A spider trap is a situation in web crawling, where a web crawler ends up in an infinite loop, by repeatedly visiting the same pages again and again, or continuously discovering new, but irrelevant, pages.

 

Let us get a quick glance on this with below example.

 

Example 1: Infinite Loops

Suppose the web crawler is scanning a calendar application that presents the current month details and has links to "Next" and "Previous" months. This setup can create a spider trap, specifically an infinite loop trap for web crawlers.

 

How to address this infinite loop problem?

1.   By Implementing a limit on how much depth (back or forward) the links go, e.g., only 8 to 10 level in either direction.

2.   We can even tell the crawler that this page is not meant to crawl by adding below content to robots.txt file.

ser-agent: *
Disallow: /calendar/

3.   By adding a "noindex" meta tag to the calendar pages, we can prevent them from being indexed by web crawlers.

<meta name="robots" content="noindex">

 

name="robots": This attribute specifies that the metadata is about robots, which are automated programs that crawl the web, like search engine crawlers.

 

content="noindex": This attribute specifies the instruction for the robots. In this case, "noindex" tells the crawler to not index the page, meaning the page won't show up in search results.

 

Example 2: Dynamically Generated Content Trap

Suppose you have a web page (/my-page/random-data) that generates new random data every time it is visited. This setup can create a spider trap known as a dynamic content trap.

 

In this example, the web crawler believes it is discovering new content on each visit, and this causes the crawler to repeatedly index the page, each time thinking it is indexing a different page.

 

We can notify crawler to not crawl these pages using robots.txt file and meta tags that we discussed in Example 1.

 

Another way is to look for patterns whether this content is really relevant, or some random data not meant to be indexed by crawler.

 

                                                                                System Design Questions