JUnit 5 @BeforeAll: One-Time Setup for Your Tests

When writing automated tests, we often need to perform setup tasks before the tests run. This could involve initializing a database connection, starting a web server, or preparing a complex object that’s expensive to create. JUnit 5 provides a powerful set of annotations to manage the lifecycle of your tests, and for one-time setup logic, the @BeforeAll annotation is the perfect tool.

In this guide, we’ll take a deep dive into the @BeforeAll annotation, understand its rules, and explore its usage with practical code examples. We’ll also clarify the key difference between @BeforeAll and @BeforeEach.

@BeforeAll is the direct replacement for JUnit 4’s @BeforeClass annotation.

What is @BeforeAll?

The @BeforeAll annotation is used to signal that a method should be executed only once, before any tests in the current test class are run. It’s ideal for setup operations that are shared across all test methods in a class but are too resource-intensive to run before each and every test.

Continue reading JUnit 5 @BeforeAll: One-Time Setup for Your Tests

Using Regular Expressions with Java 8 Predicates for Clean Code

Java 8 introduced some powerful functional interfaces, and one of the most versatile is Predicate. A Predicate represents a boolean-valued function of one argument. While it’s commonly used for simple checks, combining it with regular expressions opens up a world of possibilities for more complex data validation and filtering, all within a concise and readable lambda expression.

In this post, we’ll explore how to leverage Java’s Pattern.compile() method to create efficient and reusable regex-based predicates. This approach is particularly useful when you need to perform the same regex validation multiple times, avoiding recompilation overhead for each check.

The Problem with Repeated Regex Matching

Let’s say you have a list of strings, and you want to filter them based on whether they match a specific regular expression. A naive approach might look something like this:

Continue reading Using Regular Expressions with Java 8 Predicates for Clean Code

Mastering Global Variables in JavaScript

Global variables in JavaScript are a topic that often sparks debate among developers. While they offer convenience, their misuse can lead to messy, hard-to-maintain code. At AnkurM.com, we believe in writing clean, robust JavaScript, and that includes understanding the right way to handle global variables. This guide will walk you through the various approaches, highlighting best practices and common pitfalls.

Let’s dive in!

Understanding the Global Scope

In web browsers, the global scope is represented by the window object (or self or frames, though window is most common). Any variable declared outside of a function or block, or implicitly declared without letconst, or var, becomes a property of the global object.

Continue reading Mastering Global Variables in JavaScript

Lombok @Builder: The Definitive Guide to Clean and Fluent Object Creation

As Java applications grow, creating and initializing objects can become a cumbersome task. We’ve all seen them: constructors with a long list of parameters, some of which are optional, leading to multiple overloaded constructors or the error-prone “telescoping constructor” anti-pattern. The traditional solution is the Builder design pattern, which provides a readable, fluent API for object creation. However, writing a Builder by hand for every DTO or entity is tedious and adds significant boilerplate code to your project.

This is where Project Lombok’s @Builder annotation comes to the rescue. It automatically generates the complete, robust Builder pattern implementation for your class at compile time, leaving your source code clean, concise, and focused on its primary responsibility.

In this guide, we’ll dive deep into @Builder, from basic setup to its most powerful and advanced features.

1. Why Do We Need a Builder?

Let’s consider a simple Employee class. Without a builder, you might initialize it like this:


// Telescoping constructors - hard to read, easy to make mistakes
Employee emp1 = new Employee(1L, "Ankur", "Kumar", "DEV", "ACTIVE");
Employee emp2 = new Employee(2L, "John", "Doe", "QA"); // What is the default status?

Continue reading Lombok @Builder: The Definitive Guide to Clean and Fluent Object Creation

Configuring Tomcat to See the Real Client IP Behind a Proxy or Load Balancer

When you deploy a Java web application on Apache Tomcat and place it behind a reverse proxy or a load balancer (like Nginx, Apache httpd, or an AWS Elastic Load Balancer), a common challenge arises: Tomcat no longer sees the original client’s IP address. Instead, methods like request.getRemoteAddr() return the IP address of the load balancer itself.

This can be a significant problem for features that rely on the client’s IP, such as:

  • Security and rate-limiting
  • Geolocation-based services
  • Audit logging and analytics
  • User session tracking

Fortunately, Tomcat provides a clean, built-in solution to this problem: the RemoteIpValve. This post will guide you through understanding the problem and implementing the fix in your server.xml file.

Continue reading Configuring Tomcat to See the Real Client IP Behind a Proxy or Load Balancer

Building Your First Spring RESTful API: A “Hello World” Guide

Let’s dive into the exciting world of Spring Boot and RESTful APIs. If you’re looking to build robust, scalable web services, Spring Boot is an excellent choice and understanding how to create a simple REST API is a fundamental first step.

In this tutorial, we’ll walk through creating a “Hello World” RESTful service that exposes JSON data. This example will cover the basic setup of a Spring Boot project and demonstrating how to handle HTTP GET requests.

Prerequisites

Before we begin, make sure you have the following installed:

  • Java Development Kit (JDK) 8 or higher: You can download it from the Oracle website.
  • Apache Maven: For project management and dependency handling. Download from the Maven website.
  • An Integrated Development Environment (IDE): IntelliJ IDEA, Eclipse, or VS Code with Java extensions are all great choices.

Step 1: Create a Spring Boot Project

The easiest way to start a Spring Boot project is by using the Spring Initializr. Go to the website and configure your project as follows:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: Choose the latest stable version (e.g., 2.7.x or 3.x.x)
  • Group: com.ankurm.restapi
  • Artifact: hello-world
  • Name: hello-world
  • Package name: com.ankurm.restapi.helloworld
  • Packaging: Jar
  • Java: 17 (or your preferred version)
  • Dependencies: Add Spring Web

Click “Generate” to download the project as a ZIP file. Extract it to your desired location.

Continue reading Building Your First Spring RESTful API: A “Hello World” Guide

From Raw Threads to Virtual Threads: A Developer’s Guide to Java Concurrency

If you’ve been a Java developer for any length of time, you’ve heard the words “multithreading” and “concurrency.” They can sound intimidating, conjuring images of deadlocks, race conditions, and nights spent debugging bizarre, unpredictable behavior. But the truth is, in the modern world of multi-core processors, concurrency isn’t optional—it’s essential for building responsive, high-performance applications.

The good news? Java’s approach to concurrency has undergone a massive evolution, a journey from unwieldy, manual controls to elegant, high-level abstractions. It’s like going from manually shifting gears on a Model T to driving a modern car with a sophisticated automatic transmission.

Let’s take a walk through this evolution. Understanding this journey doesn’t just teach you history; it gives you a mental model for choosing the right tool for the job today.

Chapter 1: The Wild West — Thread and Runnable

In the beginning, there was Thread. This is the bedrock of Java concurrency. It’s a direct, one-to-one mapping to an operating system (OS) thread. You want something to run in the background? You create a Thread and you tell it what to do via a Runnable.

Continue reading From Raw Threads to Virtual Threads: A Developer’s Guide to Java Concurrency