Posts

Showing posts from June, 2025

@Transactional

Image
  @Transactional When You Use @Transactional at the Class Level: All public methods of the class are automatically transactional, as if you had added @Transactional on each method. Public method  ==> Runs within a transaction                                            Private / protected method  ==>  Not transactional (no proxy interception)                         Internal method call  ==>  Not transactional (e.g., calling one method from another within same class)  Spring AOP-based proxy  ==> Only public methods are proxied and eligible for transaction management   With Proxy (via @Transactional): Spring creates this proxy automatically when you use @Transactional. userService.updateUser();  Goes through proxy first:    ...

Thread part 1: Thread for client handing request

Image
  Thread part 1: Thread for client handing request 01. Request → Thread Mapping When a request arrives, Spring Boot (via an embedded servlet container like Tomcat) assigns it to a thread from a thread pool (like the Tomcat thread pool).  Each thread handles one request at a time.  This thread is often called a worker thread. 02. ThreadLocal for Request-Specific Data ThreadLocal is used to store data that should be accessible throughout the request without passing it explicitly.  Spring Security and frameworks like Sleuth (for logging) use this under the hood.  However, ThreadLocal should be cleared manually or with proper filters/interceptors to avoid memory leaks in thread pools (since threads are reused). 03. ThreadLocal Automatically Not Cleared (Reasons have been explain at the end) If you use ThreadLocal, you must call .remove() after the request is done (or in a filter/interceptor). Spring Security and others manage their own cleanup. java threadLocal.remo...

JAVA features from 8 to 21

Image
JAVA features from 8 to 21 JAVA 8 1. Lambda Expressions 2. Functional Interfaces - Interfaces with a single abstract method. Example: Runnable, Comparable 3. Streams API 4. Default and Static Methods in Interfaces 5. Method References - list.forEach(System.out::println); 6. Optional Class 7. New Date and Time API (java.time) JAVA 9 01. Private Methods in Interfaces - Interfaces can now have private methods to share code between default methods. interface MyInterface {     private void log(String msg) {         System.out.println("Log: " + msg);     } } 02. Factory Methods for Collections New List.of(), Set.of(), and Map.of() methods for creating immutable collections. 03. Stream API Enhancements New methods: takeWhile(), dropWhile(), and ofNullable() JAVA 10 Not very important JAVA 11 1. var in Lambda Parameters list.forEach((var item) -> System.out.println(item)); 2. New String Methods isBlank(), lines(), strip(), repeat(), etc. JAVA 16 Record...

Identity Providers

Image
Popular Identity Brokers / Identity Providers 1. Auth0 (now part of Okta) Easy to set up and very developer-friendly. Supports social logins, enterprise identity providers, and custom databases.  Offers built-in multi-tenancy, rules, hooks, and extensibility. Free tier available; widely used in startups and enterprises. 2. Okta Enterprise-focused identity platform. Strong integration with SAML, OAuth, OpenID Connect, and SCIM. Supports workforce and customer identity. Very powerful for large-scale enterprise SSO needs.  3. Azure Active Directory (Azure AD) / Entra ID Microsoft's identity platform. Ideal for organizations already using Microsoft 365 or Azure. Supports OAuth, OIDC, and SAML. Common in enterprise environments.  4. Google Identity Platform Allows federated identity through Google accounts. Can be used directly or as part of Firebase Authentication. Good for consumer-facing apps with Google users. 5. Firebase Authentication Developer-friendly from Google. Supp...

JWT Signature Verification Flow (RS256)

Image
JWT Signature Verification Flow (RS256) This document explains how JWT (JSON Web Token) signature verification works using asymmetric encryption (e.g., RS256 ), where the issuer signs with a private key and the verifier checks it using a public key . Example Input JWT Header (before encoding): { "alg" : "RS256" , "typ" : "JWT" } JWT Payload (before encoding): { "sub" : "1234567890" , "name" : "John Doe" , "iat" : 1516239022 } After Base64URL encoding: Header: lmn Payload: pqr Signature Generation: Signature = signWithPrivateKey( "lmn.pqr" ) = x123 Final JWT: JWT = lmn.pqr.x123 Signature Generation (by Token Issuer — e.g., AWS Cognito) The issuer (e.g., AWS Cognito) creates a message: message = lmn.pqr The message is signed using the private RSA key and the algorithm specified in the JWT header: RS256 = RSA with SHA-256  hashing. Signature...

Why you see it in IntelliJ but not in your project folder

Image
  Why you see it in IntelliJ but not in your project folder IntelliJ shows all dependencies under External Libraries, but they are not stored directly inside your project directory. Instead, they are downloaded and cached by your build tool (like Gradle or Maven) in a global location on your system. ~ /.gradle/ caches/modules- 2 /files- 2.1 / ~ / .m2 / repository/ You have a Maven project that uses a:1.2 → it downloads the JAR to ~/.m2/repository. Now, in a Gradle project, you also want to use a:1.2 What actually happens: Gradle does not use Maven’s .m2/repository directly. Instead: Gradle will check its own cache: ~/.gradle/caches/modules-2/files-2.1/ If a:1.2 is not found in Gradle's cache, it will: Download a:1.2 from the remote repository (e.g., Maven Central) again. Store it in the Gradle cache, not reuse from .m2. Why this happens: Gradle and Maven use different caching strategies and metadata formats, so they maintain separate repositories. BUT: You can configure Gradle to l...

JAR vs fat/uber JAR

Image
 JAR  vs fat/uber JAR 01.By default, when you build a regular JAR with Maven or Gradle, your code is packaged inside the JAR, but the dependencies (external libraries) are NOT included inside the JAR itself. 02. This means, on the server where you deploy, you also need to have those dependency JARs available in the classpath for your application to run correctly. 03. However, for easier deployment, many projects use a “fat” or “uber” JAR (sometimes called a shaded JAR). This is a special kind of JAR that packages all your project classes AND all dependency classes into a single JAR file. 04. Tools like Spring Boot’s Gradle or Maven plugins can create such fat JARs using the bootJar task. That way, you only deploy one big JAR, and it has everything needed inside. Extra: When you build a JAR file using Gradle, the Gradle build files themselves (like build.gradle or settings.gradle) are NOT included inside the JAR. The JAR contains only Here’s how usually works when Jenkins and y...

Java thread life cycle and wait/notify

Image
  Java thread life cycle and wait/notify 01.Java Thread Life Cycle — The 6 Main States New → Runnable → Running → Blocked / Waiting / Timed Waiting → Terminated 1. New: Thread is created, but start() hasn’t been called yet. Thread t = new Thread(() -> {}); 2. Runnable: Thread is ready to run, but waiting for CPU time. t.start(); // thread goes to Runnable state 3. Running: CPU picks the thread and runs its run() method. 4. Blocked:  Thread is trying to enter a synchronized block, but another thread holds the lock. synchronized(obj) {     // if another thread is inside this block, you are BLOCKED } 5. Waiting / Timed Waiting: The thread is waiting for another thread to signal/notify it. There are two kinds:   Waiting: infinite until notify()   Timed Waiting: waits for a timeout (e.g., sleep(1000)) wait() and notify() — How They Work These are used for inter-thread communication — not locking. wait(): Tells the thread ->  “Go to ...

How HTTPS works:

Image
How HTTPS works: Phase 1: TLS Handshake (Secure Channel Setup) Phase 2: HTTPS Communication (Encrypted Data Transfer) Phase 1: TLS Handshake (Secure Channel Setup) Step 1: Client Hello  The browser (client) sends an HTTPS request to the server.  It includes:    A random number (`client_random`)    A list of supported cipher suites (e.g., ECDHE-RSA, ECDHE-ECDSA)    TLS version info  Step 2: Server Hello  The server responds with:    Another random number (`server_random`)    A selected cipher suite (e.g., ECDHE-RSA, ECDHE-ECDSA)    Its digital certificate (contains public key and domain info)  Step 3: Certificate Validation (Browser Side)  The browser verifies the server certificate:    Is it issued by a trusted Certificate Authority (CA)?    Is it not expired?    Is the domain name correct?    If valid → continue.    If not → browser shows a "connec...

Data structure and algorithms

Image
Data structure and algorithms 01. Data structure Data structure means the way we used to store or hold the data (RAM or Hard Disk). Advanced: A data structure is a way of organizing and storing data in memory (like RAM or even on disk) so that we can access and manipulate it efficiently. There are some basic data Structures (several commonly used data structures): Basic data structures: Array, LinkedList, Stack, Queue, Map Advanced/complex data structures: Tree, Graph, Trie, Heap, etc. Those 2 types are the foundation/base to build most of data structures. Array: Stores data contiguously in memory (in a memory block). Fast to access by index, but resizing and insert/delete operations are expensive. Linked List: In the Link List, not matter where data has been saved. Each data may have in different different locations but in Link List, they (Node) hold the memory address (Stores elements as nodes, where each node contains the data and a reference (or address) to the next node). Singly ...

AOP

Image
Simple definition: AOP is a way which add some behavior to a method before and after execution it. To handle the AOP behavior proxy concept has been used. Each beans which need AOP, wrap by proxy object and any incoming call is common through proxy and proxy object is handling AOP part (Normally when inject AOP beans, actually beans not inject and instead if that proxy is injecting and proxy redirect to actual methods). Optimize version: AOP is a way to apply behavior before, after, or around method execution without modifying the method itself. Spring AOP uses proxies to achieve this. Only beans that match AOP pointcuts are wrapped in proxy objects. When we inject such a bean, we are actually injecting the proxy, which intercepts method calls, applies AOP logic, and then calls the actual method on the real bean. Core Spring AOP Annotations (used in custom aspects) @Aspect --------------------> Marks a class as an aspect that contains AOP advice methods    @Pointcut -------...

User Auth technique

Image
  Full Federated Login Flow: Cognito + Azure AD 1. User triggers login Your app redirects the user to this Cognito URL: https://prod-timemate.auth.us-east-1.amazoncognito.com/authorize?client_id=jssams30e4gciifv89j6abc5f&response_type=token&scope=email+openid&redirect_uri=https://app.timemate.aeturnum.com%2Ftimesheet 2. Cognito redirects the user to Microsoft login (Cognito redirects to Azure AD) 3. Azure AD authenticates the user  Azure checks its own user pool for the username and password.  If the user exists and credentials are valid → login success.  Azure returns an ID token (and maybe access token) to Cognito. 4. Cognito extracts user info  Cognito reads claims from Azure’s token (like email, `sub`, name, etc.).  If this is the user's first login, Cognito creates a federated user in its user pool (linked to Azure AD). 5. Cognito issues its own token  Cognito now generates and returns a Cognito JWT token (ID token + access token) to y...

What is a BOM (Bill of Materials)

Image
What is a BOM (Bill of Materials)? A BOM is a special kind of POM file (in Maven) that defines a set of dependencies with their versions. It doesn’t bring in the dependencies directly — it just tells the build tool which versions to use when those dependencies are needed. Avoid version conflicts, Centralize version management, Ensure all modules use compatible versions, Reduce duplication in multi-module or large projects Create and Use a BOM in a Multi-Microservice Setup Create a new Maven project for your BOM. This will be a pom-only project — not a JAR. 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 http://maven.apache.org/xsd/maven-4.0.0.xsd" > <modelVersion> 4.0.0 </modelVersion> <groupId> com.lahiru.company </groupId> <artifactId> lah...

OAuth,OpenId,SAML - Topics

Image
 OAuth,OpenId,SAML - Topics 01. OAuth and OpenID 02. Why OpenID 03. Understanding OAuth 2.0: Flows, Standards, and Security Best Practices

01. OAuth and OpenID

Image
  OAuth and OpenID   01. OAuth (Think: Valet Key for Your Car) What it is: OAuth (Open Authorization) is all about authorization. It's a way for us to grant one application (like a photo printing service) permission to access our data in another application (like your Google Photos) without giving it your actual password for Google Photos.   02. OpenID Connect (OIDC) (Think: Showing Your ID at a Bar) What it is: OpenID Connect is all about authentication. It's a layer built on top of OAuth 2.0. It allows you to use one login (like your Google or Facebook account) to sign in to other websites or apps Key Difference OAuth = About access ("Can this app use my data?") OIDC = About identity ("Is this really John Doe?")   Real-World Use Pure OAuth: Allowing a finance app to read your bank transactions OIDC: Logging into that finance app using your Google account   Without OAuth 2.0, OIDC would not exist . W ithout OIDC , OAuth 2.0 can exist. So, w e can u se OAuth...