<?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 Punam Mankar on Medium]]></title>
        <description><![CDATA[Stories by Punam Mankar on Medium]]></description>
        <link>https://medium.com/@mankarpunam35?source=rss-414836c9f53c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YolbZgKpVUPouUKFza6eJA@2x.jpeg</url>
            <title>Stories by Punam Mankar on Medium</title>
            <link>https://medium.com/@mankarpunam35?source=rss-414836c9f53c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 03:44:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mankarpunam35/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[A Beginner’s Guide to Financial Messaging Protocols]]></title>
            <link>https://medium.com/@mankarpunam35/a-beginners-guide-to-financial-messaging-protocols-e7572a2892e8?source=rss-414836c9f53c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7572a2892e8</guid>
            <dc:creator><![CDATA[Punam Mankar]]></dc:creator>
            <pubDate>Sat, 05 Apr 2025 10:25:12 GMT</pubDate>
            <atom:updated>2025-04-06T19:14:08.345Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Financial messaging protocols are <strong>standards used to communicate between banks, payment networks </strong>etc. to exchange transaction data securely and reliably. These protocols ensure that money movement instructions like fund transfers, settlements, or payment confirmations.</blockquote><h3>ISO 20022</h3><p>ISO 20022 is a global standard that helps financial institutions talk to each other in a clear and consistent way. It defines a common language and structure for electronic messages exchanged between banks, payment systems, and other financial players.</p><p><strong>This standard is used for all kinds of financial data including:</strong></p><p>Payments (like bank transfers)</p><p>Securities trading and settlement</p><p>Credit and debit card transactions</p><p>Other important financial messages</p><p><em>By using ISO 20022, financial institutions can improve communication, reduce errors, and make cross-border transactions faster and more efficient.</em></p><p><strong>It provide the XML-based</strong>, structured.</p><pre>&lt;Document&gt;<br>  &lt;FIToFICstmrCdtTrf&gt;<br>    &lt;GrpHdr&gt;...&lt;/GrpHdr&gt;<br>    &lt;CdtTrfTxInf&gt;...&lt;/CdtTrfTxInf&gt;<br>  &lt;/FIToFICstmrCdtTrf&gt;<br>&lt;/Document&gt;</pre><h3><strong>SWIFT MT (Message Type)</strong></h3><p>SWIFT MT stands for <em>Message Type</em>. These are standardized message formats used by banks around the world to send financial information securely like payments, transfers, or trade details.</p><p>They allow banks in different countries to understand each other when sending money or financial instructions. It’s like a common financial language</p><p><strong>Example:</strong></p><p><strong>MT103</strong> is a very common message for single customer credit transfers. It’s used for <strong>international wire transfers</strong>.</p><p><strong>Contains details such as: </strong><br>Ordering customer, Beneficiary, Sending and receiving bank details, Amount and currency and Payment instructions</p><pre>{1:F01BANKBEBBAXXX0000000000}{2:O1031200BANKUS33AXXX0000000000120000000000N}{4:<br>:20:REFERENCE12345<br>:23B:CRED<br>:32A:250405USD1234,56<br>:50K:/123456789<br>JOHN DOE<br>:59:/987654321<br>JANE SMITH<br>:71A:SHA<br>-}</pre><blockquote>SWIFT MT messages are being gradually replaced by <strong>ISO 20022</strong> messages (e.g., pacs.008 instead of MT103) for more structured, XML-based data formats.</blockquote><h3><strong>SO 8583</strong></h3><p><strong>ISO 8583 </strong>is a standard message format used in card-based transactions, like when you swipe or tap your debit or credit card. It’s used in <strong>ATMs, POS (Point of Sale) machines, and payment gateways </strong>basically, anywhere card payments happen.</p><p><strong>Example:</strong></p><p>When you swipe your card at a store, an <strong>ISO 8583 </strong>message<strong> </strong>is sent to your bank asking:</p><p>‘Can this person pay ₹500?’ and the bank replies with approval or denial, also using ISO 8583.</p><p>ISO 8583 is the standard used to process card payments. it makes sure your card transactions go through securely and correctly.</p><p><strong>An ISO 8583 message has 3 main parts:</strong></p><p><strong>MTI (Message Type Identifier):</strong> Tells what kind of message it is (like request, response, etc.)<br><strong>Bitmap : </strong>Tells which data elements (fields) are present in the message.<br><strong>Data Elements: </strong>These carry the actual transaction info like amount, card number, time, etc.</p><pre>MTI:        0200  → Financial transaction request  <br>Bitmap:     723000110000...  (Fields: 2, 3, 4, 7, 11, 37, 41)  <br>DE2:        411111******1111  <br>DE3:        000000  <br>DE4:        000000010000  <br>DE7:        0405143012  <br>DE11:       123456  <br>DE37:       654321ABCDEF  <br>DE41:       TERMID01</pre><h3><strong>SEPA</strong> (<strong>Single Euro Payments Area)</strong></h3><p>SEPA uses <strong>ISO 20022 XML messages</strong> to send payment instructions.<br> These messages are structured, machine-readable, and carry detailed payment info across European banks in euro currency.</p><p>SEPA makes them fast, cheap, and standardized. It’s used for <strong>bank transfers, direct debits, and card payments</strong> in euros.</p><pre>&lt;Document xmlns=&quot;urn:iso:std:iso:20022:tech:xsd:pain.001.001.03&quot;&gt;<br>  &lt;CstmrCdtTrfInitn&gt;<br>    &lt;GrpHdr&gt;<br>      &lt;MsgId&gt;PAY20250405&lt;/MsgId&gt;<br>      &lt;CreDtTm&gt;2025-04-05T10:30:00&lt;/CreDtTm&gt;<br>      &lt;NbOfTxs&gt;1&lt;/NbOfTxs&gt;<br>      &lt;CtrlSum&gt;100.00&lt;/CtrlSum&gt;<br>      &lt;InitgPty&gt;<br>        &lt;Nm&gt;ABC Company Ltd&lt;/Nm&gt;<br>      &lt;/InitgPty&gt;<br>    &lt;/GrpHdr&gt;<br><br>    &lt;PmtInf&gt;<br>      &lt;PmtInfId&gt;PMT001&lt;/PmtInfId&gt;<br>      &lt;PmtMtd&gt;TRF&lt;/PmtMtd&gt;<br>      &lt;ReqdExctnDt&gt;2025-04-06&lt;/ReqdExctnDt&gt;<br>      &lt;Dbtr&gt;<br>        &lt;Nm&gt;ABC Company Ltd&lt;/Nm&gt;<br>      &lt;/Dbtr&gt;<br>      &lt;DbtrAcct&gt;<br>        &lt;Id&gt;&lt;IBAN&gt;DE89370400440532013000&lt;/IBAN&gt;&lt;/Id&gt;<br>      &lt;/DbtrAcct&gt;<br>      &lt;CdtTrfTxInf&gt;<br>        &lt;Amt&gt;<br>          &lt;InstdAmt Ccy=&quot;EUR&quot;&gt;100.00&lt;/InstdAmt&gt;<br>        &lt;/Amt&gt;<br>        &lt;Cdtr&gt;<br>          &lt;Nm&gt;John Doe&lt;/Nm&gt;<br>        &lt;/Cdtr&gt;<br>        &lt;CdtrAcct&gt;<br>          &lt;Id&gt;&lt;IBAN&gt;FR7630006000011234567890189&lt;/IBAN&gt;&lt;/Id&gt;<br>        &lt;/CdtrAcct&gt;<br>        &lt;RmtInf&gt;<br>          &lt;Ustrd&gt;Invoice 456&lt;/Ustrd&gt;<br>        &lt;/RmtInf&gt;<br>      &lt;/CdtTrfTxInf&gt;<br>    &lt;/PmtInf&gt;<br>  &lt;/CstmrCdtTrfInitn&gt;<br>&lt;/Document&gt;</pre><h3>Open Banking</h3><p>Open Banking is a system where banks allow third-party apps to securely access customer data and services, like account info or payments using APIs.</p><p>Open Banking APIs use RESTful services with JSON messages. A typical message includes account details, amount, and purpose, all securely shared using OAuth tokens and encrypted channels.</p><p><strong>Example:</strong></p><p><strong>Google Pay, PhonePe, or Paytm </strong>use Open Banking APIs to connect to your bank.<br>They don’t store your money, they just act as a bridge between you and your bank.</p><pre>POST /payments<br>Authorization: Bearer eyJhbGciOiJIUzI1NiIsIn...<br>Content-Type: application/json</pre><pre>{<br>  &quot;debtorAccount&quot;: {<br>    &quot;iban&quot;: &quot;DE89370400440532013000&quot;<br>  },<br>  &quot;creditorAccount&quot;: {<br>    &quot;iban&quot;: &quot;FR7630006000011234567890189&quot;<br>  },<br>  &quot;amount&quot;: {<br>    &quot;currency&quot;: &quot;EUR&quot;,<br>    &quot;amount&quot;: &quot;100.00&quot;<br>  },<br>  &quot;remittanceInformation&quot;: {<br>    &quot;unstructured&quot;: &quot;Invoice #456&quot;<br>  }<br>}</pre><p>Response:</p><pre>{<br>  &quot;paymentId&quot;: &quot;abc123&quot;,<br>  &quot;transactionStatus&quot;: &quot;ACCP&quot;<br>}</pre><p>Whether you’re building a payment gateway, working on a banking API, or designing a financial app. Understanding these messaging protocols is crucial.</p><p>They form the foundation of modern banking. From card swipes to international wire transfers, everything relies on these standards to ensure security, speed, and consistency across banks and systems.</p><p>For developers, it’s not just about writing code -it’s about knowing how money moves behind the scenes helps you build better, more compliant, and scalable systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7572a2892e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a Scalable and Secure Banking System for Millions of Transactions]]></title>
            <link>https://medium.com/@mankarpunam35/designing-a-scalable-and-secure-banking-system-for-millions-of-transactions-a2fee19cfe0c?source=rss-414836c9f53c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2fee19cfe0c</guid>
            <dc:creator><![CDATA[Punam Mankar]]></dc:creator>
            <pubDate>Fri, 04 Apr 2025 19:00:08 GMT</pubDate>
            <atom:updated>2025-04-05T03:19:33.106Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In today’s digital age, <strong>banking</strong> <strong>systems</strong> must be not only fast but also secure, reliable, and scalable to handle millions of transactions daily. One effective approach to achieving these goals is through a <strong>microservices</strong> <strong>architecture -</strong>an architectural style that structures an application as a collection of small, autonomous services, each implementing a specific business capability. This modular approach enhances <strong>flexibility</strong>, <strong>scalability</strong>, and <strong>resilience</strong> in complex systems.</blockquote><p>In this article, I’ll walk through a high-level architecture for designing a modern banking system that can handle massive transaction loads while ensuring data security and system integrity.</p><h3><strong>1. Architecture</strong></h3><p>A <strong>microservices based</strong> architecture with an <strong>event-driven design</strong> ensures high scalability and resilience. The key components are:</p><h4>Core Components</h4><p><strong>API Gateway: </strong>Serves as the single entry point for clients, handling authentication, authorization, rate limiting, and request routing.</p><p><strong>Authentication &amp; Authorization</strong>: OAuth 2.0, OpenID Connect (OIDC), JWT tokens for securing access.</p><p><strong>Transaction Service</strong>: Manages fund transfers, deposits, and withdrawals.</p><p><strong>Account Service</strong>: Maintains account details and balances.</p><p><strong>Fraud Detection Service</strong>: Uses AI/ML models to detect suspicious activities.</p><p><strong>Notification Service</strong>: Sends alerts and confirmations via email/SMS.</p><p><strong>Audit &amp; Compliance Service</strong>: Ensures adherence to banking regulations.</p><blockquote>These are just a few core services. In a full-scale banking system, there are many other supporting services like customer onboarding, KYC verification, payment gateway integration, reconciliation, reporting, analytics, and more -each with its own responsibility and importance.</blockquote><h4>Data Storage &amp; Consistency</h4><p><strong>Relational Databases (PostgreSQL/MySQL)</strong> for core banking transactions with strong ACID properties.</p><p><strong>NoSQL Databases (MongoDB/Cassandra)</strong> for high-throughput read operations, such as storing customer profiles and logs.</p><p><strong>Event Sourcing with Kafka</strong>: Ensures event-driven processing and eventual consistency.</p><p><strong>Caching (Redis, Memcached)</strong>: Reduces load on databases for frequently accessed data.</p><h4>Scalability Considerations</h4><p><strong>Load Balancing</strong>: HAProxy, Nginx, or cloud-based solutions (AWS ALB, GCP Load Balancer).</p><p><strong>Auto-scaling</strong>: Kubernetes-based scaling of microservices.</p><p><strong>Sharding &amp; Replication</strong>: Distribute transaction data across multiple nodes.</p><h3>2. Security Measures</h3><h4>Authentication &amp; Authorization</h4><p><strong>OAuth 2.0 and OpenID Connect</strong> for secure user authentication.</p><p><strong>MFA (Multi-Factor Authentication)</strong> for additional security layers.</p><p><strong>Role-Based Access Control (RBAC) &amp; Attribute-Based Access Control (ABAC) </strong>or granular access control.</p><h4>Data Security</h4><p><strong>Encryption</strong>: TLS for data in transit, AES-256 for data at rest.</p><p><strong>Tokenization</strong>: Masking sensitive information such as card numbers.</p><h4>Fraud Detection &amp; Anomaly Detection</h4><p><strong>Machine Learning Models</strong>: Monitor transaction patterns in real-time.</p><p><strong>Rule-Based Detection</strong>: Alert for unusual transaction behaviors.</p><p><strong>Geofencing &amp; Device Fingerprinting</strong>: Detect fraudulent access attempts.</p><h4>Compliance &amp; Audit Logging</h4><p><strong>Regulatory Compliance</strong>: GDPR, PCI-DSS, PSD2 compliance.</p><p><strong>Immutable Audit Logs</strong>: Store transaction history securely.</p><p><strong>SIEM (Security Information and Event Management)</strong>: Real-time monitoring and alerts.</p><h3>3. High Availability &amp; Fault Tolerance</h3><p><strong>Active-Active Architecture</strong>: Ensure zero downtime.</p><p><strong>Geo-Replication</strong>: Disaster recovery across multiple regions.</p><p><strong>Failover Mechanisms</strong>: Automated failover in case of system failure.</p><p><strong>Circuit Breaker Patterns (e.g., Resilence4j, Retry, BulkHead)</strong>: Prevent cascading failures.</p><h3>4. Performance Optimization</h3><p><strong>Asynchronous Processing</strong>: Using Kafka for event-driven transaction handling.</p><p><strong>Database Indexing &amp; Query Optimization</strong>: To improve read/write efficiency.</p><p><strong>CDN (Content Delivery Network)</strong>: Optimized static content delivery.</p><h3>5. Observability &amp; Monitoring</h3><p><strong>Distributed Tracing (Jaeger, OpenTelemetry)</strong>: Track transactions across services.</p><p><strong>Metrics &amp; Logs (Prometheus, ELK Stack)</strong>: Real-time monitoring of system health.</p><p><strong>Automated Incident Response</strong>: Alerting via PagerDuty or Slack.</p><p><em>Building a scalable and secure banking platform is a complex but solvable challenge. With the right architecture, you can support millions of transactions per day, stay compliant, protect sensitive data, and deliver a seamless experience to users</em>.</p><blockquote>If you’re working on a similar system or modernizing your banking stack, I’d love to hear how you’re approaching it. Drop a comment or DM me on <a href="http://linkedin.com/in/punam-mankar-04286271">LinkedIn</a>!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2fee19cfe0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build your Application with Spring Boot and LLM Model(Ollama)]]></title>
            <link>https://medium.com/@mankarpunam35/build-your-application-with-spring-boot-and-llm-model-ollama-fa8aeba68904?source=rss-414836c9f53c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa8aeba68904</guid>
            <dc:creator><![CDATA[Punam Mankar]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 06:07:22 GMT</pubDate>
            <atom:updated>2024-11-18T06:07:22.845Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U-VGBGvW2gez718L7-pP0A.jpeg" /></figure><p>In today’s AI-driven world, large language models (LLMs) are transforming the way applications interact with users. From chatbots to recommendation engines, AI models enhance the responsiveness and intelligence of applications. While these models are powerful, they often come with privacy concerns, especially for organizations handling sensitive data. This article explores <strong>Llama AI</strong>, an open-source language model developed by Meta, which stands out due to its flexibility, customizability, and suitability for private deployments. By running Llama models locally or in private cloud environments, businesses can integrate AI while maintaining data security.</p><h4><strong>Overview of the Article</strong></h4><p>In this guide, I’ll introduce you to <strong>Llama AI</strong> and its unique capabilities, followed by how to use <strong>Ollama</strong>, a platform that facilitates local deployment of Llama models. Finally, you’ll learn how to integrate these models into a <strong>Spring Boot application</strong> for building secure, AI-powered solutions.</p><h4><strong>What is Llama AI?</strong></h4><p>Llama AI, created by Meta, is a powerful type of language model that stands out because it’s open-source. Unlike other large language models, which are usually locked to specific platforms or are private, Llama is fully accessible for everyone. This open approach allows developers and companies to download, customize, and use Llama models on their own servers or private cloud environments.</p><p>Organizations often deal with sensitive, private, or confidential data, making data security a top priority. Many prefer not to use cloud-based AI models for handling this information, as it can pose potential risks to data privacy. Instead, they want the flexibility to run and train AI models within their own infrastructure, whether on-premises or on their private cloud servers.</p><p>For such cases, <strong>Llama</strong> is an excellent solution. Llama’s models are designed for deployment on local machines or private servers, allowing organizations to build and run AI applications securely, without needing to rely on external cloud-based models. This approach ensures that data remains within the organization’s control, adhering to privacy policies and compliance requirements.</p><h4><strong>Features of Llama AI</strong></h4><ul><li><strong>Open-Source Accessibility</strong>: Llama’s open-source nature allows users to download and modify the model, making it highly accessible for experimentation, customization, and deployment across different environments. Organizations don’t need to rely on a third-party cloud provider, which is crucial for data-sensitive applications.</li><li><strong>Customizability and Fine-Tuning</strong>: Since Llama models can be fine-tuned with specific data, they can be adapted to specialized needs. This capability is ideal for businesses wanting to tailor the model’s responses, tone, and accuracy to fit their brand or specific use cases.</li><li><strong>Flexibility for On-Premises Deployment</strong>: Unlike models that require external cloud-based APIs, Llama’s models can be run locally. This flexibility allows for private and secure deployment, with complete control over data and infrastructure. Organizations can integrate Llama into their own servers, keeping data within their control to meet strict privacy or regulatory standards.</li><li><strong>Scalability Across Different Model Sizes</strong>: Llama offers models in various sizes, from smaller ones suitable for fast, real-time applications to larger models capable of handling more complex language tasks. This scalability allows developers to select a model size that matches their hardware capabilities and project needs.</li><li><strong>Optimization for Resource Efficiency</strong>: Llama has been engineered to be relatively resource-efficient compared to other large language models. It is optimized to run on fewer computing resources without sacrificing performance, making it a good option for teams with limited hardware or for edge deployments.</li></ul><h4><strong>Specific Models in the Llama Family</strong></h4><p>LLaMA, Llama 2, Code Llama, Llama 3, Llama 3.1, Llama 3.2</p><p>Each model in the Llama family adds new capabilities, making the progression from LLaMA to Llama 3.2.</p><h4>What is Ollama?</h4><p><strong>Ollama</strong> is a platform designed to help developers and organizations run large language models, including open-source models like <strong>Llama</strong> by Meta, on their own machines or private servers. In contrast to typical cloud-based AI services, Ollama provides a framework for managing and deploying language models locally, offering enhanced privacy, control, and flexibility.</p><p>With Ollama, you can easily integrate language models into your existing applications while keeping your data within your infrastructure. This approach is especially beneficial for companies with strict data security requirements, as it minimizes exposure to third-party services.</p><h4>Setting Up Ollama in Spring Boot</h4><ol><li>Install the <a href="https://ollama.com/download">ollama</a> libraries or SDKs for Llama AI.</li><li>We are using <a href="https://ollama.com/library/llama3.2">llama3.2</a> 3b copy the command ollama run llama3.2 and run on terminal.</li><li>Create a Spring Boot project using <a href="https://start.spring.io/">Spring Initializr</a>.</li><li>Add dependencies for Ollama.</li></ol><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-ai-ollama-spring-boot-starter&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>5. Add model in Spring Boot Configuration</p><pre>spring.ai.ollama.chat.options.model=llama3.2</pre><p>6. Building a Controller for API .</p><p>Add ChatModel which will have only one implementation OllamaChatModel.</p><pre>@RestController<br>public class SpringAIController {<br>    private final ChatModel chatModel;<br><br>    public SpringAIController(ChatModel chatModel) {<br>        this.chatModel = chatModel;<br>    }<br><br>    @GetMapping(&quot;/prompt&quot;)<br>    public String promt(@RequestParam String message) {<br><br>        return chatModel.call(message);<br>    }<br><br>}</pre><p>7: Testing Your Application from a Browser</p><p><a href="http://localhost:8080/prompt?message=%22who%20are%20you%22">http://localhost:8080/prompt?message=”who</a> are you”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I22IYS8zSBToNrR8OKApIg.jpeg" /></figure><h4><strong>Additional Resources</strong></h4><p><a href="https://github.com/facebookresearch/llama"><strong>Llama AI Documentation</strong></a>: Official repository and documentation for understanding and using Llama AI.</p><p><a href="https://spring.io/projects/spring-boot"><strong>Spring Boot Documentation</strong></a>: Learn more about creating and managing Spring Boot applications.</p><p><a href="https://docs.spring.io/spring-ai/reference/api/chat/ollama-chat.html#https://ollama.com/download"><strong>Spring AI with Olama</strong></a><strong>:</strong> Official guide to integrating AI functionalities into Spring Boot applications.</p><p><a href="https://ollama.com/library/llama3.2:3b"><strong>Ollama Library</strong></a>: Explore the details of the Llama model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa8aeba68904" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with AI in Spring Boot]]></title>
            <link>https://medium.com/@mankarpunam35/getting-started-with-ai-in-spring-boot-6fa9d7e0645e?source=rss-414836c9f53c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fa9d7e0645e</guid>
            <dc:creator><![CDATA[Punam Mankar]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 09:33:51 GMT</pubDate>
            <atom:updated>2024-11-11T19:17:10.603Z</atom:updated>
            <content:encoded><![CDATA[<p>In recent years, artificial intelligence (AI) has changed how apps interact with people and handle information. We now see AI everywhere — from chatbots and virtual assistants to recommendation engines and content generation. As AI becomes more popular in application development, more businesses and developers are seeing how it can make their apps smarter, more responsive, and better at engaging users.</p><p>But while AI offers a lot of potential, adding it to applications hasn’t always been easy. Integrating AI models has usually required specialized machine learning knowledge, which can be a barrier for many developers. Thankfully, the <strong>Spring AI</strong> project is making this easier. It brings AI to <strong>Spring Boot</strong>, one of the most widely-used Java frameworks for building robust applications.</p><p>With Spring AI, developers can quickly add advanced AI models — like those from OpenAI — into their Spring Boot projects. OpenAI’s language models are known for generating text, analyzing emotions, and even creating new content. Spring AI simplifies the setup and connection to these models, so Java developers can start building AI-powered features without needing deep ML expertise. This opens up new possibilities for Spring Boot applications to become smarter and more interactive with minimal setup.</p><p>In this article, we’ll explore how to set up Spring AI with OpenAI in a Spring Boot project to start building AI-enhanced applications.</p><h4>Introduction to Spring AI</h4><p>Spring AI is a powerful framework that simplifies the process of integrating generative artificial intelligence or GAI functionalities into your Java applications. It acts as a bridge eliminating the complexities of directly integrating with various and multiple GAI models and enabling you to leverage their capabilities within your Java code base.</p><p>What is generative AI? Generative AI or GAI refers to a subfield of artificial intelligence focused on creating new content such as texts, images or code. These models are trained on massive data sets and can learn to generate realistic and creative outputs based on the information they have been exposed to.</p><p>Spring AI exposes high level functionalities like chat completion, text to image generation and embedding models. You can focus on the business logic of your application without getting bogged down in the underlying complexities. So why should you use Spring AI? Spring AI is great for Java developers who want to leverage GAI functionalities within their applications without extensive GAI expertise. You can build AI-powered features such as chatbots, creative content generation tools or data analysis applications or you can simplify integration with various GAI providers and maintain flexibility in their technology stack.</p><h4>Setting Up the Spring Boot Project with Spring OpenAI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4DlNOO7zlIo2yT3iXskxTg.jpeg" /></figure><ol><li>Create a Spring Boot project using <a href="https://start.spring.io/">Spring Initializr</a>.</li><li>Add essential dependencies for Spring OpenAI , Spring Web etc.</li></ol><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br> &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-ai-openai-spring-boot-starter&lt;/artifactId&gt;<br> &lt;/dependency&gt;</pre><h3>Configuring OpenAI in Spring AI</h3><p>To use OpenAI’s powerful language models in our Spring Boot project, we first need to configure access to OpenAI’s API.</p><p><strong>Step 1: Get Your OpenAI API Key</strong></p><p>First, you’ll need an API key from OpenAI. If you don’t already have one, you can get it by creating an OpenAI account and navigating to their <a href="https://platform.openai.com/account/api-keys">API key generation page</a>. Once you’ve signed up and logged in, you can generate a new API key. Copy this key — you’ll need it in the next step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ISLMqXy64XTRF1Ny0HoyfA.jpeg" /></figure><p><strong>Step 2: Add the API Key to Your Spring Boot Configuration</strong></p><p>With your API key in hand, you can now configure it in your Spring Boot project. This key needs to be securely stored so that our application can use it to connect with OpenAI. In your project’s application.properties or application.yml file, add the following line:</p><p>For <strong>application.properties</strong>:</p><pre>spring.ai.openai.api-key=your_openai_api_key<br>spring.ai.openai.model=gpt-3.5-turbo</pre><p>For <strong>application.yml</strong>:</p><pre>spring:<br>  ai:<br>    openai:<br>      api-key: your_openai_api_key<br>      model: gpt-3.5-turbo</pre><p><strong>Building an API Endpoint:</strong></p><p>Here we can call this prompt using direct call method from ChatModel or manually.</p><p><strong>With Call method:</strong></p><pre>package com.spring.ai.demo.test.controller;<br><br><br>import org.springframework.ai.chat.model.ChatModel;<br>import org.springframework.beans.factory.annotation.Autowired;<br><br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RequestParam;<br>import org.springframework.web.bind.annotation.RestController;<br><br><br>@RestController<br>public class AIController {<br>    @Autowired<br>    ChatModel chatModel;<br><br>    @GetMapping(&quot;/prompt&quot;)<br>    public String prompt(@RequestParam String message){<br>       return chatModel.call(message);<br>    }<br>}</pre><p><strong>Example of Setting the Request Body Manually:</strong></p><pre>package com.spring.ai.demo.test.controller;<br><br><br>import org.springframework.ai.chat.model.ChatModel;<br>import org.springframework.beans.factory.annotation.Autowired;<br><br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.http.*;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RequestParam;<br>import org.springframework.web.bind.annotation.RestController;<br>import org.springframework.web.client.RestTemplate;<br><br>@RestController<br>public class AIController {<br><br><br>    @Autowired<br>    private RestTemplate restTemplate;<br><br>    @Value(&quot;${spring.ai.openai.api-key}&quot;)<br>    String apiKey;<br><br>    @Autowired<br>    ChatModel chatModel;<br><br>    @GetMapping(&quot;/prompt&quot;)<br>    public String prompt(@RequestParam String message){<br><br>        String url = &quot;https://api.openai.com/v1/chat/completions&quot;;<br>        String body = String.format(<br>                &quot;{\&quot;model\&quot;: \&quot;gpt-3.5-turbo\&quot;, \&quot;messages\&quot;: [{\&quot;role\&quot;: \&quot;user\&quot;, \&quot;content\&quot;: \&quot;%s\&quot;}]}&quot;,<br>                message.replace(&quot;\&quot;&quot;, &quot;\\\&quot;&quot;)  <br>        );<br>        HttpHeaders headers = new HttpHeaders();<br>        headers.set(&quot;Authorization&quot;, &quot;Bearer &quot; + apiKey);<br>        headers.setContentType(MediaType.APPLICATION_JSON);<br>        HttpEntity&lt;String&gt; request = new HttpEntity&lt;&gt;(body, headers);<br><br>        try {<br>            ResponseEntity&lt;String&gt; response = restTemplate.exchange(url, HttpMethod.POST, request, String.class);<br>            return response.getBody();<br>        } catch (Exception e) {<br>            return &quot;Error occurred: &quot; + e.getMessage();<br>        }<br>    }<br><br><br>}</pre><p><strong>Output with Call():</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a-HOodNJKmiDEwQAgvZ_Jw.jpeg" /><figcaption>Call() with OpenAI</figcaption></figure><p><strong>Output With Setting the Request Body Manually:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vvhyvf1feyO40FJE2hDdYA.jpeg" /><figcaption>Manually calling the OpenAI</figcaption></figure><p>Just a heads-up: To get a response from AI, you’ll need to add some funds — it’s not free.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fa9d7e0645e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Authentication and Authorization: A Developer’s Guide]]></title>
            <link>https://medium.com/@mankarpunam35/understanding-authentication-and-authorization-a-developers-guide-b249533d918e?source=rss-414836c9f53c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b249533d918e</guid>
            <dc:creator><![CDATA[Punam Mankar]]></dc:creator>
            <pubDate>Wed, 07 Aug 2024 03:03:51 GMT</pubDate>
            <atom:updated>2024-08-07T03:03:51.623Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s tech interviews, questions about authentication and authorization protocols can easily trip up developers. While we often know how to implement these concepts in our projects, explaining them succinctly and clearly can be challenging.</p><p>This article aims to provide a comprehensive overview of authentication and authorization, their differences, and the protocols commonly used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3TddahG0hzcR5blvDImT_A.jpeg" /></figure><h4>What is Authentication?.</h4><p>Authentications is the process of verifying the identify the user, system or entity etc. attempting to access the particular resources or service. In the context of computer security and information technology, authentication ensure that the entity requesting the access is who it claim to be.</p><h3>Types of Authentication</h3><h4><strong>Password Authentication:</strong></h4><p>This is the common form of authentication where the user provide the username and unique password. The system compares the provided information with stored credentials to authenticate the user.</p><h4>Multi-Factor authentication(MFA):</h4><p>MFA add the extra layer of security by requiring the user to provide the more than one form of identification. This could include a combinations that user knows (like a password), something the user has (such as a smart card or token), and something the user is (such as biometric data like a fingerprint).</p><h4>Certificate based authentication:</h4><p>The digital certificate are used to verify the identity of entity. This is common in secure the communication over a network such as HTTP.</p><h4>Biometric authentication:</h4><p>This method involves using the unique physical or behavioural characteristic of an individuals such as fingerprint, facial recognition and voice recognition etc. to verify the identity.</p><h4>Token Based authentication:</h4><p>This methods involves the use of tokens such as JWT tokens for authenticating the users and user logs in and upon successful authentication they received the token with that token user access the protected resources.</p><h4>OAuth and OpenID Connect authentication:</h4><p>OAuth is used for authorization, allowing a user to grant third-party applications limited access to their resources. OpenID Connect is built on top of OAuth and provides authentication services.</p><h4><strong>What is Authorization?.</strong></h4><p>Authorization is the process of determining whether an authenticated user has the right to access specific resources or perform certain actions.</p><h4>Authorization Methods:</h4><ol><li><strong>Role Based Access Control(RBAC):</strong> Assign the permissions based on the user’s role within the organisation.</li><li><strong>Attribute Based Access Control (ABAC): </strong>Grant the access based on attributes.</li><li><strong>Access Control List(ACLs): </strong>Specify the individual permissions for each user or group or users.</li></ol><h3>Differences Between Authentication and Authorization</h3><ul><li><strong>Authentication:</strong> Confirms identity. It’s about validating credentials like usernames and passwords.</li><li><strong>Authorization:</strong> Confirms permissions. It’s about verifying what an authenticated user is allowed to do.</li></ul><h3>Authentication Protocols</h3><p>Authentication protocol provides the set of rules that allows the system the to verify the identity of an endpoint (laptop, desktop, phone, server, etc.) or a user.</p><h4>Password Authentication Protocol (PAP)</h4><p>Password Authentication protocol is least secure protocol to authenticate the user because it is not encrypted. This is the login process that requires the username or password combination to access the specified system and verify the provided credentials with user directory.</p><h4>Challenge Handshake Authentication Protocol (CHAP)</h4><p>CHAP is authentication protocol that uses the three-way exchange to authenticate the users, verifying their identity with strong encryption. First device send the request to remote system , second remote system send the response using cryptographic hash function and third local system checks if the hash value of matches the expected response. If it matches it establish the connection otherwise it close the connection.</p><h4>OAuth</h4><p>Delegates the access control for web, mobile and desktop applications. allows the third party service to exchange the information on behalf of user. In simple terms OAuth is protocol that let you give the website or app permission to use your information without giving their password .</p><h4>OpenID Connect (OIDC)</h4><p>OpenID is simple layer built on the top of OAuth2.0 protocol. It allows the client to verify the identity of end-user based on the authentication performed by an authorization server, as well as obtain the basic profile information about the user.</p><h4>SAML (Security Assertion Markup Language)</h4><p>SAML is an open standard that allows the application developer to implement the single sign on (SSO). Secure exchange of authentication and authorization data between parties. It provides standardised and secure protocol, based on XML it allows application to transfer authentication and authorization data between them.</p><h4>JSON Web Token (JWT)</h4><p>JWT is an open standard used to create compact, self-contained tokens used for securely transmitting information between different applications. These tokens are typically used for authentication and authorization, as they can contain information that verify the identity of a user and their permissions.</p><h4>Lightweight Directory Access Protocol (LDAP)</h4><p>LDAP is a protocol is used to access and manage the directory services over a network. Directory service stores and organize the information about users, devices, applications and other resources in hierarchical structure, making it easy to retrieve and manage this information.</p><ul><li><strong>Directory Service Protocol:</strong> LDAP is specifically designed to work with directory services, which are optimized for read-heavy operations and are structured in a hierarchical format.</li><li><strong>Centralized Management:</strong> It allows for centralized management of user information, which can be accessed by different applications and services.</li><li><strong>Authentication and Authorization:</strong> LDAP is commonly used for both authentication (verifying user identity) and authorization (determining access rights).</li></ul><h4>Extensible Authentication Protocol (EAP)</h4><p>EAP support the different type of authentication, from one-time password to smart card. EAP is highly secure for wireless communications because it allows the remote device to perform mutual authentication using built-in encryption. Using EAP all the communications are encrypted. user connect to access point, requesting for credentials, verifying their identity through authentication server and then requesting a userID through the server to verify again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b249533d918e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Exploring Spring WebFlux: CRUD Examples Using WebClient for Reactive Programming”]]></title>
            <link>https://medium.com/@mankarpunam35/exploring-spring-webflux-examples-using-webclient-for-reactive-programming-058fed513050?source=rss-414836c9f53c------2</link>
            <guid isPermaLink="false">https://medium.com/p/058fed513050</guid>
            <dc:creator><![CDATA[Punam Mankar]]></dc:creator>
            <pubDate>Fri, 19 Jul 2024 04:27:56 GMT</pubDate>
            <atom:updated>2024-07-19T20:00:59.396Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Spring WebFlux is a part of the Spring Framework that provides support for building reactive web applications. It offers a non-blocking, reactive programming model suitable for highly scalable applications. One of the core components of Spring WebFlux is the WebClient, which is a non-blocking, reactive client to perform HTTP requests.</blockquote><p>Here are some examples to understand when working with Spring WebFlux and WebClient.</p><p>GET API Example:</p><p>Generally, we will use GET API to fetch either a collection of resources or a singular resource. Let’s see the example of both use cases using get() method calls.</p><ul><li>HTTP GET /students : collection of students as Flux</li><li>HTTP GET /students/{id} : single student by id as Mono</li></ul><pre>import org.springframework.stereotype.Service;<br>import org.springframework.web.reactive.function.client.WebClient;<br>import reactor.core.publisher.Flux;<br>import reactor.core.publisher.Mono;<br><br>@Service<br>public class StudentService {<br><br>  private final WebClient webClient;<br><br>  public MyService(WebClient webClient) {<br>    this.webClient = webClient;<br>  }<br><br>  public Flux&lt;Student&gt; getAllStudents() {<br><br>    return webClient.get()<br>      .uri(&quot;/students&quot;)<br>      .retrieve()<br>      .onStatus(httpStatus -&gt; !httpStatus.is2xxSuccessful(),<br>              clientResponse -&gt; handleErrorResponse(clientResponse.statusCode()))<br>      .bodyToFlux(Student.class)<br>      .onErrorResume(Exception.class, e -&gt; Flux.empty());<br>  }<br><br>  public Mono&lt;Student&gt; getStudentById(int id) {<br>    return webClient.get()<br>            .uri(&quot;/students/{id}&quot;, id)<br>            .retrieve()<br>            .onStatus(httpStatus -&gt; !httpStatus.is2xxSuccessful(),<br>                    clientResponse -&gt; handleErrorResponse(clientResponse.statusCode()))<br>            .bodyToMono(Student.class);<br>  }<br><br>  private Mono&lt;? extends Throwable&gt; handleErrorResponse(HttpStatus statusCode) {<br>    return Mono.error(new StudentServiceException(&quot;Failed to fetch students. Status code: &quot; + statusCode));<br>  }<br>}</pre><p>POST ,PUT and DELETE API Example:</p><ul><li>HTTP POST /students : creates a new student from the request body and returns the created student in response.</li></ul><pre>@Service<br>public class StudentService {<br><br>  private final WebClient webClient;<br><br>  @Autowired<br>  public StudentService(WebClient webClient) {<br>      this.webClient = webClient;<br>  }<br><br>  public Mono&lt;ResponseEntity&lt;Student&gt;&gt; createStudent(Student newStudent) {<br><br>    return webClient.post()<br>      .uri(&quot;/students&quot;)<br>      .body(Mono.just(newStudent), Student.class)<br>      .retrieve()<br>      .onStatus(HttpStatus::is4xxClientError, response -&gt; {<br>        return Mono.error(new WebClientResponseException<br>          (&quot;Bad Request&quot;, response.statusCode().value(), null, null, null));<br>      })<br>      .onStatus(HttpStatus::is5xxServerError, response -&gt; {<br>        return Mono.error(new WebClientResponseException<br>          (&quot;Server Error&quot;, response.statusCode().value(), null, null, null));<br>      })<br>      .toEntity(Student.class);<br>  }<br><br>}</pre><ul><li>HTTP PUT /students/{id} : updates an existing student data from the request body and returns the updated student in response.</li></ul><pre>public Mono&lt;Student&gt; updateStudent(Student updateStudent) {<br>  return webClient.put()<br>    .uri(&quot;/students/{id}&quot;, updateStudent.getId())<br>    .body(Mono.just(updateStudent), Student.class)<br>    .retrieve()<br>    .onStatus(HttpStatus::is4xxClientError, clientResponse -&gt; handleClientError(clientResponse))<br>    .onStatus(HttpStatus::is5xxServerError, clientResponse -&gt; handleServerError(clientResponse))<br>    .bodyToMono(Student.class);<br>  }<br><br>  private Mono&lt;? extends Throwable&gt; handleClientError(ClientResponse clientResponse) {<br>  return Mono.error(new StudentNotFoundException(&quot;Student not found&quot;));<br>  }<br><br>  private Mono&lt;? extends Throwable&gt; handleServerError(ClientResponse clientResponse) {<br>  return Mono.error(new RuntimeException(&quot;Server error&quot;));<br>}</pre><ul><li>HTTP DELETE /students/{id} : deletes an existing student by its ID. It does not accept any request body as well as does not return any response body as well.</li></ul><pre>public Mono&lt;Void&gt; deleteStudent(Integer id) {<br>  return webClient.delete()<br>    .uri(&quot;/students/&quot; + id)<br>    .retrieve()<br>    .onStatus(HttpStatus::is4xxClientError, clientResponse -&gt; handleClientError(clientResponse))<br>    .onStatus(HttpStatus::is5xxServerError, clientResponse -&gt; handleServerError(clientResponse))<br>    .bodyToMono(Void.class);<br>}<br><br>private Mono&lt;? extends Throwable&gt; handleClientError(ClientResponse clientResponse) {<br>    return Mono.error(new StudentNotFoundException(&quot;Student not found&quot;));<br>}<br><br>private Mono&lt;? extends Throwable&gt; handleServerError(ClientResponse clientResponse) {<br>    return Mono.error(new RuntimeException(&quot;Server error&quot;));<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=058fed513050" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive Programming with Spring WebFlux]]></title>
            <link>https://medium.com/@mankarpunam35/spring-webflux-b82c735f98db?source=rss-414836c9f53c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b82c735f98db</guid>
            <dc:creator><![CDATA[Punam Mankar]]></dc:creator>
            <pubDate>Fri, 19 Jul 2024 03:16:55 GMT</pubDate>
            <atom:updated>2024-07-19T04:20:03.598Z</atom:updated>
            <content:encoded><![CDATA[<p>Spring WebFlux, has been added to <strong><em>Spring 5</em></strong>. Spring WebFlux is framework within spring ecosystem designed for building the reactive web application. It allows you to handling the asynchronous request in non-blocking manner. Spring WebFlux uses project reactor as the reactive library.</p><h4><strong>Features</strong></h4><p><strong>1. Reactive Programming Model:</strong></p><p>Spring WebFlux is based on reactive programming that promotes an asynchronous, non-blocking, event-driven approach to data processing. It allows us to handle large number of concurrent requests with fewer thread.</p><p><strong>2. Non-blocking I/O:</strong></p><p>Utilizes the non-blocking I/O, which helps in improving the scalability and performance.</p><p><strong>3. Functional Endpoint:</strong></p><p>Beside the traditional annotation based approach. Spring WebFlux also supports the functional endpoint declaration using Java8 lambda and method reference.</p><p><strong>4. Streaming:</strong></p><p>Support the streaming of data, which is particularly useful for application requiring the real-time data processing.</p><p><strong>Spring WebFlux heavily uses two publishers :</strong></p><p>1 <strong>Mono:</strong> Return 0 or 1 elements.</p><pre>Mono&lt;String&gt; mono = Mono.just(&quot;Floya&quot;);<br>Mono&lt;String&gt; mono = Mono.empty();</pre><p>2 <strong>Flux: </strong>Return 0…N elements. A Flux can be endless, meaning that it can keep emitting elements forever.</p><pre>Flux&lt;String&gt; stringFlux = Flux.just(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;);<br>Flux&lt;String&gt; flux = Flux.fromArray(new String[]{&quot;A&quot;, &quot;B&quot;, &quot;C&quot;}); <br>Flux&lt;String&gt; flux = Flux.fromIterable(Arrays.asList(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;));<br>flux.subscribe();</pre><h4><strong>Components</strong></h4><p><strong>Router Function:</strong> Defines the routing of HTTP requests to handler functions in functional style.</p><p><strong>Handler Function: </strong>Processes the request and return the response in functional style</p><p><strong>WebClient: </strong>A non-blocking , reactive client to perform the HTTP requests, replacing the RestTemplate for reactive application.</p><p><strong>Server-Sent Events(SSE): </strong>Supports the server sent event for real time, server to client communication.</p><p><strong>Data Access: </strong>Integrates with reactive libraries like R2DBC for database access and Spring Data Reactive repositories.</p><p>Here’s a simple example of how to define a router function and a handler function:</p><p>We define a route /numbers that maps to the streamNumbers method in the Handler class.</p><pre>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.web.reactive.function.server.RouterFunction;<br>import org.springframework.web.reactive.function.server.ServerResponse;<br>import static org.springframework.web.reactive.function.server.RequestPredicates.GET;<br>import static org.springframework.web.reactive.function.server.RouterFunctions.route;<br><br>@Configuration<br>public class Config{<br>  @Bean<br>  public RouterFunction&lt;ServerResponse&gt; request(Handler handler){<br>        return route(GET(&quot;/numbers&quot;), handler::streamNumbers);<br>  }<br>}</pre><p>The streamNumbers method creates a Flux&lt;Long&gt; that emits a long value every second (Flux.interval(Duration.ofSeconds(1))).</p><pre>import org.springframework.stereotype.Component;<br>import org.springframework.web.reactive.function.server.ServerResponse;<br>import reactor.core.publisher.Mono;<br>import reactor.core.publisher.Flux;<br><br>@Component<br>public class Handler{<br>  public Mono&lt;ServerResponse&gt; streamNumbers(ServerRequest request){<br>      Flux&lt;Long&gt; numberFlux = Flux.interval(Duration.ofSeconds(1)).take(10);<br>      return ServerResponse.ok().bodyValue(numberFlux,Long.class);<br>  }<br>}</pre><p><strong>Example of using WebClient</strong></p><p>First, add the necessary dependencies to your pom.xml if they are not already present:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-webflux&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>configure a WebClient bean in your Spring configuration:</p><pre>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.web.reactive.function.client.WebClient;<br><br>@Configuration<br>public class WebClientConfig {<br><br>    @Bean<br>    public WebClient webClient() {<br>        return WebClient.builder()<br>                .baseUrl(&quot;http://api.example.com&quot;)<br>                .build();<br>    }<br>}</pre><p><strong>Using WebClient to make request</strong></p><p>Below is an example of a service that uses WebClient to fetch data from an external API.</p><pre>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.stereotype.Service;<br>import org.springframework.web.reactive.function.client.WebClient;<br>import reactor.core.publisher.Mono;<br><br>@Service<br>public class TestService {<br><br>    private final WebClient webClient;<br><br>    @Autowired<br>    public TestService(WebClient webClient) {<br>        this.webClient = webClient;<br>    }<br><br>    public Mono&lt;String&gt; getData() {<br>        return webClient.get()<br>                .uri(&quot;/data&quot;)<br>                .retrieve()<br>                .bodyToMono(String.class);<br>    }<br>}</pre><p><strong>Controller to handle the request:</strong></p><pre>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RestController;<br>import reactor.core.publisher.Mono;<br><br>@RestController<br>public class TestController {<br><br>    private final TestService testService;<br><br>    @Autowired<br>    public TestController(TestService testService) {<br>        this.testService = testService;<br>    }<br><br>    @GetMapping(&quot;/fetch-data&quot;)<br>    public Mono&lt;String&gt; fetchData() {<br>        return testService.getData();<br>    }<br>}</pre><p><strong>Server-Sent-Events example:</strong></p><p>In the server side, expose a SSE endpoint is easy. Set the content type to text/event-stream, and produces a Flux stream in the response body.</p><pre>@GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE)<br>public Flux&lt;Post&gt; sse() {<br>    return Flux.interval(Duration.ofSeconds(1))<br>           .map(seq -&gt; &quot;SSE - &quot; + LocalTime.now().toString());<br>}</pre><p>There is no special client to consume SSE APIs, like interacting with RESTful APIs. set Accept header to text/event-stream to consume SSE events.</p><pre>client.get()<br>    .uri(&quot;messages&quot;)<br>    .accept(MediaType.TEXT_EVENT_STREAM)<br>    .retrieve()<br>    .bodyToFlux(Message::class.java)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b82c735f98db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Interview Insights: String, StringBuffer, StringBuilder Explained]]></title>
            <link>https://medium.com/@mankarpunam35/java-interview-insights-string-stringbuffer-stringbuilder-explained-fbba1a614cde?source=rss-414836c9f53c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbba1a614cde</guid>
            <dc:creator><![CDATA[Punam Mankar]]></dc:creator>
            <pubDate>Tue, 16 Apr 2024 21:50:37 GMT</pubDate>
            <atom:updated>2024-04-16T21:50:37.444Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s understand the concept of String: String is immutable which means it cannot be changed. StringBuilder and StringBuffer are the mutable which means they can be changed. StringBuffer is thread safe and synchronised but String Builder is not thread safe. That’s why StringBuilder is faster than StringBuffer.</p><p>String concatenation (+) internally user the StringBuffer class to perform the action.</p><p>When we create a string using double quote like “Hello”, JVM first look for the String with same value in the String pool. If found it return the reference of String object from String pool. Otherwise it creates the String object in String pool.</p><p>When we create a String with new operator like</p><p>String s = new String(“Hello”);</p><p>JVM create the new String object in heap memory and literal “Hello” will be placed in String constant pool.</p><p><strong>General question asked by interviewer.</strong></p><p>How many object will created in below case?.</p><p><strong>Q 1. String s = ”Hello”;</strong></p><p>Ans: 1 (In String constant pool one object)</p><p><strong>Q 2. String s = new String(“Hello”) ;</strong></p><p>Ans: 2 (One object create in heap are and String constant pool.)</p><p><strong>Q 3. String s1= new String(“Hello”)</strong></p><p><strong>String s2= new String(“Hello);</strong></p><p><strong>String s3 = ”hello”;</strong></p><p><strong>String s4 = ”Hello”</strong></p><p>Ans: 3 (one object hello is in SCP ,s1 and s2 in heap area and s3 and s4 will reference to object in scp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*P7u5ewGLxi6ytST4X1UF7g.jpeg" /></figure><p>Q 4. <strong>String s = new String(“Welcome”);</strong></p><p><strong>s.concat(“Java”);</strong></p><p><strong>s = s.concat(“Tutorial”);</strong></p><p>Ans. 6. For each literal object should be placed in scp so, In SCP three object will be created “Welcome”, “Java” and “Tutorial”. In Heap area “Welcome” , WelcomeJava and “WelcomeTutorial” three object is created but as the s is referencing to “WelcomeTutorial” other two object will be eligible for garbage collection(“Welcome” and “WelcomeJava”).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*KxKEBLv04Dt2StYAECTIFw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbba1a614cde" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>