Posts

Showing posts with the label java

Changing the Default Terminal to Terminator on Ubuntu

Image
Terminator is a powerful tool for developers, allowing you to manage multiple terminal sessions in a single window. Features like splitting panes, tabs, and simultaneous input can significantly boost your productivity. Step 1: Install Terminator First, install Terminator using the apt package manager. sudo apt update sudo apt install terminator -y The -y option automatically answers 'yes' to any prompts during the installation process, streamlining the setup. Step 2: Set as the System Default Ubuntu uses a utility called update-alternatives to manage default applications. We'll use this tool to change the default terminal emulator ( x-terminal-emulator ) to Terminator. Run the Configuration Command Enter the following command in your terminal. A list of available terminals will appear. sudo update-alternatives --config x-terminal-emulator Select Terminator From the resulting list, enter the selection number corresponding to terminator and press Enter. ...

A Comprehensive Guide to Spring Boot & Swagger (OpenAPI) Integration

Image
This guide provides a detailed walkthrough for integrating Swagger UI (with OpenAPI 3.0) into your Spring Boot project. It covers everything from initial dependency setup to handling authentication and following best practices to effectively automate and manage your API documentation. 1. Adding Dependencies First, add the necessary springdoc-openapi dependencies to your pom.xml file. springdoc-openapi-starter-webmvc-ui : This is the core library that automatically generates the OpenAPI 3.0 specification by analyzing your Spring Boot application. It also provides the embedded Swagger UI. springdoc-openapi-maven-plugin : (Optional) This plugin extracts the API documentation into a static file (e.g., openapi.json ) during the Maven build process. It's useful for CI/CD pipelines, sharing API specs with other teams, or generating client-side code. <dependencies> <dependency> <groupId>org.springdoc</groupId> <artifactId>s...

How to Add a gRPC Endpoint to a Spring Boot Microservice

Image
This blog guides you through the standard procedure for adding a gRPC endpoint to the order-service project. The primary goal is to handle "create new order" requests from external clients via gRPC. This process involves calling an internal u ser-service to validate user information. Why Use gRPC? Performance: It's fast, using HTTP/2 and binary serialization (Protobuf), which reduces communication overhead. Strict API Specification: The .proto file clearly defines the service interface and message structures, ensuring type safety at compile time. Multi-language Support: It's suitable for polyglot architectures, as clients and servers can be implemented in various languages. 1. Define the Service with Protocol Buffers (.proto) First, define the service contract by creating a .proto file in the src/main/proto directory. order.proto syntax = "proto3"; package com.abc.order.grpc; // Java code generation options option java_multiple_fil...

How to Fix Lombok's @Builder Ignoring Initial Values with @Builder.Default

Image
Lombok's @Builder is a powerful feature that replaces repetitive builder pattern code with a single annotation. However, when using @Builder , you might encounter the following warning message when you set an initial value for a field: java: @Builder will ignore the initializing expression entirely. If you want the initializing expression to serve as default, add @Builder.Default. If it is not supposed to be settable during building, make the field final. Why Does the Warning Occur? - How Lombok Works Before solving the problem, it's important to understand why Lombok ignores the initial value of the field. When a class is annotated with @Builder , Lombok generates a separate inner Builder class (e.g., UserBuilder ) at compile time. This is the class we use through the .builder() method. The key is that the fields of the original class and the fields of the Builder class exist in different spaces. import lombok.Builder; import lombok.Getter; @Getter @Builder pu...

Checked vs Unchecked Exceptions in Java

In Java, exceptions are categorized into Checked Exceptions and Unchecked Exceptions , depending on how the compiler and exception handling mechanisms operate. Throwable ├─ Error (Unchecked) └─ Exception ├─ CheckedException (e.g., IOException) └─ RuntimeException (Unchecked) 1. Classification Criteria Type Inheritance Hierarchy Compiler Enforcement Common Examples Checked Exception Exception (excluding RuntimeException ) Required IOException , SQLException Unchecked Exception RuntimeException and its subclasses Not Required NullPointerException , IllegalArgumentException 2. What is a Checked Exception? Subclasses of Exception , excluding RuntimeException Compiler forces exception handling You must handle them using try-catch or declare them with throws Common Examples: IOException SQLException FileNotFoundException Cl...

Java Exception Hierarchy – Throwable, Exception, and Error

Image
Java provides a robust and predictable error-handling system, and at the heart of this system lies the exception hierarchy rooted in the Throwable class. Understanding this hierarchy gives you several advantages: Write cleaner and safer code Respond appropriately and recover from errors Easier debugging and maintenance Build more reliable programs In this article, we’ll visualize the Java exception hierarchy, explain each layer, and cover practical exception handling strategies and best practices you’ll use every day. Java Exception Hierarchy at a Glance 1. Top-Level Class: Throwable At the very top is the Throwable class, which represents anything that can be thrown as an error or exception. It has two main direct subclasses: Error : Serious problems at the JVM or system level (not recoverable) Exception : Application-level issues (recoverable) 2. Error – System/JVM-Level Critical Failures Error represents severe problems that applications should not try ...

How Modern Java Improves Exception Handling (Java 21)

Image
In recent Java releases, especially Java 21, exception handling mechanisms have been significantly enhanced to improve both code safety and system reliability . These improvements help developers write more robust, maintainable, and error-resilient applications. 1. switch Statements Now Handle null and Support Pattern Matching In Java versions prior to 21, passing a null value to a switch statement would throw a NullPointerException . Java 21 allows developers to explicitly handle null values inside switch , preventing unexpected crashes. switch (input) { case null -> System.out.println("Input is null."); case "YES" -> System.out.println("Yes!"); default -> System.out.println("Other input."); } Benefits Prevents NullPointerException by design Improves clarity and readability 2. Pattern Matching and when Clauses in switch Java 21 introduces pattern matching for switch , allowing developers to write m...

Managing Shared Libraries in Microservice Architecture Using GCP Artifact Registry

Image
In a microservice architecture, it's common for multiple services to share common functionality or utility classes. To handle this effectively, I manage these shared components as a reusable library (like libs.jar ) that each service can depend on. In this post, I’ll show you how I use GCP Artifact Registry to efficiently manage and distribute a shared library across microservices. Step 1: Enable the Artifact Registry API $ gcloud services enable artifactregistry.googleapis.com --project=[PROJECT_ID] Step 2: Create a Maven Repository in GCP Artifact Registry $ gcloud artifacts repositories create maven-repo \ --repository-format=maven \ --location=us-central1 \ --description="Shared Maven Repo for common libraries" $ gcloud artifacts repositories list --location=us-central1 REPOSITORY FORMAT LOCATION DESCRIPTION maven-repo MAVEN us-central1 Shared Maven repo Step 3: Configure pom.xml for the Shared Library Project In the share...

Mastering GitHub Copilot with IntelliJ

Image
If you're developing Spring Boot applications using IntelliJ and GitHub Copilot (paid plan), this post is your ultimate guide. Learn how to generate boilerplate code, auto-generate tests, refactor suggestions, and much more—all using AI-powered assistance. Supported IDEs IntelliJ IDEA (Community & Ultimate) Visual Studio Code ⚠️ Requires GitHub Copilot Chat plugin installed Summary of GitHub Copilot Usage Feature Description Example 1. Editor Autocomplete Autocomplete suggestions appear after typing comments or method signatures // Create a REST controller → Press Tab 2. Copilot Chat + Slash Commands Use commands like /explain , /doc , /test to analyze, document, or test code /explain → describes what the code does 3. Natural Language Requests Ask questions conversationally without a slash Generate a method that...

Accessing Configuration Values in Spring Boot with @Value Annotation

Spring Boot simplifies the process of accessing external configuration properties, like those defined in application.properties or application.yml, making it easier to maintain and change these properties without altering the codebase. A common approach to access these values is by using the @Value annotation in Spring-managed beans. However, sometimes developers encounter issues when trying to inject these values directly into their classes. The Problem Consider you have the following setup in your Spring Boot application: application.yml app: default-avatar-url: /images/twitter-default-avatar.jpg AuthServiceImpl.java import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; @Service public class AuthServiceImpl implements AuthService { @Value("${app.default-avatar-url}") private String defaultAvatarUrl; } However, when you run the application, you encounter a startup failure with the following error me...