<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vaibhav Pithadiya on Medium]]></title>
        <description><![CDATA[Stories by Vaibhav Pithadiya on Medium]]></description>
        <link>https://medium.com/@vaibhavpithadiya09?source=rss-9d6f8b2b8cdc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*kiRBYj0_P-SeLAj7</url>
            <title>Stories by Vaibhav Pithadiya on Medium</title>
            <link>https://medium.com/@vaibhavpithadiya09?source=rss-9d6f8b2b8cdc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 23:14:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vaibhavpithadiya09/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Use JPA Projections for Selective Query Results in Spring Boot ?]]></title>
            <link>https://medium.com/@vaibhavpithadiya09/how-to-use-jpa-projections-for-selective-query-results-in-spring-boot-a18eba06e232?source=rss-9d6f8b2b8cdc------2</link>
            <guid isPermaLink="false">https://medium.com/p/a18eba06e232</guid>
            <category><![CDATA[jpa-projection]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-data-jpa]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[hibernate-jpa]]></category>
            <dc:creator><![CDATA[Vaibhav Pithadiya]]></dc:creator>
            <pubDate>Mon, 24 Aug 2026 18:38:38 GMT</pubDate>
            <atom:updated>2026-08-24T18:38:38.016Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fa1Hxd5Ckl2d2HzhSU_B6g.png" /></figure><p>When you work with databases in Spring Boot, you usually deal with full entity objects. But in many cases, you don’t need the whole thing.</p><p>Let’s say you have a Student entity with 15 fields. For a dashboard, you only need the student&#39;s name and grade. Fetching the entire record is unnecessary and slows things down.</p><p>This is where <strong>JPA projections</strong> help. They let you query <strong>just the data you actually need</strong> — nothing more.</p><p>In this guide, we’ll look at:</p><ul><li>What projections are</li><li>How to use interface, DTO, and dynamic projections</li><li>When and why to use each one</li></ul><h3>📌 What Are Projections?</h3><p><strong>Projections</strong> allow you to select specific fields from an entity instead of fetching the entire object.</p><p>This is useful when:</p><ul><li>You’re building lightweight API responses</li><li>You want to reduce memory usage</li><li>You need different views of the same entity for different use cases</li></ul><p>Spring Data JPA supports:</p><ul><li>Interface-based projections</li><li>Class-based projections (DTOs)</li><li>Dynamic projections (choose the type at runtime)</li></ul><p>We’ll explain each one using a simple Student example.</p><h3>The Entity: Student</h3><p>Here’s the base entity we’ll use:</p><pre>@Entity<br>public class Student {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br><br>    private String name;<br>    private String email;<br>    private String department;<br>    private Double grade;<br>    private LocalDate enrolledDate;<br><br>    // Getters and setters<br>}</pre><h3>1️⃣ Interface-Based Projection</h3><p>This is the simplest way to fetch only selected fields from your entity.<br>You define a Java interface with just the getters you want, and Spring automatically maps the query result to it.</p><p>Let’s say you’re building a leader board to display the <strong>name</strong> and <strong>grade</strong> of top-performing students. You don’t need their email, department, or enrolment date — just the essentials.</p><p>Instead of fetching the full Student entity, use an <strong>interface-based projection</strong>:</p><p>🧩 Step 1: Define the projection interface</p><pre>public interface StudentSummary {<br>    String getName();<br>    Double getGrade();<br>}</pre><p>This is a plain Java interface with getter methods for the fields you want.</p><blockquote><em>✨ </em><strong><em>Spring Magic:</em></strong><em> When you use this interface in a repository method, Spring Data JPA automatically selects and maps only the fields specified in the interface.</em></blockquote><p>📚 Step 2: Add method to the repository</p><pre>public interface StudentRepository extends JpaRepository&lt;Student, Long&gt; {<br>    List&lt;StudentSummary&gt; findByGradeGreaterThan(Double gradeThreshold);<br>}</pre><p>Here, the method name defines the query (findByGradeGreaterThan) and the return type (List&lt;StudentSummary&gt;) tells Spring to map the results to your interface projection.</p><p>🚀 Step 3: Use it in your service or controller</p><pre>List&lt;StudentSummary&gt; topStudents = studentRepository.findByGradeGreaterThan(90.0);</pre><p>You now get a lightweight list of students with only the name and grade fields populated.</p><h4>✅ Pros:</h4><ul><li>Simple to use</li><li>No custom query needed</li><li>Spring handles the mapping</li></ul><h4>⚠️ Limitations:</h4><ul><li>You can’t add logic or formatting</li><li>Field names must match exactly with entity</li></ul><h3>2️⃣ Class-Based Projection (DTO for Control)</h3><p>This approach uses a <strong>custom class</strong> (a Data Transfer Object) to hold the selected fields. You write a query that matches the class constructor.</p><p>It gives you more flexibility — like formatting data, renaming fields, or adding custom logic.</p><p>Now let’s say you’re building a department-wise student list. You want to display <strong>name</strong> and <strong>department</strong>, but also need to <strong>format or process</strong> the data before returning it in your API.</p><p>🧩 Step 1: Create a DTO class</p><pre>public class StudentDTO {<br>    private String name;<br>    private String department;<br><br>    public StudentDTO(String name, String department) {<br>        this.name = name;<br>        this.department = department;<br>    }<br><br>    // Getters (No setters needed if it&#39;s read-only)<br>}</pre><p>💡 You can add more logic here like formatting or derived fields.</p><p>📚 Step 2: Add a query in the repository</p><pre>@Query(&quot;SELECT new com.example.dto.StudentDTO(s.name, s.department) FROM Student s WHERE s.department = :dept&quot;)<br>List&lt;StudentDTO&gt; findStudentsByDepartment(@Param(&quot;dept&quot;) String department);</pre><p>Spring uses the constructor of StudentDTO to map the selected fields.</p><p>🚀 Step 3: Use in your service or controller</p><pre>List&lt;StudentDTO&gt; csStudents = studentRepository.findStudentsByDepartment(&quot;Computer Science&quot;);</pre><p>Now you have a DTO with only the fields you need — cleanly separated from your entity logic.</p><h4>✅ Pros:</h4><ul><li>You control the structure</li><li>You can include logic or formatting</li><li>Good for building API responses</li></ul><h4>⚠️ Limitations:</h4><ul><li>You must write a query</li><li>The constructor must match exactly</li></ul><h3>3️⃣ Dynamic Projections (Flexible &amp; DRY)</h3><p>This lets you decide the projection <strong>at runtime</strong> by passing the projection class as a parameter.<br>You can reuse the same repository method for different return shapes.</p><p>Imagine you’re building an admin dashboard that shows <strong>basic details</strong> to regular users but <strong>full profiles</strong> to admins. You don’t want to write separate repository methods for each use case.</p><p>This is where <strong>dynamic projections</strong> shine.</p><p>🧩 Step 1: Define multiple projections</p><pre>public interface StudentSummary {<br>    String getName();<br>    Double getGrade();<br>}<br><br>public class StudentDTO {<br>    private String name;<br>    private String department;<br><br>    public StudentDTO(String name, String department) {<br>        this.name = name;<br>        this.department = department;<br>    }<br><br>    // Getters<br>}</pre><p>📚 Step 2: Create a dynamic method in the repository</p><pre>&lt;T&gt; List&lt;T&gt; findByDepartment(String department, Class&lt;T&gt; type);</pre><p>This tells Spring: “I’ll provide the projection class when I call this.”</p><p>🚀 Step 3: Use in service layer</p><pre>// For frontend leaderboard<br>List&lt;StudentSummary&gt; basicView = studentRepository.findByDepartment(&quot;Science&quot;, StudentSummary.class);<br><br>// For admin panel<br>List&lt;StudentDTO&gt; detailedView = studentRepository.findByDepartment(&quot;Science&quot;, StudentDTO.class);</pre><p>It keeps your code DRY and adaptable without having to define multiple methods.</p><h4>✅ Pros:</h4><ul><li>Flexible</li><li>Works with both interfaces and DTOs</li><li>Keeps repository code simple</li></ul><h4>⚠️ Limitations:</h4><ul><li>Slightly harder to read and debug</li><li>Requires consistent DTOs and projections</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FGnJ0zAetobPiXJijWXc5w.png" /></figure><p>JPA projections help you write cleaner, faster, and more focused code. Whether you’re building APIs or just optimizing queries, projections let you avoid over-fetching and keep keep your logic simple.</p><ul><li>Start with <strong>interface projections</strong> if you only need a few fields.</li><li>Use <strong>DTOs</strong> when you want more control or need custom formatting.</li><li>Use <strong>dynamic projections</strong> when you want flexibility with minimal duplication.</li></ul><blockquote>Select only what you need — your code (and your database) will thank you. 😄🗃️<br>Happy coding! 🚀</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a18eba06e232" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Digitally Sign and Validate XML Using Java (PKCS#12 + X.509)]]></title>
            <link>https://medium.com/@vaibhavpithadiya09/how-to-digitally-sign-and-validate-xml-using-java-pkcs-12-x-509-7dd5efc3afa6?source=rss-9d6f8b2b8cdc------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dd5efc3afa6</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[xml-security]]></category>
            <category><![CDATA[xml-signature]]></category>
            <category><![CDATA[digital-signatures]]></category>
            <category><![CDATA[secure-coding]]></category>
            <dc:creator><![CDATA[Vaibhav Pithadiya]]></dc:creator>
            <pubDate>Sun, 27 Apr 2025 05:53:49 GMT</pubDate>
            <atom:updated>2025-04-27T05:53:49.938Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nbb4a1m3xEU3w9U1JR2K9Q.png" /><figcaption>XML Digital Signature in Java</figcaption></figure><p>In today’s world of secure communications, ensuring the authenticity and integrity of your XML documents is more important than ever.<br> Whether you’re signing invoices, API messages, or security tokens, <strong>digitally signing XML</strong> is a critical step.</p><p>In this guide, I’ll show you <strong>how to sign and validate XML documents using Java</strong>, loading your keys from a secure <strong>PKCS#12 keystore</strong> and embedding <strong>X.509 certificates</strong> properly.</p><blockquote><strong>🚀 What Is Java XML Digital Signature?</strong></blockquote><p>Java has built-in support for XML digital signatures through the javax.xml.crypto.dsig package. It allows you to:</p><ul><li>Create a digital signature inside your XML.</li><li>Use modern algorithms like <strong>SHA-256</strong> and <strong>RSA-SHA256</strong>.</li><li>Embed public key or certificate information.</li><li>Verify if a document has been tampered with after signing.</li></ul><p><strong>In short</strong>: you can prove that the XML was created by you and hasn’t been modified.</p><h3><strong>Generate the Signature</strong></h3><p>Before anything else, you need a <strong>key pair</strong> — a private key to sign and a public key (or certificate) to validate.</p><p>Here’s the code to sign an XML string:</p><pre>// --- Setup XML string to be signed ---<br>String xmlString = &quot;&lt;YourXml&gt;...&lt;/YourXml&gt;&quot;; // Set your XML content here<br><br>// --- Load PKCS12 KeyStore from Base64 ---<br>// You can load private key bytes from a Base64 string, a file, a secret manager, etc.<br>byte[] keyBytes = Base64.getDecoder().decode(YOUR_BASE_64_STRING);<br>KeyStore keyStore = KeyStore.getInstance(&quot;PKCS12&quot;);<br>keyStore.load(new ByteArrayInputStream(keyBytes), &quot;YOUR_PRIVATE_KEY_PASSWORD&quot;.toCharArray());<br><br>// --- Extract Private Key and Certificate ---<br>String keyAlias = keyStore.aliases().nextElement();<br>PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, &quot;YOUR_PRIVATE_KEY_PASSWORD&quot;.toCharArray());<br>X509Certificate certificate = (X509Certificate) keyStore.getCertificate(keyAlias);<br><br>// --- Parse the XML Document ---<br>DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();<br>dbFactory.setNamespaceAware(true);<br>DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();<br>Document xmlDoc = dBuilder.parse(new InputSource(new StringReader(xmlString)));<br><br>// --- Setup XML Signature ---<br>XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance(&quot;DOM&quot;);<br><br>Reference reference = sigFactory.newReference(<br>        &quot;&quot;,<br>        sigFactory.newDigestMethod(DigestMethod.SHA256, null),<br>        Collections.singletonList(sigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),<br>        null,<br>        null<br>);<br><br>// Note: You can configure SignatureMethod as RSA_SHA256, RSA_SHA1, etc.<br>SignedInfo signedInfo = sigFactory.newSignedInfo(<br>        sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null),<br>        sigFactory.newSignatureMethod(SignatureMethod.RSA_SHA256, null),<br>        Collections.singletonList(reference)<br>);<br><br>KeyInfo keyInfo = sigFactory.getKeyInfoFactory().newKeyInfo(<br>        Collections.singletonList(<br>                sigFactory.getKeyInfoFactory().newX509Data(Collections.singletonList(certificate))<br>        )<br>);<br><br>// --- Sign the XML Document ---<br>XMLSignature signature = sigFactory.newXMLSignature(signedInfo, keyInfo);<br>DOMSignContext signContext = new DOMSignContext(privateKey, xmlDoc.getDocumentElement());<br>signature.sign(signContext);<br><br>// --- Output the signed XML as a String ---<br>TransformerFactory tf = TransformerFactory.newInstance();<br>Transformer transformer = tf.newTransformer();<br>transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, &quot;yes&quot;);<br>transformer.setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, &quot;no&quot;);<br><br>StringWriter writer = new StringWriter();<br>transformer.transform(new DOMSource(xmlDoc), new StreamResult(writer));<br><br>// Here is your final signed XML<br>String signedXmlString = writer.toString();<br>System.out.println(&quot;Signed XML:\n&quot; + signedXmlString);</pre><ul><li><strong>Prepare XML:</strong> Set your XML content.</li><li><strong>Load KeyStore:</strong> Decode Base64 PKCS12 and load it.</li><li><strong>Extract Keys:</strong> Get PrivateKey and Certificate.</li><li><strong>Parse XML:</strong> Convert XML string to a Document.</li><li><strong>Create Signature:</strong> Setup SHA-256 digest and signature info.</li><li><strong>Sign XML:</strong> Apply the signature to the XML.</li><li><strong>Output Result:</strong> Convert signed Document back to a String.</li></ul><p>✅ <strong>Tip</strong>: Always set namespaceAware to true, otherwise XML signatures won&#39;t work properly!</p><h3>🔍Validate a Signed XML</h3><p>Here’s the code to <strong>validate</strong> an XML signature:</p><pre>// Your Signed XML Content<br>String signedXml = &quot;&lt;YourSignedXml&gt;...&lt;/YourSignedXml&gt;&quot;; // Your Signed XML content<br><br>// --- Load X.509 Certificate (Public Key) from Base64 ---<br>byte[] certBytes = Base64.getDecoder().decode(YOUR_PUBLIC_KEY_BASE64_STRING); // Set your PublicKey Bytes here [you can read it from Base64 String or file]<br>CertificateFactory certFactory = CertificateFactory.getInstance(&quot;X.509&quot;);<br>X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(certBytes));<br><br>// --- Parse the Signed XML Document ---<br>DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();<br>dbFactory.setNamespaceAware(true);<br><br>DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();<br>Document xmlDoc = dBuilder.parse(new InputSource(new StringReader(signedXml)));<br><br>// --- Locate Signature Node ---<br>NodeList signatureNodes = xmlDoc.getElementsByTagNameNS(XMLSignature.XMLNS, &quot;Signature&quot;);<br>if (signatureNodes.getLength() == 0) {<br>    throw new Exception(&quot;No Signature element found in the XML.&quot;);<br>}<br><br>// --- Setup Validation Context ---<br>DOMValidateContext validateContext = new DOMValidateContext(certificate.getPublicKey(), signatureNodes.item(0));<br>XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance(&quot;DOM&quot;);<br><br>// --- Unmarshal Signature ---<br>XMLSignature xmlSignature = sigFactory.unmarshalXMLSignature(validateContext);<br><br>// --- (Optional) If you want to allow SHA-1 based Signatures ---<br>// By default Java enforces SHA-256 (and stronger). If you want to validate older SHA-1 signatures, uncomment below line:<br>// validateContext.setProperty(&quot;org.jcp.xml.dsig.secureValidation&quot;, Boolean.FALSE);<br><br>// --- Validate Signature ---<br>boolean isValid = xmlSignature.validate(validateContext);<br><br>// --- Result ---<br>System.out.println(&quot;Signature valid: &quot; + isValid);Good practice: Always enable secureValidation to block weak algorithms and attacks.</pre><ul><li><strong>Load Certificate:</strong> Decode Base64 X.509 public key.</li><li><strong>Parse XML:</strong> Read and parse the signed XML into a DOM.</li><li><strong>Find Signature:</strong> Locate the &lt;Signature&gt; element inside XML.</li><li><strong>Setup Validation:</strong> Link public key to the signature node.</li><li><strong>Unmarshal Signature:</strong> Prepare signature object for validation.</li><li><strong>(Optional)</strong>: Allow SHA-1 signatures if needed (generally not recommended).</li><li><strong>Validate:</strong> Check if the XML signature is correct and trustworthy.</li></ul><p>✅ <strong>Tip: </strong>Always prefer SHA-256 or stronger algorithms. Only relax validation rules (e.g., for SHA-1) if absolutely necessary and you trust the data source. 🔒</p><h3>📈 Signing Flow (Diagram)</h3><p>👉 Here’s the high-level process:</p><pre>[Original XML] <br>    ↓<br>[Parse XML Document]<br>    ↓<br>[Generate Digital Signature]<br>    ↓<br>[Embed Signature inside XML]<br>    ↓<br>[Signed XML Output]</pre><p>And for validation:</p><pre>[Signed XML]<br>    ↓<br>[Extract Signature]<br>    ↓<br>[Verify Signature using Public Key]<br>    ↓<br>[Result: Valid / Invalid]</pre><h3>✅ Quick Checklist for XML Signature (Java)</h3><ul><li>📦 Use PKCS#12 (.p12) keystores for keys and certs.</li><li>🛡️ Enable namespaceAware on your XML parser.</li><li>🔐 Prefer SHA256, RSA_SHA256 over older algorithms.</li><li>✨ Use correct canonicalization (Inclusive/Exclusive).</li><li>🏷️ Decide where to place &lt;Signature&gt; inside the XML.</li><li>📋 Verify digest values match exactly.</li><li>🎯 Match declared encoding (UTF-8/UTF-16).</li><li>📜 Embed X.509 certificates inside &lt;KeyInfo&gt;.</li><li>🔒 Enable/Disable secureValidation during verification.</li><li>🧪 Always validate the signature immediately after signing.</li></ul><blockquote>That’s it for today! If XML signing and validation felt confusing before, I hope it’s a breeze now. 🚀<br> Clap, comment, or share if you found this helpful — let’s keep decoding Java’s hidden gems together!</blockquote><blockquote>Remember: Always trust but verify… and double-sign if needed. 😉🔏</blockquote><blockquote>Happy coding! 🚀</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dd5efc3afa6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use AbstractRoutingDataSource for Multitenant Architecture in Java Spring Boot with JPA…]]></title>
            <link>https://medium.com/@vaibhavpithadiya09/how-to-use-abstractroutingdatasource-for-multitenant-architecture-in-java-spring-boot-with-jpa-f7075346703b?source=rss-9d6f8b2b8cdc------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7075346703b</guid>
            <category><![CDATA[datasource]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[abstractroutingdatasource]]></category>
            <category><![CDATA[multitenancy]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Vaibhav Pithadiya]]></dc:creator>
            <pubDate>Fri, 14 Mar 2025 11:16:42 GMT</pubDate>
            <atom:updated>2025-03-14T11:16:42.221Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to use AbstractRoutingDataSource for Multitenant Architecture in Java Spring Boot with JPA Repository ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4BHwrDgtzpEec5hZD0QOkg.png" /></figure><p>If you’re working on a SaaS application, handling multiple tenants (clients) efficiently is a big deal. Each tenant might have its own database, and you need a way to route requests to the correct data source dynamically. That’s where AbstractRoutingDataSource comes in. In this blog, we&#39;ll break down how to use it in a Spring Boot app with JPA, and how you can load tenant details dynamically—whether from an API, a text file, or a database.</p><p>If you’re new to multi-tenancy, check out my detailed guide on <a href="https://medium.com/@vaibhavpithadiya09/what-is-multitenant-architecture-e21c5e1d4fc8">What is Multi-Tenancy and Ways to Implement It</a> before diving into this tutorial.</p><h3>What is AbstractRoutingDataSource?</h3><p>AbstractRoutingDataSource is a special type of DataSource that dynamically determines the actual DataSource to be used based on a given context. This is particularly useful for multi-tenant applications where each tenant has its own database.</p><h3>Steps to Implement Multi-Tenancy</h3><blockquote><strong><em>Step 1: Storing Current Tenant Information</em></strong></blockquote><p>To identify which tenant is making the request, we use a ThreadLocal variable:</p><pre>public class CurrentTenantHolder {<br>    private static final ThreadLocal&lt;String&gt; tenantHolder = new ThreadLocal&lt;&gt;();<br><br>    public static void setTenantId(String tenantId) {<br>        tenantHolder.set(tenantId);<br>    }<br><br>    public static String getTenantId() {<br>        return tenantHolder.get();<br>    }<br><br>    public static void clear() {<br>        tenantHolder.remove();<br>    }<br>}</pre><p>This class provides a thread-safe way to store and retrieve the tenant ID for each request.</p><blockquote><strong><em>Step 2: Creating the AbstractRoutingDataSource Implementation</em></strong></blockquote><p>This class decides which data source to use based on the current tenant:</p><p><strong>Required Dependency: </strong><a href="https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa">Spring Data JPA</a></p><pre>public class MultiTenantDataSource extends AbstractRoutingDataSource {<br>    @Override<br>    protected Object determineCurrentLookupKey() {<br>        return CurrentTenantHolder.getTenantId();<br>    }<br>}</pre><p>Spring will call <strong>determineCurrentLookupKey()</strong> whenever it needs to figure out which data source to use.</p><blockquote><strong><em>Step 3: Configure the DataSources Dynamically</em></strong></blockquote><p>We need to configure DataSources dynamically based on tenant info, which can come from different sources [like APIs, Text File, DataBase, etc].</p><p><strong>Required Dependency: </strong><a href="https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web">Spring Boot Web</a></p><pre>@Service<br>public class TenantDataSourceService {<br>    private final Map&lt;String, DataSource&gt; dataSourceMap = new HashMap&lt;&gt;();<br><br>    @PostConstruct<br>    public void loadTenantsFromApi() {<br>        // Fetch tenant details from an API, File or DataBase and populate dataSourceMap<br>    }<br><br>    private DataSource createDataSource(String jdbcUrl, String username, String password) {<br>        HikariDataSource dataSource = new HikariDataSource();<br>        dataSource.setJdbcUrl(jdbcUrl);<br>        dataSource.setUsername(username);<br>        dataSource.setPassword(password);<br>        return dataSource;<br>    }<br><br>    public Map&lt;String, DataSource&gt; getDataSourceMap() {<br>        return dataSourceMap;<br>    }<br>}</pre><p>This service fetches tenant database details from an API, File or DataBase and creates data sources dynamically.</p><blockquote><strong><em>Step 4: Configure MultiTenant DataSource in Spring Boot</em></strong></blockquote><pre>@Configuration<br>public class DataSourceConfig {<br><br>    @Bean<br>    public DataSource defaultDataSource() {<br>        HikariDataSource defaultDataSource = new HikariDataSource();<br>        defaultDataSource.setJdbcUrl(&quot;jdbc:mysql://localhost:3306/default_db&quot;);<br>        defaultDataSource.setUsername(&quot;default_user&quot;);<br>        defaultDataSource.setPassword(&quot;default_password&quot;);<br>        return defaultDataSource;<br>    }<br><br>    @Bean<br>    public DataSource dataSource(TenantDataSourceService tenantDataSourceService, DataSource defaultDataSource) {<br>        MultiTenantDataSource multiTenantDataSource = new MultiTenantDataSource(defaultDataSource);<br>        multiTenantDataSource.setTargetDataSources(new HashMap&lt;&gt;(tenantDataSourceService.getDataSourceMap()));<br>        multiTenantDataSource.setDefaultTargetDataSource(defaultDataSource); // To Ensure fallback<br>        return multiTenantDataSource;<br>    }<br>}</pre><p>This configuration sets up the multi-tenant data source and populates it with tenant-specific data sources.</p><h4>Why Do We Need a Default DataSource?</h4><p>In a multi-tenant setup, every request needs to be routed to the right database. But what happens if a request comes in without a valid tenant ID? Or if a tenant’s database isn’t configured yet? That’s where a <strong>default DataSource</strong> comes in.</p><p>Having a default DataSource ensures that:<br> ✔️ The app doesn’t crash when a tenant ID is missing.<br> ✔️ You can handle shared or system-wide operations easily.<br> ✔️ There’s always a fallback database available.</p><p>If you don’t set up a default DataSource, <strong>Spring Boot will throw an error</strong> because it requires at least one DataSource to initialize the application context. So, setting a default DataSource is not just a good practice — it’s a necessity to keep your app stable and running smoothly! 🚀</p><blockquote><strong><em>Step 5: Capturing Current Tenant ID from Requests</em></strong></blockquote><p><strong>Required Dependency: </strong><a href="https://mvnrepository.com/artifact/org.springframework/spring-web">Spring Web</a>, <a href="https://mvnrepository.com/artifact/jakarta.servlet/jakarta.servlet-api">Jakarta Servlet</a></p><pre>@Component<br>public class TenantFilter extends OncePerRequestFilter {<br>    @Override<br>    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, <br>                                    FilterChain filterChain) throws ServletException, IOException {<br>        String tenantId = request.getHeader(&quot;X-Tenant-ID&quot;);<br>        if (tenantId != null) {<br>            CurrentTenantHolder.setTenantId(tenantId);<br>        }<br>        try {<br>            filterChain.doFilter(request, response);<br>        } finally {<br>            CurrentTenantHolder.clear();<br>        }<br>    }<br>}</pre><p>This filter extracts the tenant ID from the request header and sets it in the <strong>CurrentTenantHolder</strong>.</p><blockquote><strong><em>Step 6: Using JPA Repository with Multi-Tenancy</em></strong></blockquote><pre>@Repository<br>public interface CustomerRepository extends JpaRepository&lt;Customer, Long&gt; {}<br><br>@Service<br>public class CustomerService {<br>    @Autowired<br>    private CustomerRepository customerRepository;<br><br>    public List&lt;Customer&gt; getAllCustomers() {<br>        return customerRepository.findAll();<br>    }<br>}</pre><p><em>This demonstrates how to use a JPA repository in a multi-tenant setup. The correct database is selected based on the current tenant.</em></p><p>With AbstractRoutingDataSource, managing multiple tenants in a Spring Boot application becomes much easier. Whether your tenant details come from an API, a text file, or another source, this approach allows you to dynamically route database connections efficiently.</p><blockquote>That’s a wrap! If this guide helped unravel a bit of Java’s mystery for you, be sure to hit that clap button or leave a comment. I’m always here to dive into more Java twists, turns, and hidden gems! ☕👨‍💻</blockquote><blockquote>Happy coding, and may your multi-tenant configurations be seamless and your JPA queries always efficient! 😎</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7075346703b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Multitenant Architecture ?]]></title>
            <link>https://medium.com/@vaibhavpithadiya09/what-is-multitenant-architecture-e21c5e1d4fc8?source=rss-9d6f8b2b8cdc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e21c5e1d4fc8</guid>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[tenants]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[multitenancy]]></category>
            <dc:creator><![CDATA[Vaibhav Pithadiya]]></dc:creator>
            <pubDate>Fri, 14 Mar 2025 11:14:09 GMT</pubDate>
            <atom:updated>2025-03-14T11:14:09.392Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Multitenant Architecture ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*25RujXnVzLWU3y2GcqpbGg.png" /><figcaption>Multitenant Architecture</figcaption></figure><p>Multitenancy is a software architecture where a single application instance serves multiple customers, known as tenants. Each tenant shares the same infrastructure but has its own data and configurations. This approach is widely used in cloud-based SaaS (Software as a Service) platforms because it optimizes resources and reduces costs while still allowing for tenant-specific customizations.</p><h3>Different Approaches to Implement Multitenancy</h3><p>There are several ways to implement multitenancy, each offering different levels of data isolation, scalability, and complexity.</p><blockquote><strong><em>Approach 1: Shared Database with a Common Schema</em></strong></blockquote><p>This approach uses a single database and the same set of tables for all tenants. A tenant_id column is used to differentiate data belonging to different tenants.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*TNr23XkdtRZNEpW_O1Yc8g.png" /></figure><p><strong>Pros:</strong></p><ul><li>Cost-effective and easy to manage</li><li>Highly scalable</li><li>Simple schema management</li></ul><p><strong>Cons:</strong></p><ul><li>Security risks due to data co-location</li><li>More complex query filtering to ensure tenant isolation</li></ul><blockquote><strong><em>Approach 2: Shared Database with Tenant-Specific Schemas</em></strong></blockquote><p>In this model, all tenants still use a single database, but each tenant has its own schema. This allows better separation of data while keeping the benefits of a shared infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IIb9eb94AooQNoW39JkYsw.png" /></figure><p><strong>Pros:</strong></p><ul><li>Moderate data isolation</li><li>More control over tenant-specific configurations</li><li>Easier to scale than separate databases per tenant</li></ul><p><strong>Cons:</strong></p><ul><li>More complex schema management</li><li>Potential resource contention if one tenant uses too many resources</li></ul><blockquote><strong><em>Approach 3: Separate Database Per Tenant</em></strong></blockquote><p>Each tenant has its own dedicated database. This model ensures complete data isolation and is often used for enterprises with strict security and compliance needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YVbTnw2OHtA5C8fqo7Fxhw.png" /></figure><p><strong>Pros:</strong></p><ul><li>Strongest data isolation and security</li><li>Easy to comply with industry regulations</li><li>Performance tuning possible for each tenant</li></ul><p><strong>Cons:</strong></p><ul><li>Higher infrastructure and maintenance costs</li><li>More complex management at scale</li></ul><h3>Different Ways to Identify a Tenant</h3><p>Tenant verification ensures that users can only access their assigned data and resources.</p><ul><li><strong>Subdomains:</strong> Assigning unique subdomains for each tenant, such as tenant1.example.com, tenant2.example.com. This is useful in web applications where each tenant needs a separate branded experience and can have custom settings per subdomain.</li><li><strong>Custom Headers:</strong> Including X-Tenant-ID in API requests to identify the tenant dynamically. This is commonly used in microservices architectures where a single API serves multiple tenants.</li><li><strong>JWT Tokens:</strong> Embedding tenant-specific information inside authentication tokens to verify access rights. This method ensures secure and stateless identification of tenants, making it efficient for authentication flows.</li><li><strong>Database Lookup:</strong> Mapping users to tenants in a database before granting access to resources. This is particularly useful in systems that manage multiple user roles across different tenants and require strict access control.</li></ul><h3>Pros and Cons of Multitenancy</h3><h4>Benefits</h4><ul><li><strong>Cost Savings:</strong> Shared infrastructure reduces hosting and maintenance costs.</li><li><strong>Easy Scaling:</strong> A single platform can accommodate multiple tenants efficiently.</li><li><strong>Centralized Management:</strong> Updates and security patches apply to all tenants simultaneously.</li><li><strong>Faster Deployment:</strong> Onboarding new tenants is quicker and requires minimal setup.</li></ul><h4>Challenges</h4><ul><li><strong>Security Risks:</strong> Without strong isolation measures, there’s a risk of data leaks.</li><li><strong>Performance Issues:</strong> A high-traffic tenant could impact other tenants in shared models.</li><li><strong>Complex Access Control:</strong> Proper access restrictions must be enforced to prevent cross-tenant data exposure.</li></ul><p>Multitenancy is a highly efficient architecture for SaaS platforms, but it comes with trade-offs. Choosing the right model depends on your business needs, compliance requirements, and scalability goals. By implementing the right security, performance, and management strategies, businesses can leverage multitenancy to build cost-effective and scalable solutions.</p><blockquote>That’s a wrap! If this guide helped you understand multitenancy better, be sure to share your thoughts or drop a comment. 🚀</blockquote><blockquote>Multitenancy is a game-changer for scalable SaaS applications, but choosing the right approach depends on security, performance, and management needs. May your tenant isolation be strong, your queries efficient, and your scaling seamless! 😎💻</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e21c5e1d4fc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Method Hiding ?]]></title>
            <link>https://medium.com/@vaibhavpithadiya09/what-is-method-hiding-82fa61580730?source=rss-9d6f8b2b8cdc------2</link>
            <guid isPermaLink="false">https://medium.com/p/82fa61580730</guid>
            <category><![CDATA[java-programming]]></category>
            <category><![CDATA[overriding]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[method-hiding]]></category>
            <category><![CDATA[java-method-hiding]]></category>
            <dc:creator><![CDATA[Vaibhav Pithadiya]]></dc:creator>
            <pubDate>Sat, 28 Dec 2024 14:23:55 GMT</pubDate>
            <atom:updated>2024-12-28T14:27:01.364Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Method Hiding and Why It Matters in OOP?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oWB-io61d5RMON06E2dztg.png" /></figure><p>When we talk about object-oriented programming, one of the most important concepts is method overriding. It allows a subclass to redefine a method that’s already defined in its parent/super class. This is what enables polymorphism — where the method that runs depends on the actual object at runtime, not the reference type. But things get a little different when it comes to static methods. Instead of overriding, we encounter something called <strong>method hiding</strong>.</p><h3>Method Overriding</h3><p>Whatever method a parent class has is by default available to the child class through inheritance. If the child class is not satisfied with the parent class’s implementation, it is allowed to redefine that method based on its own requirements. This process is called overriding.</p><h3>Method Hiding</h3><p>Now, when you are working with static methods or trying to override static methods, the behaviour is different. This behaviour is called <strong>Method Hiding</strong>.</p><p>When both the parent and child classes have <strong>static </strong>methods with the same signature[method name and parameters], it’s called <strong>method hiding</strong> instead of overriding. Here, the method that gets called depends on the type of the reference, not the object. That’s because static methods are resolved at compile-time.</p><blockquote>Example of Method Hiding:</blockquote><pre>class Parent {<br>    public static void test1() {<br>        System.out.println(&quot;Parent&quot;);<br>    }<br>}<br><br>class Child extends Parent {<br>    public static void test1() {<br>        System.out.println(&quot;Child&quot;);<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        Parent obj = new Child();<br>        obj.test1(); // ==&gt; Output: Parent<br><br>        Child childObj = new Child();<br>        childObj.test1(); // ==&gt; Output: Child<br>    }<br>}</pre><p>Here, the test1 method in the Child class hides the test1 method in the Parent class. Here compiler is responsible for method resolution based on reference type (Parent or Child).</p><blockquote>Difference between Method Overriding and Method Hiding</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*br0e98YBpalzSLlBBK-vTA.png" /></figure><blockquote>At first glance, method overriding and method hiding might seem similar, but they work very differently. Overriding deals with instance methods and decisions made at runtime, while method hiding involves static methods and decisions made at compile-time.</blockquote><p>Happy coding, and may your static methods always stay hidden when needed! 😎</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82fa61580730" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implement Http Retry in C#?]]></title>
            <link>https://medium.com/@vaibhavpithadiya09/how-to-implement-http-retry-in-c-875413eef0c2?source=rss-9d6f8b2b8cdc------2</link>
            <guid isPermaLink="false">https://medium.com/p/875413eef0c2</guid>
            <category><![CDATA[c-sharp-development]]></category>
            <category><![CDATA[timeouthandling]]></category>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[retry-policy]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Vaibhav Pithadiya]]></dc:creator>
            <pubDate>Thu, 12 Dec 2024 17:11:27 GMT</pubDate>
            <atom:updated>2024-12-12T17:11:27.577Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S79KcGol0fJhurgeQkhtQA.jpeg" /></figure><p>When working with external services or APIs, it’s common to encounter transient errors, such as network timeouts or temporary unavailability of services. Handling these failures gracefully is essential for building resilient applications. One effective way to do this is by implementing <strong>retry logic</strong>. In this blog post, we’ll explore how to implement retry logic in C# with <strong>timeout handling</strong>, using the popular <strong>Polly</strong> library.</p><blockquote><strong>Why Use Retry Logic?</strong></blockquote><p>Retry logic automatically retries failed operations a few times to handle <strong>transient failures</strong> — temporary issues like network glitches or brief service downtimes. This prevents your application from failing outright due to such issues. However, indiscriminate retries can cause resource overloads and increased wait times. To avoid this, retry logic should be paired with <strong>timeout handling</strong> and <strong>exponential backoff</strong> strategies.</p><h4><strong>Step 1: Setting Up the Polly Library</strong></h4><p>To implement retry logic in C#, we will use <strong>Polly</strong>, a .NET resilience and transient-fault-handling library. Polly provides easy-to-use policies to handle retries, timeouts, circuit breakers, and more.</p><p>Start by installing the Polly NuGet package into your project:</p><pre>Install-Package Polly</pre><h4>Step 2: Creating the Retry Client</h4><p>Now, let’s create a custom HTTP client that incorporates retry logic and timeout handling. We’ll create a class CustomHttpRetryClient that inherits from DelegatingHandler. This class will use <strong>Polly&#39;s </strong><strong>WaitAndRetryAsync policy</strong> for retrying failed requests, and <strong>TimeoutAsync</strong> for managing request timeouts.</p><pre>public class CustomHttpRetryClient : DelegatingHandler<br>{<br>    private int _maxRetries;<br>    private int _maxWaitSec;<br><br>    public CustomHttpRetryClient(HttpClientHandler handler, int MaxRetries, int MaxWait) : base(handler)<br>    {<br>        _maxRetries = MaxRetries;<br>        _maxWaitSec = MaxWait;<br>    }<br><br>    protected override Task&lt;HttpResponseMessage&gt; SendAsync(<br>        HttpRequestMessage request,<br>        CancellationToken cancellationToken)<br>    {<br>        return Policy<br>            .Handle&lt;HttpRequestException&gt;()<br>            .Or&lt;TaskCanceledException&gt;()<br>            .OrResult&lt;HttpResponseMessage&gt;(x =&gt; !x.IsSuccessStatusCode)<br>            .WaitAndRetryAsync(_maxRetries, (retryAttempt) =&gt;<br>            {<br>                var backoff = TimeSpan.FromMilliseconds(Math.Min(Math.Pow(2, retryAttempt) * 100, _maxWaitSec * 1000));<br><br>                // You can add logging or other activities here for retry attempts<br>                // For example: log.Info($&quot;Retry Attempt No:- {retryAttempt} in {backoff} sec, for request url : {request.RequestUri}&quot;);<br><br>                return backoff;<br>            },<br>            onRetry: (result, timespan, attempt, context) =&gt;<br>            {<br>                string errorMessage = result.Exception?.Message ?? $&quot;HTTP Status Code: {result.Result?.StatusCode}&quot;;<br>                if (result.Exception?.InnerException != null)<br>                {<br>                    errorMessage += &quot;Inner Exception: &quot; + result.Exception.InnerException.Message;<br>                }<br><br>                // You can add logging or other activities here for retry failures<br>                // For example: log.Warn($&quot;Retry Attempt {attempt} failed. Exception: {errorMessage}&quot;);<br><br>                // You can also implement email alerts or other mechanisms here<br>            })<br>            .ExecuteAsync(() =&gt; base.SendAsync(request, cancellationToken));<br>    }<br>}</pre><p><strong>Explanation of Key Concepts:</strong></p><ul><li><strong>Retries with Exponential Backoff: </strong>The retry logic waits for a progressively increasing duration (e.g., 1s, 2s, 4s) between each retry attempt, which is done through <strong>Polly’s </strong><strong>WaitAndRetryAsync</strong>. This approach prevents overwhelming the target service and gives it time to recover from transient issues.</li><li><strong>Timeout Handling:</strong> Using Polly’s <strong>TimeoutAsync</strong>, you set a maximum time limit for each request. If the request takes longer than the specified timeout, it will be aborted, and a TaskCanceledException will be thrown.</li></ul><h4>Step 3: Using the CustomHttpRetryClient</h4><p>Now that the retry logic and timeout handling are implemented in CustomHttpRetryClient, let’s see how to use this client in your application. This involves creating an instance of HttpClient with the custom retry logic and sending requests using the retry mechanism.</p><p>Here’s an example of how you can use this CustomHttpRetryClient in a service that makes HTTP requests:</p><pre>using (var client = new HttpClient(new CustomHttpRetryClient(new HttpClientHandler { UseCookies = false }, 3, 10)))<br>{<br>    client.Timeout = TimeSpan.FromSeconds(60); // Setting HttpClient timeout separately<br>    client.DefaultRequestHeaders.Add(&quot;ApiKey&quot;, &quot;your-api-key&quot;);<br><br>    var request = new HttpRequestMessage<br>    {<br>        Method = HttpMethod.Get,<br>        RequestUri = new Uri(&quot;https://api.example.com/endpoint&quot;)<br>    };<br><br>    try<br>    {<br>        var response = await client.SendAsync(request);<br><br>        if (response.IsSuccessStatusCode)<br>        {<br>            // Process the successful response<br>            var content = await response.Content.ReadAsStringAsync();<br>            Console.WriteLine($&quot;Success: {content}&quot;);<br>        }<br>        else<br>        {<br>            // Handle the failure response (e.g., 404, 500)<br>            Console.WriteLine($&quot;Request failed with status code: {response.StatusCode}&quot;);<br>        }<br>    }<br>    catch (HttpRequestException ex)<br>    {<br>        // This will catch exceptions like network errors or HTTP request failures<br>        Console.WriteLine($&quot;Request failed: {ex.Message}&quot;);<br>    }<br>    catch (TaskCanceledException ex)<br>    {<br>        // Handle timeouts<br>        if (!ex.CancellationToken.IsCancellationRequested)<br>        {<br>            Console.WriteLine(&quot;Request timed out.&quot;);<br>        }<br>    }<br>}</pre><h4>Step 4: Fine-tuning the Retry and Timeout Logic</h4><p>Here are a few considerations when configuring the retry and timeout logic:</p><ul><li><strong>Max Retries:</strong> You don’t want to retry too many times, as that could degrade performance. A good default is 3 retries, but it can be adjusted based on the criticality of the request.</li><li><strong>Exponential Backoff:</strong> This strategy increases the wait time between each retry exponentially (e.g., 1s, 2s, 4s, etc.). This prevents overwhelming the external service and increases the chances of success on subsequent retries.</li><li><strong>Timeouts:</strong> It’s important to configure reasonable timeouts. For example, a <strong>request timeout</strong> of 30 seconds means that the application will wait for a maximum of 30 seconds <strong>[including retry]</strong> for a response before considering the request failed.</li></ul><blockquote>Implementing retry logic with Polly in C# is a powerful way to make your applications more resilient to transient failures. Combining this with timeout handling ensures that your application can gracefully deal with network issues or external service downtime. Proper configuration of retries, backoff strategies, and logging can significantly improve the reliability of your API or service calls.</blockquote><blockquote>Incorporate this strategy into your critical services to ensure uptime and robust communication with external systems!</blockquote><p>Happy coding, and may your retries succeed and your timeouts stay far away! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=875413eef0c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Read the HTTP Request Body Multiple Times in Java?]]></title>
            <link>https://medium.com/@vaibhavpithadiya09/how-to-read-the-http-request-body-multiple-times-in-java-f3fa91fd65c0?source=rss-9d6f8b2b8cdc------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3fa91fd65c0</guid>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[http-request-body]]></category>
            <category><![CDATA[java-filters]]></category>
            <category><![CDATA[servlet-filter]]></category>
            <dc:creator><![CDATA[Vaibhav Pithadiya]]></dc:creator>
            <pubDate>Sun, 10 Nov 2024 14:51:38 GMT</pubDate>
            <atom:updated>2025-01-02T17:59:28.615Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wF1Lgk5inka267FOmw8mQ.jpeg" /></figure><p>While working on a Java web project, I ran into a common issue: needing to read the HTTP request body multiple times. If you’ve ever tried this, you know it’s tricky — HttpServletRequest only allows you to read the body once. Spring’s ContentCachingRequestWrapper seemed like a good solution, but I noticed a couple of quirks:</p><ol><li>The body is only cached <em>after</em> the filter chain, so you can’t access it in filters before doFilter is called.</li><li>Even with caching, ServletInputStream still only supports a single read—meaning that once you reach the end, it’s done. Any further reads just return -1.</li></ol><p>Because of these quirks, ContentCachingRequestWrapper didn’t quite work for my needs. So, I came up with a custom HttpServletRequestWrapper to cache the body properly and allow multiple reads wherever needed. Here’s how it works!</p><blockquote><strong>Solution: Custom </strong><strong>HttpServletRequestWrapper with Cached Request</strong></blockquote><p>One of the most effective solutions is to create a custom HttpServletRequestWrapper class. This wrapper reads and caches the entire request body when it’s first created, making it available for repeated access whenever needed. This approach works reliably across both Spring and non-Spring projects.</p><p>Here’s how to implement the custom wrapper. This approach reads the request body into a byte array on initialization, then serves that cached content each time getInputStream() or getReader() is called.</p><pre>import jakarta.servlet.ServletInputStream;<br>import jakarta.servlet.ReadListener;<br>import jakarta.servlet.http.HttpServletRequest;<br>import jakarta.servlet.http.HttpServletRequestWrapper<br>import java.io.*;<br><br>public class CustomHttpServletRequestWrapper extends HttpServletRequestWrapper {<br><br>    private final byte[] cachedRequest;<br><br>    public CustomHttpServletRequestWrapper(HttpServletRequest request) throws IOException {<br>        super(request);<br>        // Read and cache the request body<br>        this.cachedRequest= request.getInputStream().readAllBytes();<br>    }<br><br>    @Override<br>    public ServletInputStream getInputStream() {<br>        return new CachedServletInputStream(this.cachedRequest);<br>    }<br><br>    @Override<br>    public BufferedReader getReader() {<br>        return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(this.cachedRequest)));<br>    }<br><br>    private static class CachedServletInputStream extends ServletInputStream {<br>        private final ByteArrayInputStream byteArrayInputStream;<br><br>        public CachedServletInputStream(byte[] cachedRequest) {<br>            this.byteArrayInputStream = new ByteArrayInputStream(cachedRequest);<br>        }<br><br>        @Override<br>        public boolean isFinished() {<br>            return byteArrayInputStream.available() == 0;<br>        }<br><br>        @Override<br>        public boolean isReady() {<br>            return true;<br>        }<br><br>        @Override<br>        public void setReadListener(ReadListener listener) {<br>            // Not required for this implementation<br>        }<br><br>        @Override<br>        public int read() {<br>            return byteArrayInputStream.read();<br>        }<br>    }<br>}</pre><h3>How It Works</h3><ol><li><strong>Constructor</strong>: The wrapper reads the entire request body from the original HttpServletRequest input stream, storing it in a byte[] (called cachedRequest).</li><li><strong>Overridden </strong><strong>getInputStream() and </strong><strong>getReader()</strong>: These methods return a ServletInputStream and a BufferedReader, respectively, both backed by the cached byte array. This allows the request body to be read multiple times.</li></ol><p><strong>Using in Filter:</strong></p><p>To use this wrapper in a filter, simply wrap the original request and access the body as needed:</p><pre>import jakarta.servlet.*;<br>import jakarta.servlet.http.HttpServletRequest;<br>import java.io.IOException;<br><br>public class LoggingFilter implements Filter {<br><br>    @Override<br>    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)<br>            throws IOException, ServletException {<br>        <br>        // Wrap the original request<br>        HttpServletRequest httpRequest = (HttpServletRequest) request;<br>        CustomHttpServletRequestWrapper wrappedRequest = new CustomHttpServletRequestWrapper(httpRequest);<br><br>        // Log the request body (for demonstration purposes)<br>        String requestBody = new String(wrappedRequest.getInputStream().readAllBytes());<br>        System.out.println(&quot;Request body before chain: &quot; + requestBody);<br><br>        // Proceed with the filter chain<br>        chain.doFilter(wrappedRequest, response);<br><br>        // You can access the cached body again after the filter chain if needed<br>    }<br>}</pre><p><strong>Why This Works Well</strong>: This solution is reliable because it doesn’t rely on framework-specific features, making it a good fit for Spring and non-Spring applications alike.</p><p>Reading the request body multiple times in filters and interceptors can be challenging, but using a custom HttpServletRequestWrapper makes it possible to cache the body and access it as needed throughout the request lifecycle. This approach provides full control over request handling and works consistently in both Spring and non-Spring projects.</p><blockquote>That’s a wrap! If this guide helped unravel a bit of Java’s mystery for you, be sure to hit that clap button or leave a comment. I’m always here to dive into more Java twists, turns, and hidden gems! ☕👨‍💻</blockquote><blockquote>Happy coding, and may your filters be smooth and your requests always accessible! 😎</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3fa91fd65c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Add a Custom Header to an HTTP Request in Java?]]></title>
            <link>https://medium.com/@vaibhavpithadiya09/how-to-add-a-custom-header-to-an-http-request-in-java-82aeb944a81e?source=rss-9d6f8b2b8cdc------2</link>
            <guid isPermaLink="false">https://medium.com/p/82aeb944a81e</guid>
            <category><![CDATA[java-programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[httpservletrequest]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[custom-header]]></category>
            <dc:creator><![CDATA[Vaibhav Pithadiya]]></dc:creator>
            <pubDate>Wed, 30 Oct 2024 18:37:10 GMT</pubDate>
            <atom:updated>2024-10-30T18:37:10.197Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Custom Header with Java" src="https://cdn-images-1.medium.com/max/1024/0*Mk5WJmNnXwPV39fJ" /></figure><p>In Java web development, adding custom headers to HTTP requests can be necessary for several reasons — like security, tracking, or simply passing custom information that the server needs. However, <strong>Java’s </strong>HttpServletRequest <strong>doesn’t provide a direct method like </strong>setHeader <strong>to add custom headers</strong>. This limitation means we need a workaround that can still add headers efficiently without complicating our code.</p><p>This is where <strong>custom request wrappers</strong> come in handy! With a wrapper, you can inject custom headers into requests in a clean, efficient way, making your code easier to manage and scale. In this guide, I’ll show you how to set this up in two easy steps: creating a custom wrapper class and setting up a filter to use that wrapper.</p><blockquote><strong>Step 1: Building the Custom Request Wrapper Class</strong></blockquote><p>The first thing we need is a <strong>custom request wrapper class</strong>. This class lets us create and manage custom headers without touching the core of the original HTTP request. Here’s a quick breakdown of how it works:</p><ul><li><strong>What it Does</strong>: The custom wrapper allows us to “wrap” around the original request and add new headers or modify existing ones.</li><li><strong>Why it Works</strong>: By extending HttpServletRequestWrapper, a built-in Java class, we can override how headers are handled in the request.</li><li><strong>How to Use It</strong>: We create a simple method to add headers, which we can then access whenever we need them.</li></ul><pre>import javax.servlet.http.HttpServletRequest;<br>import javax.servlet.http.HttpServletRequestWrapper;<br>import java.util.Enumeration;<br>import java.util.HashMap;<br>import java.util.Map;<br><br>public class CustomHttpServletRequestWrapper extends HttpServletRequestWrapper {<br>    private final Map&lt;String, String&gt; customHeaders;<br><br>    public CustomHttpServletRequestWrapper(HttpServletRequest request) {<br>        super(request);<br>        this.customHeaders = new HashMap&lt;&gt;();<br>    }<br><br>    public void addHeader(String name, String value) {<br>        this.customHeaders.put(name, value);<br>    }<br><br>    @Override<br>    public String getHeader(String name) {<br>        return this.customHeaders.containsKey(name) ? this.customHeaders.get(name) : super.getHeader(name);<br>    }<br><br>    @Override<br>    public Enumeration&lt;String&gt; getHeaders(String name) {<br>        return this.customHeaders.containsKey(name) ? Collections.enumeration(Collections.singletonList(this.customHeaders.get(name))) : super.getHeaders(name);        <br>    }<br><br>    @Override<br>    public Enumeration&lt;String&gt; getHeaderNames() {<br>        var allHeaders = Collections.list(super.getHeaderNames());<br>        allHeaders.addAll(this.customHeaders.keySet());<br>        return Collections.enumeration(allHeaders);<br>    }<br>}</pre><p>To ensure the custom headers are fully accessible just like standard headers, we override these three methods:</p><ul><li><strong>getHeader(String name)</strong>: This method returns the value of a specific header. By overriding it, we allow our custom header values to be returned when this method is called.</li><li><strong>getHeaders(String name)</strong>: This method provides all values for a header (e.g., headers like Set-Cookie can have multiple values). By overriding it, we ensure that our custom headers, even with multiple values, are handled consistently with Java’s HttpServletRequest.</li><li><strong>getHeaderNames()</strong>: This method returns all header names in an Enumeration, allowing other parts of the application to see our custom headers alongside built-in headers.</li></ul><p>These overrides guarantee that the custom headers are treated just like any other headers by the application, making our custom wrapper seamlessly compatible with existing code.</p><blockquote><strong>Step 2: Setting Up a Filter to Add Headers</strong></blockquote><p>Once we have our custom request wrapper, we need a way to use it in our web application. This is where a <strong>filter</strong> comes in. Filters in Java can intercept requests and responses, making them perfect for our purpose here.</p><p>Our CustomHeaderFilter will do the following:</p><ul><li><strong>Check if the request is HTTP</strong>: We only want to wrap HttpServletRequest, so we check the request type.</li><li><strong>Add Our Custom Header</strong>: We’ll use our wrapper to set a new header called X-Custom-Header.</li><li><strong>Pass the Request Along</strong>: After setting up our custom header, the filter lets the request continue through the rest of the application.</li></ul><pre>import javax.servlet.Filter;<br>import javax.servlet.FilterChain;<br>import javax.servlet.FilterConfig;<br>import javax.servlet.ServletException;<br>import javax.servlet.ServletRequest;<br>import javax.servlet.ServletResponse;<br>import javax.servlet.http.HttpServletRequest;<br>import java.io.IOException;<br><br>public class CustomHeaderFilter implements Filter {<br><br>    @Override<br>    public void init(FilterConfig filterConfig) throws ServletException {<br>        // Initialization of Filter<br>    }<br><br>    @Override<br>    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) <br>            throws IOException, ServletException {<br>        if (request instanceof HttpServletRequest) {<br>            // Our Wrapper Request<br>            CustomHttpServletRequestWrapper customWrappedRequest = new CustomHttpServletRequestWrapper((HttpServletRequest) request);<br>            // Setting the custom header<br>            customWrappedRequest.setHeader(&quot;X-Custom-Header&quot;, &quot;CustomHeaderValue&quot;);<br><br>            // Pass wrapped request along the next filter chain<br>            chain.doFilter(customWrappedRequest, response);<br>        } else {<br>            chain.doFilter(request, response);<br>        }<br>    }<br><br>    @Override<br>    public void destroy() {<br>        // Clean up of resources if needed<br>    }<br>}</pre><ul><li>The doFilter method is where we check the type of the incoming request.</li><li>If the request is an HttpServletRequest, we create an instance of CustomHttpServletRequestWrapper, add our custom header, and pass this wrapped request along the filter chain.</li><li>This setup ensures that the custom header we’ve added will be available to the rest of the application as it handles the request.</li></ul><p>By combining a custom request wrapper with a filter, we’ve created a flexible and scalable way to add headers to HTTP requests in Java. Whether you’re adding headers for tracking, security, or custom processing, this setup provides a clean solution that’s easy to maintain.</p><blockquote><em>That’s a wrap! If this guide helped unravel a bit of Java’s mystery for you, be sure to hit that clap button or leave a comment. I’m always here to dive into more Java twists, turns, and hidden gems! ☕👨‍💻</em></blockquote><blockquote>Happy coding, and may your headers always be custom! <em>😎</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82aeb944a81e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>