<?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 Minindu Bimsara Abeywardena on Medium]]></title>
        <description><![CDATA[Stories by Minindu Bimsara Abeywardena on Medium]]></description>
        <link>https://medium.com/@minindubim?source=rss-67f2f7be01d8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*zFHIz0rv42kltvwi</url>
            <title>Stories by Minindu Bimsara Abeywardena on Medium</title>
            <link>https://medium.com/@minindubim?source=rss-67f2f7be01d8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:36:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@minindubim/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[Software Reengineering: Breathing New Life into Aging Systems]]></title>
            <link>https://medium.com/@minindubim/software-reengineering-breathing-new-life-into-aging-systems-c0333ef34d4e?source=rss-67f2f7be01d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0333ef34d4e</guid>
            <dc:creator><![CDATA[Minindu Bimsara Abeywardena]]></dc:creator>
            <pubDate>Thu, 30 Apr 2026 17:15:11 GMT</pubDate>
            <atom:updated>2026-04-30T17:15:11.739Z</atom:updated>
            <content:encoded><![CDATA[<p>How to transform outdated software without starting from scratch: concepts, models, processes, and the future of reengineering</p><h3>Introduction</h3><p>Imagine inheriting a factory that has been running for 30 years. The machines still work, but they are held together with duct tape, run on obsolete fuel, and only two employees know how to operate them. Do you demolish the entire facility and build anew, or do you modernize what is already there? Software organizations face this exact dilemma every day.</p><p>Software reengineering is the systematic process of examining, restructuring, and reimplementing existing software to improve its quality, maintainability, and performance, without fundamentally changing its external behavior. It is one of the most critical disciplines in software evolution, and in an era where decades-old banking systems still process billions of dollars daily, it has never been more relevant.</p><p>This article explores what software reengineering means, the models and processes behind it, the role of reverse engineering, emerging tools, and where the field is heading in the age of AI.</p><h3>What is Software Reengineering?</h3><p>Software reengineering is not the same as rewriting software from scratch. It involves taking an existing system, often poorly documented, heavily patched, and written in outdated languages, and transforming it into a cleaner, more maintainable form that preserves its original functionality.</p><blockquote>Reengineering is the examination and alteration of a subject system to reconstitute it in a new form. — Chikofsky &amp; Cross, 1990</blockquote><p>The need arises when software becomes what practitioners call a <em>legacy system</em>: software that is difficult to change, expensive to maintain, and risky to extend. A study by the Standish Group found that over 70% of enterprise IT budgets are consumed by maintaining existing systems, leaving little room for innovation. Reengineering addresses this imbalance.</p><h3>Why not just rewrite?</h3><p>The instinct to “start clean” is understandable but dangerous. Netscape’s ill-fated decision to rewrite its browser from scratch in 2000, chronicled as one of the worst decisions in software history, took years and handed market dominance to competitors. Existing systems, however messy, contain years of business logic, edge-case handling, and institutional knowledge that is nearly impossible to fully recreate. Reengineering preserves this value while modernizing the vessel.</p><h3>Core Concepts and Models</h3><h3>The Reengineering Horseshoe Model</h3><p>The most widely cited framework for software reengineering is the <em>Horseshoe Model</em>, introduced by Arnold and Frakes. Visualized as an upside-down U, it describes a two-phase journey:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*r-E0CgjLmSSoxOZrhmlelw.png" /><figcaption><em>Horseshoe Model</em></figcaption></figure><p>On the left side of the horseshoe, you perform <strong>reverse engineering</strong>, moving upward from the existing source code to extract high-level abstractions like architecture diagrams, data models, and business rules. At the top of the arch sits the redesigned architecture. On the right side, you perform <strong>forward engineering</strong>, descending from those abstractions back down to a new, improved implementation.</p><p>The beauty of this model is that it acknowledges the existing system as the starting point of knowledge, not a throwaway artifact.</p><h3>The Three Levels of Reengineering</h3><p>Reengineering efforts typically operate at one of three levels of ambition:</p><p><strong>Code-level reengineering</strong> focuses on improving the source code itself, refactoring methods, renaming variables for clarity, removing duplication, and applying design patterns. Tools like SonarQube and IntelliJ’s refactoring engine operate at this level.</p><p><strong>Architecture-level reengineering</strong> restructures the high-level organization of the system, for example, decomposing a monolithic application into microservices, or separating business logic from presentation layers.</p><p><strong>Data reengineering</strong> addresses the underlying data structures and databases, normalizing schemas, migrating from flat files to relational databases, or moving to cloud-native storage solutions.</p><h3>The Reengineering Process</h3><p>A typical software reengineering project follows a structured process, though the exact steps vary by methodology. Below are the core phases:</p><p>Phase 1</p><p>Inventory Analysis : Catalog all software assets, assess business value, quality, and maintainability to prioritize candidates.</p><p>Phase 2</p><p>Document Restructuring : Recreate missing or outdated documentation by analyzing the existing code and behavior.</p><p>Phase 3</p><p>Reverse Engineering : Extract design artifacts such as class diagrams, sequence diagrams, and architecture models from the source.</p><p>Phase 4</p><p>Code Restructuring : Refactor the source code to improve readability, reduce complexity, and eliminate technical debt.</p><p>Phase 5</p><p>Data Restructuring : Modernize data schemas, migrate databases, and improve data model quality.</p><p>Phase 6</p><p>Forward Engineering : Implement the improved design, migrating functionality to modern platforms and languages.</p><h3>Reverse Engineering: Understanding Before Changing</h3><p>Reverse engineering is the analytical backbone of reengineering. It is the process of working backward from an existing implementation to recover its design and requirements. Think of it like an archaeologist reconstructing a civilization from its artifacts, rather than its written history.</p><p>In practice, reverse engineering involves static analysis (examining source code without running it), dynamic analysis (observing the system’s behavior at runtime), and architectural recovery (using clustering algorithms to identify subsystems).</p><p>Real-world example</p><p>The US Social Security Administration maintains COBOL systems from the 1960s that process over $1 trillion in payments annually. Reverse engineering tools were used to extract the business logic embedded in millions of lines of code before any modernization efforts could begin, a process that took years before a single line of new code was written.</p><p>A key output of reverse engineering is the <em>recovered architecture</em>: a high-level map of the system’s components and their relationships. This becomes the blueprint for all subsequent reengineering decisions.</p><h3>Tools and Techniques</h3><p>The reengineering tooling landscape has matured considerably. Modern practitioners draw on a rich ecosystem of tools:</p><h3>Static analysis and code quality</h3><p><strong><em>SonarQube Checkstyle PMD ESLint Pylint</em></strong></p><p>These tools scan source code to detect code smells, security vulnerabilities, and technical debt hotspots, helping teams decide where to focus reengineering efforts.</p><h3>Architecture recovery</h3><p><strong><em>Understand Lattix Structure101 CodeScene</em></strong></p><p>These tools visualize dependencies between modules, identify circular references, and help teams understand the true architecture, not the one that was intended, but the one that actually evolved.</p><h3>Automated refactoring</h3><p><strong><em>IntelliJ IDEA Eclipse Visual Studio Resharper</em></strong></p><p>Modern IDEs automate safe refactoring operations such as extracting methods, renaming symbols across an entire codebase, and introducing interfaces, tasks that would take days to perform manually.</p><h3>Migration platforms</h3><p>AWS Migration HubAzure MigrateMicro Focus</p><p>Cloud providers now offer dedicated platforms for migrating legacy workloads, including tools that can automatically translate COBOL or PL/I programs into Java or .NET equivalents.</p><h3>Challenges in Software Reengineering</h3><p>Despite its appeal, reengineering is not without significant challenges. The most common pitfall is <em>insufficient understanding</em> of the original system. When documentation is absent and original developers have long departed, reverse engineering becomes an exercise in archaeology, slow, expensive, and prone to misinterpretation.</p><p>Another major challenge is <em>testing coverage</em>. Reengineering is safest when backed by a comprehensive suite of automated tests that verify the system’s behavior before and after changes. Many legacy systems, however, were built before unit testing was standard practice, leaving teams to reengineer without a safety net.</p><p>Finally, there is the <em>organizational challenge</em>: reengineering requires sustained investment over months or years, and it is notoriously difficult to demonstrate progress to stakeholders when the external behavior of the system does not change. Building a business case for invisible improvements demands strong communication and clear metrics.</p><h3>Future Directions: AI-Assisted Reengineering</h3><p>The most transformative shift in software reengineering today is the integration of large language models and AI-assisted tools into the workflow. Systems like GitHub Copilot, Amazon Q Developer, and purpose-built tools are beginning to automate tasks that previously required deep human expertise.</p><p>AI can now generate documentation from undocumented code, suggest refactoring opportunities based on learned patterns, translate entire codebases from one language to another, and even propose architectural improvements based on static analysis of dependency graphs.</p><p>However, AI-assisted reengineering introduces new risks. Generated code can be plausible but subtly incorrect, especially when preserving the nuanced business logic embedded in legacy systems. The discipline of <em>human-in-the-loop reengineering</em>, where AI automates routine transformations while human engineers verify critical logic, is emerging as the practical model for the near term.</p><p>Looking further ahead, the convergence of program synthesis, formal verification, and AI promises a future where systems can be reengineered with mathematical guarantees of behavioral equivalence, transforming what is today an art form into an engineering science.</p><h3>Conclusion</h3><p>Software reengineering is one of the most economically significant activities in the technology industry. The systems that run our banks, hospitals, governments, and supply chains were not built for the modern world, and yet tearing them down is rarely an option.</p><p>By understanding the concepts, following structured processes, applying rigorous reverse engineering techniques, and embracing modern tooling, organizations can transform aging codebases into assets that will serve them for another generation. Reengineering is not the glamorous side of software development, but it may well be the most important.</p><blockquote>The best time to reengineer a system was ten years ago. The second best time is now.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0333ef34d4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Image Classification System with Survey123 (End-to-End Guide)]]></title>
            <link>https://medium.com/@minindubim/building-an-image-classification-system-with-survey123-end-to-end-guide-17e4a37e8b3b?source=rss-67f2f7be01d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/17e4a37e8b3b</guid>
            <dc:creator><![CDATA[Minindu Bimsara Abeywardena]]></dc:creator>
            <pubDate>Tue, 24 Mar 2026 05:23:26 GMT</pubDate>
            <atom:updated>2026-03-24T05:23:26.233Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/864/0*kqu0pSrswNjwrItK.png" /></figure><h3>1. Introduction</h3><p>Field data collection has evolved from manual note-taking to <strong>AI-powered real-time decision systems</strong>. One of the most powerful examples is integrating <strong>image classification directly into data collection workflows</strong> using <strong>ArcGIS Survey123</strong>.</p><p>This article explains a <strong>modern, production-ready approach</strong> to building an image classification system using Survey123 starting from training models to deploying them on mobile devices for real-time inference.</p><h3>2. What Is Image Classification in Survey123?</h3><p>Image classification in Survey123 allows a user to:</p><ol><li>Capture a photo (e.g., plant leaf, object, infrastructure)</li><li>Run a deep learning model instantly</li><li>Automatically extract results into structured form fields</li></ol><p>Unlike traditional workflows, this happens:</p><ul><li><strong>On-device (offline capable)</strong></li><li><strong>In real-time</strong></li><li><strong>Without user interaction</strong></li></ul><p>The system uses <strong>deep learning models converted to TensorFlow Lite (.tflite)</strong> to run efficiently on mobile devices.</p><h3>3. Core Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ib9uBL8HQzwJMXET.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*1oQobn6KXSZtfoaK.jpg" /></figure><p>The overall pipeline looks like this:</p><pre>Field Images → Model Training → Model Conversion → Survey123 Integration → Field Inference</pre><h4>Key Components</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*rmtOZm2_RNifZQGGZCTPtg.png" /></figure><p>This pipeline enables <strong>edge AI</strong>, where inference happens directly on the device.</p><h3>4. Data Preparation</h3><p>High-quality data is the most critical component of any image classification system.</p><h4>Data Collection &amp; Preparation</h4><p>The foundation of any classification system is <strong>high-quality labeled data</strong>.</p><h4>Best Practices</h4><ul><li>Collect <strong>100–200 images per class</strong></li><li>Use <strong>real field conditions</strong> (lighting, angles)</li><li>Maintain consistent class naming (e.g., tomato_early_blight)</li><li>Organize data in folder structure:</li></ul><pre>training_data/<br>├── tomato_healthy/<br>├── tomato_early_blight/<br>├── tomato_late_blight/</pre><p>This ensures the model generalizes well in real-world environments.</p><p>Important insight:<br>Training data must <strong>match deployment conditions</strong>, or accuracy drops significantly.</p><h3>5. Model Training (ArcGIS Pro)</h3><p>Survey123 does NOT train models, it only runs them.</p><p>Training is done using:</p><ul><li>Pretrained models (transfer learning)</li><li>Fine-tuning on your dataset</li></ul><h4>Typical Setup</h4><ul><li>Backbone: ResNet50 (training phase)</li><li>Epochs: 50–100</li><li>GPU recommended</li></ul><p>The output is:</p><pre>PlantLeafDisease.dlpk</pre><p>This is a <strong>deep learning package</strong> optimized for ArcGIS but not mobile-ready yet.</p><h3>6. Model Conversion (Critical Step)</h3><p>To run on mobile devices, the model must be converted to:</p><pre>.tflite (TensorFlow Lite)</pre><h4>Why this matters</h4><ul><li>.dlpk → desktop/server</li><li>.tflite → mobile inference</li></ul><h4>Key constraints</h4><ul><li>Must use <strong>MobileNetV2 backbone</strong></li><li>Must use <strong>TensorFlow backend</strong></li><li>Final size should be <strong>5–20 MB</strong></li></ul><p>This step bridges <strong>cloud AI → edge AI</strong></p><p>Once converted, the model cannot be retrained — always keep a checkpoint.</p><h3>7. Integrating with Survey123</h3><p>This is where the magic happens.</p><h4>Add model files</h4><pre>media/<br>├── PlantLeafDisease.tflite<br>├── PlantLeafDisease.txt</pre><h4>Configure XLSForm</h4><pre>type     | name  | label<br>image    | photo | Take a photo</pre><pre>bind::esri:parameters:<br>smartAttributes=PlantLeafDisease&amp;cameraPreview=true&amp;minScore=0.5</pre><h3>8. What happens internally?</h3><ol><li>User takes a photo</li><li>Model runs automatically</li><li>Output is stored as JSON in EXIF metadata</li><li>Survey extracts results using pulldata()</li></ol><p>Example:</p><pre>pulldata(&quot;@json&quot;, ${raw_results}, &quot;classNames&quot;)</pre><h3>9. How the AI Output Works</h3><p>When classification runs, Survey123 embeds results like:</p><pre>{<br>  &quot;classNames&quot;: &quot;tomato_early_blight&quot;,<br>  &quot;classes&quot;: [<br>    {<br>      &quot;name&quot;: &quot;tomato_early_blight&quot;,<br>      &quot;score&quot;: 0.8241<br>    }<br>  ]<br>}</pre><p>You can extract:</p><ul><li>Disease name</li><li>Confidence score</li><li>Additional metadata</li></ul><p>This enables <strong>fully automated form population</strong>.</p><h3>10. Real-Time Inference in the Field</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*i7luR2vpP6fu1idJ" /></figure><p>Once deployed, the workflow becomes:</p><ol><li>Field worker opens Survey123</li><li>Takes a photo of a leaf/object</li><li>AI predicts instantly</li><li>Form fields auto-fill</li><li>Data is submitted to GIS system</li></ol><p>This eliminates:</p><ul><li>Manual inspection</li><li>Expert dependency</li><li>Post-processing delays</li></ul><h3>11. Alternative Approach: Cloud-Based Classification</h3><p>There is another architecture:</p><pre>Survey123 → Webhook → Python API → AI Model → Update GIS</pre><p>Here:</p><ul><li>Model runs on server (not device)</li><li>Uses Flask/Azure Functions</li><li>Updates results after submission</li></ul><p>This approach is useful when:</p><ul><li>Model is too large for mobile</li><li>Requires heavy computation</li><li>Needs centralized control</li></ul><p>Example workflow includes webhook triggers and Python automation pipelines.</p><h3>12. Classification vs Object Detection</h3><p>Survey123 supports both:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*tbKBid-dsb91B1Aeq-13sw.png" /></figure><p>Object detection also stores:</p><ul><li>Bounding boxes</li><li>Object size &amp; location</li></ul><p>It uses the same EXIF-based extraction approach.</p><h3>13. Key Advantages</h3><h4>Real-time insights</h4><p>Immediate feedback during data collection</p><h4>Offline capability</h4><p>Works without internet using .tflite</p><h4>Reduced human error</h4><p>Standardized AI predictions</p><h4>Scalable field operations</h4><p>Non-experts can perform expert-level tasks</p><h3>14. Challenges &amp; Limitations</h3><ul><li>Model accuracy depends heavily on data quality</li><li>Mobile constraints (model size, performance)</li><li>Limited ability to retrain on-device</li><li>Requires ArcGIS ecosystem</li></ul><h3>15. Best Practices</h3><ul><li>Use <strong>MobileNetV2</strong> for mobile optimization</li><li>Keep model size under <strong>20 MB</strong></li><li>Match training and field conditions</li><li>Tune minScore (e.g., 0.5 → 0.7)</li><li>Always validate results in production</li></ul><h3>16. Future Trends</h3><p>The integration of Survey123 with AI is moving toward:</p><ul><li>Multi-agent field assistants</li><li>Continuous learning systems</li><li>Hybrid edge + cloud AI</li><li>Real-time analytics dashboards</li></ul><h3>17. Conclusion</h3><p>Image classification in Survey123 represents a shift toward <strong>intelligent field data collection systems</strong>.</p><p>By combining:</p><ul><li>Deep learning</li><li>Edge computing</li><li>GIS workflows</li></ul><p>you can build systems that <strong>detect, analyze, and act — all in real time</strong>.</p><p>This approach is not limited to agriculture. It can be applied to:</p><ul><li>Infrastructure inspection</li><li>Environmental monitoring</li><li>Disaster assessment</li><li>Smart city applications</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17e4a37e8b3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed System Technology Deep Dive: Domain Name System (DNS)]]></title>
            <link>https://medium.com/@minindubim/distributed-system-technology-deep-dive-domain-name-system-dns-9b8d1b76f92c?source=rss-67f2f7be01d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b8d1b76f92c</guid>
            <dc:creator><![CDATA[Minindu Bimsara Abeywardena]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 18:30:44 GMT</pubDate>
            <atom:updated>2026-03-23T18:39:25.777Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>A distributed system is a system where multiple computers work together by communicating through a network. These systems are very common in modern applications, especially mobile apps and web platforms.</p><p>One of the most important distributed technologies behind the internet is the <strong>Domain Name System (DNS)</strong>. Even though users do not see it, DNS is used every time we open a website or mobile app.</p><p>In Sri Lanka, a good real-world example is <strong>PickMe</strong>, which is available at <a href="https://pickme.lk/">https://pickme.lk/</a>. PickMe is a popular ride-hailing and delivery platform that connects passengers and drivers in real time using advanced technology . This blog explains DNS using PickMe as the example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IFgkfYXCi-_F3IIwvUPknw.png" /></figure><h3>What is DNS</h3><p>DNS works like a phonebook of the internet. Humans use names like pickme.lk, but computers use IP addresses.</p><p>DNS translates the domain name into an IP address so the system can connect to the correct server.</p><p>For example, when a user opens the PickMe website or app, DNS resolves pickme.lk into an IP address and connects the request to PickMe servers.</p><p>DNS is not a single server. It is a distributed system with many servers around the world working together.</p><h3>How DNS is Used in PickMe</h3><p>PickMe is a real-time digital platform that connects passengers and drivers instantly through mobile and web technologies . It handles thousands of requests at the same time across Sri Lanka.</p><p>Here is how DNS works in PickMe:</p><ol><li>A user opens the PickMe app or website</li><li>The system requests the domain pickme.lk</li><li>DNS translates this into an IP address</li><li>The request is sent to PickMe servers</li><li>The system processes bookings, location tracking, and driver matching</li></ol><p>Without DNS, users would need to remember IP addresses, which is not practical. DNS makes the system user-friendly and accessible.</p><h3>Type of Distributed System</h3><p>DNS is a <strong>hierarchical distributed system</strong>.</p><p>It is structured in levels:</p><ul><li>Root servers</li><li>Top-level domain servers like .lk</li><li>Authoritative servers like pickme.lk</li></ul><p>This structure allows DNS to scale globally and respond efficiently.</p><p>PickMe also uses a <strong>client-server distributed system</strong> internally, where mobile apps act as clients and backend servers handle requests such as ride booking and tracking.</p><h3>How DNS Preserves the Desired Properties</h3><p>DNS satisfies key distributed system properties that ensure reliability, performance, and overall system stability.</p><h3>1. Fault Tolerance</h3><p>DNS uses multiple servers. If one server fails, another server can respond.</p><p>For example, even if one DNS server handling pickme.lk fails, users can still access the PickMe platform.</p><h3>2. High Availability</h3><p>DNS is always available because it is distributed worldwide.</p><p>This is important for PickMe since users request rides at any time of the day. DNS ensures the platform is reachable without downtime.</p><h3>3. Recoverability</h3><p>If a DNS server crashes, it can restart and rejoin the system.</p><p>Since data is replicated, DNS continues to function without losing information.</p><h3>4. Consistency</h3><p>DNS maintains consistent domain name mappings across servers.</p><p>Even though updates take some time, users eventually receive the correct IP address for pickme.lk.</p><h3>5. Scalability</h3><p>DNS is highly scalable. It supports millions of domain requests.</p><p>PickMe handles a large number of users and trips. DNS ensures that increasing users does not affect performance.</p><h3>6. Predictable Performance</h3><p>DNS improves performance using caching.</p><p>For example, if a user frequently uses PickMe, the DNS result may already be stored, making access faster.</p><h3>7. Security</h3><p>DNS supports security features such as DNSSEC to prevent attacks.</p><p>This is important for PickMe because it handles sensitive data like user locations, contact details, and payment information.</p><h3>Importance of DNS in Real-World Systems</h3><p>DNS is essential for modern platforms like PickMe. Without DNS:</p><ul><li>Users cannot easily access services</li><li>Applications become harder to use</li><li>System performance decreases</li></ul><p>PickMe shows how distributed systems are used in Sri Lanka to solve real problems such as transportation and delivery. DNS works in the background to make the platform reliable and accessible.</p><h3>Conclusion</h3><p>DNS is a key distributed system technology that enables communication across the internet. It translates domain names into IP addresses and allows systems to function smoothly.</p><p>Using PickMe as a real-world example, we can see how DNS supports large-scale applications by ensuring availability, scalability, and reliability.</p><p>DNS is a hierarchical distributed system that satisfies important properties such as fault tolerance, consistency, and security.</p><p>Even though users do not notice it, DNS plays a major role in making platforms like PickMe efficient and user-friendly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b8d1b76f92c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SEO Strategy Report for a Mobile Shop Website]]></title>
            <link>https://medium.com/@minindubim/seo-strategy-report-for-a-mobile-shop-website-548dbb9059f8?source=rss-67f2f7be01d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/548dbb9059f8</guid>
            <dc:creator><![CDATA[Minindu Bimsara Abeywardena]]></dc:creator>
            <pubDate>Sun, 28 Dec 2025 18:56:40 GMT</pubDate>
            <atom:updated>2025-12-28T18:56:40.524Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Practical Guide to Ranking, Traffic, and Sales Growth</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*q9eO0bH9JHiJ8lec.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kTgcYPJAs4eIrpTv.jpg" /></figure><p>Launching a mobile shop website is only the first step. To actually <strong>get traffic, visibility, and sales</strong>, you need a well-planned SEO strategy. In this article, I’ll walk you through a <strong>complete, real-world SEO strategy for a mobile shop website</strong>, covering keyword research, on-page SEO, off-page SEO, technical SEO, content planning, and analytics.</p><p>This guide is written in a practical way so it can be applied to <strong>online mobile shops, local phone stores, or hybrid e-commerce businesses</strong>.</p><h3>1. Website Overview: Mobile Shop</h3><h3>Website Purpose</h3><p>The mobile shop website focuses on:</p><ul><li>Selling smartphones (Android &amp; iPhone)</li><li>Selling mobile accessories (chargers, cases, earphones)</li><li>Offering mobile repair services (screen and battery replacement)</li><li>Providing helpful content such as buying guides and comparisons</li></ul><h3>Target Audience</h3><ul><li>Age group: 18–45</li><li>Location: Sri Lanka (local + islandwide delivery)</li><li>Interests: Smartphones, gadgets, accessories</li><li>Search intent:</li><li>Informational (e.g., <em>best budget smartphones</em>)</li><li>Commercial (e.g., <em>Samsung phone prices</em>)</li><li>Transactional (e.g., <em>buy iPhone online</em>)</li></ul><h3>2. Keyword Research: The Foundation of SEO</h3><p>Keyword research helps us understand <strong>what people are actually searching for</strong>.</p><h3>Primary Keywords</h3><p>These keywords have high relevance and strong buying intent:</p><ul><li>mobile shop</li><li>buy mobile phones online</li><li>smartphone shop</li><li>mobile phone prices Sri Lanka</li><li>android phones Sri Lanka</li><li>iPhone price Sri Lanka</li><li>mobile accessories online</li><li>mobile repair service</li><li>best mobile phones 2025</li><li>online mobile store</li></ul><p>These keywords are competitive but essential for long-term growth.</p><h3>Long-Tail Keywords</h3><p>Long-tail keywords are easier to rank and convert better:</p><ul><li>best budget smartphones in Sri Lanka</li><li>buy iPhone online Sri Lanka</li><li>mobile phone shop near me</li><li>affordable android phones 2025</li><li>Samsung mobile prices in Sri Lanka</li><li>phone screen replacement service</li><li>gaming phones under budget</li><li>original mobile chargers Sri Lanka</li></ul><p>Long-tail keywords help attract <strong>high-intent users</strong> who are closer to making a purchase.</p><h3>3. On-Page SEO Strategy</h3><h3>Title Tags &amp; Meta Descriptions</h3><p>Each page should have a unique, keyword-optimized title and meta description.</p><p><strong>Homepage Title:</strong><br>Buy Mobile Phones Online in Sri Lanka | Best Prices &amp; Warranty</p><p><strong>Meta Description:</strong><br>Shop the latest smartphones, accessories, and mobile repair services in Sri Lanka with official warranty and fast delivery.</p><h3>Header Structure (H1–H3)</h3><p>A clear header structure improves readability and SEO.</p><p><strong>Homepage Example:</strong></p><ul><li>H1: Buy Mobile Phones Online in Sri Lanka</li><li>H2: Latest Smartphones Available</li><li>H2: Why Choose Our Mobile Shop</li><li>H3: Best Prices</li><li>H3: Official Warranty</li><li>H3: Fast Delivery</li></ul><h3>SEO-Friendly URLs</h3><p>Clean URLs help both users and search engines.</p><p>Examples:</p><ul><li>/shop/mobile-phones</li><li>/shop/mobile-accessories</li><li>/blog/best-budget-smartphones-sri-lanka</li></ul><h3>4. Content Strategy &amp; Optimization</h3><p>Content is what drives long-term organic traffic.</p><h3>Example Blog Topic</h3><p><strong>Best Budget Smartphones in Sri Lanka — 2025 Buying Guide</strong></p><p>This type of content:</p><ul><li>Targets informational + commercial intent</li><li>Builds trust and authority</li><li>Leads users naturally to product pages</li></ul><p>Optimized content should:</p><ul><li>Use keywords naturally</li><li>Include headings and bullet points</li><li>Answer real user questions</li><li>Avoid keyword stuffing</li></ul><h3>5. Off-Page SEO: Building Authority</h3><h3>Backlink Strategy</h3><p>Backlinks act as trust signals for search engines.</p><p>Potential backlink sources:</p><ul><li>Local tech blogs</li><li>Sri Lankan business directories</li><li>Mobile review websites</li><li>Guest posts on tech news sites</li><li>YouTube tech reviewers’ websites</li></ul><p>Quality matters more than quantity. A few relevant backlinks are better than many low-quality ones.</p><h3>Social Media Promotion</h3><p>Social media supports SEO indirectly by driving traffic and visibility.</p><p><strong>Platforms to use:</strong></p><ul><li>Facebook — promotions, offers</li><li>Instagram — product photos, reels</li><li>TikTok — short phone reviews</li><li>YouTube — unboxing and comparisons</li></ul><h3>6. Technical SEO Essentials</h3><h3>Improving Site Speed</h3><ul><li>Compress images</li><li>Use lazy loading</li><li>Minify CSS and JavaScript</li><li>Use a CDN</li></ul><h3>Mobile-Friendliness</h3><p>Mobile-first indexing makes this critical.</p><p>Steps to ensure mobile-friendliness:</p><ul><li>Responsive design</li><li>Touch-friendly buttons</li><li>Fast mobile load times</li><li>Readable font sizes</li></ul><h3>XML Sitemap &amp; Robots.txt</h3><p>These help search engines crawl your site efficiently.</p><p><strong>XML Sitemap:</strong> Helps index important pages<br><strong>Robots.txt:</strong> Controls crawler access</p><p>Both are essential for proper indexing.</p><h3>7. Monthly Content Plan</h3><p>A consistent content schedule keeps SEO growth steady.</p><p><strong>Weekly Content Plan:</strong></p><ul><li>1 blog post (guides, comparisons, tips)</li><li>1 social media post</li><li>1 guest post or collaboration</li></ul><p>Example topics:</p><ul><li>Budget smartphones</li><li>Samsung vs iPhone</li><li>Mobile accessories buying guide</li><li>Gaming phones</li></ul><h3>8. Analytics &amp; Performance Tracking</h3><p>SEO without tracking is guesswork.</p><h3>Tools Used</h3><ul><li>Google Analytics</li><li>Google Search Console</li></ul><h3>Key Metrics to Track</h3><ol><li><strong>Organic Traffic</strong> — Measures SEO growth</li><li><strong>Bounce Rate</strong> — Indicates content relevance</li><li><strong>Conversion Rate</strong> — Measures business success</li></ol><p>These metrics show whether SEO efforts are actually delivering results.</p><h3>Final Thoughts</h3><p>A successful SEO strategy for a mobile shop website requires a <strong>balanced approach</strong>:</p><ul><li>Strong keyword research</li><li>Optimized on-page structure</li><li>High-quality content</li><li>Authoritative backlinks</li><li>Solid technical foundation</li></ul><p>When done correctly, SEO doesn’t just bring traffic — it brings <strong>qualified users who are ready to buy</strong>.</p><p>If you’re building or managing a mobile shop website, this SEO strategy can serve as a <strong>roadmap for sustainable growth</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=548dbb9059f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Secure E-Commerce with WSO2 Asgardeo: A Developer’s Journey]]></title>
            <link>https://medium.com/@minindubim/building-secure-e-commerce-with-wso2-asgardeo-a-developers-journey-84fa60503eb1?source=rss-67f2f7be01d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/84fa60503eb1</guid>
            <dc:creator><![CDATA[Minindu Bimsara Abeywardena]]></dc:creator>
            <pubDate>Wed, 17 Sep 2025 18:15:10 GMT</pubDate>
            <atom:updated>2025-09-17T18:15:10.218Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern web applications require robust authentication and authorization systems that can scale with business needs while maintaining security best practices. In this post, I’ll share how I implemented WSO2 Asgardeo as the identity and access management (IAM) solution for a full-stack e-commerce application, complete with dual authentication modes and seamless token management.</p><h3>Why Asgardeo for E-Commerce?</h3><p>When building our e-commerce platform, we needed an authentication solution that could:</p><ul><li><strong>Scale effortlessly</strong> from development to production</li><li><strong>Support modern standards</strong> like OAuth 2.0 and OpenID Connect</li><li><strong>Provide seamless integration</strong> with both frontend and backend</li><li><strong>Offer flexible user management</strong> without compromising security</li><li><strong>Enable rapid development</strong> without reinventing authentication wheels</li></ul><p>WSO2 Asgardeo checked all these boxes as a cloud-native identity-as-a-service platform that removes the complexity of building authentication from scratch.</p><h3>Architecture Overview</h3><p>Our application uses a dual authentication approach:</p><ul><li><strong>Demo Mode</strong>: Local JWT tokens for development and testing</li><li><strong>Production Mode</strong>: WSO2 Asgardeo OAuth2/OIDC integration</li></ul><p>This flexibility allows developers to work offline while providing production-ready authentication when deployed.</p><pre>interface DualAuthState {<br>  isAuthenticated: boolean;<br>  isLoading: boolean;<br>  authMode: &#39;asgardeo&#39; | &#39;demo&#39;;<br>  username?: string;<br>  email?: string;<br>  accessToken?: string;<br>}</pre><h3>Setting Up Asgardeo Integration</h3><h3>Frontend Configuration</h3><p>The frontend uses the Asgardeo React SDK to handle OAuth2 flows seamlessly:</p><pre>const asgardeoConfig = {<br>  signInRedirectURL: &quot;http://localhost:3000&quot;,<br>  signOutRedirectURL: &quot;http://localhost:3000&quot;, <br>  clientID: process.env.NEXT_PUBLIC_ASGARDEO_CLIENT_ID,<br>  baseUrl: process.env.NEXT_PUBLIC_ASGARDEO_BASE_URL,<br>  scope: [&quot;openid&quot;, &quot;profile&quot;, &quot;email&quot;],<br>  resourceServerURLs: [&quot;http://localhost:8080&quot;],<br>  enablePKCE: true,<br>};</pre><pre>export function DualAuthProvider({ children }) {<br>  return (<br>    &lt;AsgardeoAuthProvider config={asgardeoConfig}&gt;<br>      &lt;AsgardeoAuthWrapper&gt;{children}&lt;/AsgardeoAuthWrapper&gt;<br>    &lt;/AsgardeoAuthProvider&gt;<br>  );<br>}</pre><h3>Intelligent Token Management</h3><p>One of the most critical aspects is proper token handling:</p><pre>async getAccessToken(): Promise&lt;string | null&gt; {<br>  const state = this.authContext.state;</pre><pre>  // For Asgardeo mode, get OAuth2 access token<br>  if (state.authMode === &quot;asgardeo&quot;) {<br>    try {<br>      const token = await this.authContext.getAccessToken();<br>      <br>      if (token) {<br>        // Validate token expiration<br>        const payload = JSON.parse(atob(token.split(&#39;.&#39;)[1]));<br>        const now = Math.floor(Date.now() / 1000);<br>        <br>        if (payload.exp &amp;&amp; payload.exp &lt; now) {<br>          return null; // Token expired<br>        }<br>        <br>        return token;<br>      }<br>    } catch (error) {<br>      console.error(&quot;Failed to get Asgardeo token:&quot;, error);<br>    }<br>  }</pre><pre>  // For demo mode, use stored token<br>  return state.accessToken || null;<br>}</pre><h3>Backend Integration with Spring Boot</h3><h3>Dual Authentication Filter</h3><p>Our Spring Boot backend intelligently handles both token types:</p><pre>@Component<br>public class DualAuthenticationFilter extends OncePerRequestFilter {<br>    <br>    @Override<br>    protected void doFilterInternal(HttpServletRequest request, <br>                                   HttpServletResponse response, <br>                                   FilterChain filterChain) {<br>        <br>        final String token = extractTokenFromHeader(request);<br>        if (token == null) {<br>            filterChain.doFilter(request, response);<br>            return;<br>        }<br>        <br>        try {<br>            TokenType tokenType = determineTokenType(token);<br>            <br>            switch (tokenType) {<br>                case ASGARDEO_RS256:<br>                    authenticateAsgardeoToken(token, request);<br>                    break;<br>                case LOCAL_HS256:<br>                    authenticateLocalToken(token, request);<br>                    break;<br>            }<br>        } catch (Exception e) {<br>            SecurityContextHolder.clearContext();<br>        }<br>        <br>        filterChain.doFilter(request, response);<br>    }<br>}</pre><h3>Spring Security Configuration</h3><pre>@Configuration<br>@EnableWebSecurity<br>public class SecurityConfig {<br>    @Bean<br>    public SecurityFilterChain securityFilterChain(HttpSecurity http) {<br>        return http<br>            .cors(cors -&gt; cors.configurationSource(corsConfigurationSource()))<br>            .csrf(csrf -&gt; csrf.disable())<br>            .authorizeHttpRequests(auth -&gt; auth<br>                .requestMatchers(&quot;/api/auth/**&quot;, &quot;/api/products/**&quot;).permitAll()<br>                .anyRequest().authenticated()<br>            )<br>            .addFilterBefore(dualAuthenticationFilter, <br>                           UsernamePasswordAuthenticationFilter.class)<br>            .build();<br>    }<br>}</pre><h3>Asgardeo Properties Configuration</h3><pre># Asgardeo OAuth2/OIDC Configuration<br>asgardeo.org-name=${ASGARDEO_ORG_NAME:your_org}<br>spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://api.asgardeo.io/t/${asgardeo.org-name}/oauth2/jwks<br>spring.security.oauth2.client.registration.asgardeo.scope=openid,profile,email</pre><h3>Key Implementation Features</h3><h3>1. Role-Based Authorization</h3><p>Asgardeo’s group management integrates with Spring Security’s authorization:</p><pre>private Collection&lt;String&gt; extractRolesFromJwt(Jwt jwt) {<br>    // Check for &#39;groups&#39; claim (Asgardeo&#39;s primary mechanism)<br>    Object groups = jwt.getClaim(&quot;groups&quot;);<br>    if (groups instanceof List&lt;?&gt;) {<br>        return ((List&lt;?&gt;) groups).stream()<br>                .map(Object::toString)<br>                .collect(Collectors.toList());<br>    }<br>    <br>    return Collections.singletonList(&quot;USER&quot;); // Default role<br>}</pre><h3>2. Unified User Context</h3><p>A utility ensures consistent user extraction across authentication modes:</p><pre>public static String extractUsernameFromAuth(Authentication authentication) {<br>    if (authentication instanceof JwtAuthenticationToken) {<br>        Jwt jwt = ((JwtAuthenticationToken) authentication).getToken();<br>        return extractUsernameFromJwt(jwt);<br>    }<br>    <br>    return authentication.getName();<br>}</pre><h3>3. Smart API Client</h3><p>The frontend API client automatically handles token injection:</p><pre>private async getHeaders(): Promise&lt;Record&lt;string, string&gt;&gt; {<br>  const headers = { &quot;Content-Type&quot;: &quot;application/json&quot; };<br>  <br>  if (this.authService.isAuthenticated()) {<br>    const token = await this.authService.getAccessToken();<br>    if (token) {<br>      headers.Authorization = `Bearer ${token}`;<br>    }<br>  }<br>  <br>  return headers;<br>}</pre><h3>Real-World Benefits</h3><h3>1. Developer Experience</h3><ul><li><strong>Seamless offline development</strong>: Demo mode works without internet</li><li><strong>Hot-swappable authentication</strong>: Switch modes without code changes</li><li><strong>Comprehensive debugging</strong>: Clear token validation and error reporting</li></ul><h3>2. Security &amp; Compliance</h3><ul><li><strong>Industry standards</strong>: OAuth 2.0/OIDC compliance out of the box</li><li><strong>Automatic token validation</strong>: Built-in JWT verification</li><li><strong>Role-based access</strong>: Native Spring Security integration</li></ul><h3>3. Production Readiness</h3><ul><li><strong>Zero infrastructure</strong>: No authentication servers to manage</li><li><strong>Automatic updates</strong>: Asgardeo handles security patches</li><li><strong>Multi-tenant ready</strong>: Easy organization management</li></ul><h3>4. User Experience</h3><ul><li><strong>Single Sign-On</strong>: Works across multiple applications</li><li><strong>Fast authentication</strong>: Quick token validation</li><li><strong>Social login support</strong>: Easy third-party integrations</li></ul><h3>Cart Synchronization Example</h3><p>One practical implementation detail — syncing user cart data after authentication:</p><pre>const syncWithBackend = useCallback(async () =&gt; {<br>  if (!authState.isAuthenticated) return;<br>  <br>  try {<br>    const cartService = new CartService(apiClient);<br>    const backendCart = await cartService.getCart();<br>    <br>    if (backendCart.length &gt; 0) {<br>      // Load backend cart to frontend<br>      clearCart();<br>      backendCart.forEach(item =&gt; addItem(item));<br>    } else if (frontendItems.length &gt; 0) {<br>      // Sync frontend cart to backend<br>      await cartService.syncCart(frontendItems);<br>    }<br>  } catch (error) {<br>    console.warn(&quot;Cart sync failed:&quot;, error);<br>  }<br>}, [authState.isAuthenticated]);</pre><h3>Key Lessons Learned</h3><ol><li><strong>Token Management is Critical</strong>: Proper validation, expiration handling, and renewal strategies are essential</li><li><strong>Dual Authentication Provides Flexibility</strong>: Demo mode significantly improves development workflow</li><li><strong>Standards Matter</strong>: OAuth 2.0/OIDC ensures compatibility and future-proofing</li><li><strong>Error Handling Saves Time</strong>: Comprehensive debugging reduces troubleshooting</li></ol><h3>Getting Started with Asgardeo</h3><ol><li>Sign up at <a href="https://asgardeo.io/">asgardeo.io</a></li><li>Create an application in the Asgardeo console</li><li>Configure OIDC settings with your redirect URLs</li><li>Set up user groups and roles</li><li>Integrate using the client credentials</li></ol><h3>Conclusion</h3><p>WSO2 Asgardeo transformed our e-commerce authentication from a complex challenge into a streamlined, secure solution. The combination of modern standards, cloud-native architecture, and developer-friendly tools makes it ideal for applications that need to balance security with development velocity.</p><p>Whether building a startup or enterprise application, Asgardeo provides the authentication foundation needed to focus on core business logic while maintaining the highest security standards.</p><p>The dual-mode approach we implemented allows for rapid development cycles while ensuring production readiness — a perfect example of how modern identity solutions can enhance rather than hinder the development process.</p><p><em>Ready to implement secure authentication in your application? Try WSO2 Asgardeo today and experience the difference cloud-native identity management can make.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84fa60503eb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Production-Ready Secure E-Commerce Platform: Implementing OWASP Top 10 Security Measures…]]></title>
            <link>https://medium.com/@minindubim/building-a-production-ready-secure-e-commerce-platform-implementing-owasp-top-10-security-measures-e343c354515b?source=rss-67f2f7be01d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e343c354515b</guid>
            <dc:creator><![CDATA[Minindu Bimsara Abeywardena]]></dc:creator>
            <pubDate>Sun, 07 Sep 2025 18:04:13 GMT</pubDate>
            <atom:updated>2025-09-07T18:04:13.941Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Production-Ready Secure E-Commerce Platform: Implementing OWASP Top 10 Security Measures with Asgardeo OIDC</h3><h3>Introduction</h3><p>In today’s digital landscape, e-commerce applications handle sensitive user data, financial transactions, and personal information, making them prime targets for cyber attacks. This blog documents the development of <strong>NovaMart</strong>, a secure e-commerce platform that addresses the OWASP Top 10 vulnerabilities while implementing modern authentication protocols through Asgardeo OIDC.</p><p>This isn’t just another tutorial — it’s a real-world implementation guide based on a production-ready application that demonstrates how security can be built into every layer of a modern web application.</p><h3>Why Security Matters in E-Commerce</h3><p>E-commerce platforms are attractive targets because they typically handle:</p><ul><li>Personal customer information (names, addresses, phone numbers)</li><li>Authentication credentials</li><li>Purchase histories and preferences</li><li>Payment information</li><li>Administrative access to business operations</li></ul><p>A single security breach can result in:</p><ul><li>Loss of customer trust and reputation damage</li><li>Regulatory fines (GDPR, PCI DSS compliance)</li><li>Financial losses from fraud and legal costs</li><li>Operational disruption</li></ul><h3>Project Architecture Overview</h3><p><strong>NovaMart</strong> is built using modern technologies with security as a foundational principle:</p><h3>Backend Stack</h3><ul><li><strong>Spring Boot 3.2.5</strong> with Java 21</li><li><strong>Spring Security 6</strong> for comprehensive security</li><li><strong>MongoDB</strong> for scalable data storage</li><li><strong>Asgardeo OIDC</strong> for authentication</li><li><strong>JWT</strong> for local authentication fallback</li></ul><h3>Frontend Stack</h3><ul><li><strong>Next.js 14</strong> with React 18</li><li><strong>TypeScript</strong> for type safety</li><li><strong>Tailwind CSS</strong> for styling</li><li><strong>Zustand</strong> for state management</li><li><strong>Dual Authentication</strong> (Asgardeo + Local JWT)</li></ul><h3>Security Architecture</h3><pre>┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐<br>│   React Frontend │    │  Spring Boot    │    │    MongoDB      │<br>│   - Auth Guard   │◄──►│   - Security    │◄──►│   - Validation  │<br>│   - Token Mgmt   │    │   - CORS/CSRF   │    │   - Encryption  │<br>│   - Input Valid  │    │   - Rate Limit  │    │   - Indexes     │<br>└─────────────────┘    └─────────────────┘    └─────────────────┘<br>         │                        │                        │<br>         ▼                        ▼                        ▼<br>┌─────────────────────────────────────────────────────────────────┐<br>│                    Asgardeo OIDC Provider                       │<br>│        - OAuth2/OIDC Flow  - Token Validation                   │<br>│        - User Management   - Role/Group Management              │<br>└─────────────────────────────────────────────────────────────────┘</pre><h3>OWASP Top 10 Implementation</h3><h3>1. Injection (A03:2021)</h3><p><strong>Challenge</strong>: Preventing NoSQL injection attacks in MongoDB queries.</p><p><strong>Implementation</strong>:</p><p>java</p><pre>// Secure MongoDB query with validation<br>@Repository<br>public class ProductRepository {<br>    @Query(&quot;{&#39;name&#39;: {$regex: ?0, $options: &#39;i&#39;}, &#39;category&#39;: ?1}&quot;)<br>    public List&lt;Product&gt; findByNameAndCategory(<br>        @Param(&quot;name&quot;) String name, <br>        @Param(&quot;category&quot;) String category) {<br>        <br>        // Input validation before query<br>        if (name != null) {<br>            name = name.replaceAll(&quot;[^a-zA-Z0-9\\s]&quot;, &quot;&quot;);<br>        }<br>        return mongoTemplate.find(<br>            Query.query(Criteria.where(&quot;name&quot;).regex(name, &quot;i&quot;)<br>                  .and(&quot;category&quot;).is(category)), <br>            Product.class<br>        );<br>    }<br>}</pre><p><strong>Validation Layer</strong>:</p><p>java</p><pre>@RestController<br>@Validated<br>public class ProductController {<br>    <br>    @GetMapping(&quot;/products&quot;)<br>    public ResponseEntity&lt;List&lt;Product&gt;&gt; getProducts(<br>        @Pattern(regexp = &quot;^[a-zA-Z0-9\\s]*$&quot;) @RequestParam(required = false) String search,<br>        @Pattern(regexp = &quot;^[a-zA-Z\\s]*$&quot;) @RequestParam(required = false) String category) {<br>        // Controller logic<br>    }<br>}</pre><h3>2. Broken Authentication (A07:2021)</h3><p><strong>Challenge</strong>: Implementing secure authentication with modern protocols.</p><p><strong>Solution</strong>: Dual authentication system supporting both Asgardeo OIDC and local JWT.</p><p><strong>Asgardeo OIDC Configuration</strong>:</p><p>java</p><pre>@Configuration<br>@EnableWebSecurity<br>public class SecurityConfig {<br>    <br>    @Bean<br>    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {<br>        return http<br>            .cors(cors -&gt; cors.configurationSource(corsConfigurationSource()))<br>            .csrf(csrf -&gt; csrf.disable())<br>            .authorizeHttpRequests(auth -&gt; auth<br>                .requestMatchers(&quot;/api/auth/**&quot;, &quot;/api/products&quot;).permitAll()<br>                .anyRequest().authenticated()<br>            )<br>            .oauth2ResourceServer(oauth2 -&gt; oauth2<br>                .jwt(jwt -&gt; jwt<br>                    .decoder(jwtDecoder())<br>                    .jwtAuthenticationConverter(jwtAuthenticationConverter())<br>                )<br>            )<br>            .addFilterBefore(dualAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)<br>            .build();<br>    }<br>}</pre><p><strong>Dual Authentication Filter</strong>:</p><p>java</p><pre>@Component<br>public class DualAuthenticationFilter extends OncePerRequestFilter {<br>    <br>    @Override<br>    protected void doFilterInternal(HttpServletRequest request, <br>                                    HttpServletResponse response, <br>                                    FilterChain filterChain) throws ServletException, IOException {<br>        <br>        String token = extractToken(request);<br>        if (token != null) {<br>            TokenType tokenType = determineTokenType(token);<br>            <br>            switch (tokenType) {<br>                case ASGARDEO_RS256:<br>                    authenticateAsgardeoToken(token, request);<br>                    break;<br>                case LOCAL_HS256:<br>                    authenticateLocalToken(token, request);<br>                    break;<br>            }<br>        }<br>        <br>        filterChain.doFilter(request, response);<br>    }<br>}</pre><h3>3. Sensitive Data Exposure (A02:2021)</h3><p><strong>Implementation</strong>: Multi-layer data protection strategy.</p><p><strong>Password Security</strong>:</p><p>java</p><pre>@Service<br>public class UserService {<br>    <br>    private final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(12);<br>    <br>    public User createUser(UserDTO userDTO) {<br>        User user = new User();<br>        user.setPassword(passwordEncoder.encode(userDTO.getPassword()));<br>        // Never expose passwords in responses<br>        return userRepository.save(user);<br>    }<br>}</pre><p><strong>Sensitive Data Filtering</strong>:</p><p>java</p><pre>@JsonIgnore<br>private String password;</pre><pre>@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)<br>private String sensitiveField;</pre><h3>4. XML External Entities (XXE) (A04:2021)</h3><p><strong>Implementation</strong>: Input validation and safe parsing.</p><p>java</p><pre>@Component<br>public class SafeXMLProcessor {<br>    <br>    public Document parseXML(String xmlContent) throws ParserConfigurationException {<br>        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();<br>        // Disable external entity processing<br>        factory.setFeature(&quot;http://apache.org/xml/features/disallow-doctype-decl&quot;, true);<br>        factory.setFeature(&quot;http://xml.org/sax/features/external-general-entities&quot;, false);<br>        factory.setFeature(&quot;http://xml.org/sax/features/external-parameter-entities&quot;, false);<br>        <br>        return factory.newDocumentBuilder().parse(new ByteArrayInputStream(xmlContent.getBytes()));<br>    }<br>}</pre><h3>5. Broken Access Control (A01:2021)</h3><p><strong>Challenge</strong>: Ensuring users can only access their own data.</p><p><strong>Implementation</strong>:</p><p>java</p><pre>@RestController<br>@PreAuthorize(&quot;hasRole(&#39;USER&#39;)&quot;)<br>public class OrderController {<br>    <br>    @GetMapping(&quot;/orders&quot;)<br>    public ResponseEntity&lt;List&lt;Order&gt;&gt; getUserOrders(Authentication auth) {<br>        String username = extractUsername(auth);<br>        List&lt;Order&gt; orders = orderService.getOrdersByUsername(username);<br>        return ResponseEntity.ok(orders);<br>    }<br>    <br>    @GetMapping(&quot;/orders/{id}&quot;)<br>    public ResponseEntity&lt;Order&gt; getOrder(@PathVariable String id, Authentication auth) {<br>        String username = extractUsername(auth);<br>        Order order = orderService.getOrderById(id);<br>        <br>        // Critical: Verify ownership<br>        if (!order.getUsername().equals(username) &amp;&amp; !isAdmin(auth)) {<br>            throw new AccessDeniedException(&quot;Cannot access other user&#39;s orders&quot;);<br>        }<br>        <br>        return ResponseEntity.ok(order);<br>    }<br>}</pre><p><strong>Frontend Access Control</strong>:</p><p>typescript</p><pre>// AuthGuard component<br>export function AuthGuard({ children }: { children: React.ReactNode }) {<br>  const { state } = useAuthContext();<br>  const router = useRouter();</pre><pre>  useEffect(() =&gt; {<br>    if (!state.isAuthenticated &amp;&amp; !state.isLoading) {<br>      router.push(&#39;/&#39;);<br>    }<br>  }, [state.isAuthenticated, state.isLoading, router]);</pre><pre>  if (state.isLoading) {<br>    return &lt;Loader /&gt;;<br>  }</pre><pre>  if (!state.isAuthenticated) {<br>    return &lt;div&gt;Redirecting to login...&lt;/div&gt;;<br>  }</pre><pre>  return &lt;&gt;{children}&lt;/&gt;;<br>}</pre><h3>6. Security Misconfiguration (A05:2021)</h3><p><strong>Implementation</strong>: Comprehensive security headers and configuration.</p><p>java</p><pre>@Configuration<br>public class SecurityHeadersConfig {<br>    <br>    @Bean<br>    public FilterRegistrationBean&lt;SecurityHeadersFilter&gt; securityHeadersFilter() {<br>        FilterRegistrationBean&lt;SecurityHeadersFilter&gt; registrationBean = new FilterRegistrationBean&lt;&gt;();<br>        registrationBean.setFilter(new SecurityHeadersFilter());<br>        registrationBean.addUrlPatterns(&quot;/*&quot;);<br>        return registrationBean;<br>    }<br>}</pre><pre>public class SecurityHeadersFilter implements Filter {<br>    <br>    @Override<br>    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {<br>        HttpServletResponse httpResponse = (HttpServletResponse) response;<br>        <br>        // Security headers<br>        httpResponse.setHeader(&quot;X-Content-Type-Options&quot;, &quot;nosniff&quot;);<br>        httpResponse.setHeader(&quot;X-Frame-Options&quot;, &quot;DENY&quot;);<br>        httpResponse.setHeader(&quot;X-XSS-Protection&quot;, &quot;1; mode=block&quot;);<br>        httpResponse.setHeader(&quot;Strict-Transport-Security&quot;, &quot;max-age=31536000; includeSubDomains&quot;);<br>        httpResponse.setHeader(&quot;Content-Security-Policy&quot;, <br>            &quot;default-src &#39;self&#39;; script-src &#39;self&#39; &#39;unsafe-eval&#39;; style-src &#39;self&#39; &#39;unsafe-inline&#39;&quot;);<br>        <br>        chain.doFilter(request, response);<br>    }<br>}</pre><h3>7. Cross-Site Scripting (XSS) (A03:2021)</h3><p><strong>Implementation</strong>: Input sanitization and output encoding.</p><p>java</p><pre>@Component<br>public class XSSProtection {<br>    <br>    @EventListener<br>    public void handleBeforeSave(BeforeConvertEvent&lt;Object&gt; event) {<br>        Object source = event.getSource();<br>        sanitizeObject(source);<br>    }<br>    <br>    private void sanitizeObject(Object obj) {<br>        Field[] fields = obj.getClass().getDeclaredFields();<br>        for (Field field : fields) {<br>            if (field.getType() == String.class) {<br>                field.setAccessible(true);<br>                try {<br>                    String value = (String) field.get(obj);<br>                    if (value != null) {<br>                        String sanitized = Jsoup.clean(value, Safelist.basicWithImages());<br>                        field.set(obj, sanitized);<br>                    }<br>                } catch (IllegalAccessException e) {<br>                    log.error(&quot;Error sanitizing field: &quot; + field.getName(), e);<br>                }<br>            }<br>        }<br>    }<br>}</pre><p><strong>Frontend Protection</strong>:</p><p>typescript</p><pre>// Input sanitization hook<br>export function useSanitizedInput(initialValue: string = &#39;&#39;) {<br>  const [value, setValue] = useState(initialValue);<br>  <br>  const setSanitizedValue = useCallback((newValue: string) =&gt; {<br>    // Remove script tags and dangerous content<br>    const sanitized = newValue<br>      .replace(/&lt;script\b[^&lt;]*(?:(?!&lt;\/script&gt;)&lt;[^&lt;]*)*&lt;\/script&gt;/gi, &#39;&#39;)<br>      .replace(/javascript:/gi, &#39;&#39;)<br>      .replace(/on\w+=&quot;/gi, &#39;&#39;);<br>    setValue(sanitized);<br>  }, []);<br>  <br>  return [value, setSanitizedValue] as const;<br>}</pre><h3>8. Insecure Deserialization (A08:2021)</h3><p><strong>Implementation</strong>: Safe JSON processing with validation.</p><p>java</p><pre>@Configuration<br>public class JacksonConfig {<br>    <br>    @Bean<br>    @Primary<br>    public ObjectMapper objectMapper() {<br>        ObjectMapper mapper = new ObjectMapper();<br>        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);<br>        mapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, true);<br>        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);<br>        mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);<br>        return mapper;<br>    }<br>}</pre><h3>9. Using Components with Known Vulnerabilities (A06:2021)</h3><p><strong>Implementation</strong>: Automated dependency management and monitoring.</p><p>xml</p><pre>&lt;!-- Maven dependency check plugin --&gt;<br>&lt;plugin&gt;<br>    &lt;groupId&gt;org.owasp&lt;/groupId&gt;<br>    &lt;artifactId&gt;dependency-check-maven&lt;/artifactId&gt;<br>    &lt;version&gt;8.4.0&lt;/version&gt;<br>    &lt;configuration&gt;<br>        &lt;failBuildOnCVSS&gt;7&lt;/failBuildOnCVSS&gt;<br>        &lt;suppressionFile&gt;dependency-check-suppressions.xml&lt;/suppressionFile&gt;<br>    &lt;/configuration&gt;<br>    &lt;executions&gt;<br>        &lt;execution&gt;<br>            &lt;goals&gt;<br>                &lt;goal&gt;check&lt;/goal&gt;<br>            &lt;/goals&gt;<br>        &lt;/execution&gt;<br>    &lt;/executions&gt;<br>&lt;/plugin&gt;</pre><h3>10. Insufficient Logging &amp; Monitoring (A09:2021)</h3><p><strong>Implementation</strong>: Comprehensive security event logging.</p><p>java</p><pre>@Component<br>public class SecurityEventLogger {<br>    <br>    private static final Logger securityLogger = LoggerFactory.getLogger(&quot;SECURITY&quot;);<br>    <br>    @EventListener<br>    public void handleAuthenticationSuccess(AuthenticationSuccessEvent event) {<br>        String username = event.getAuthentication().getName();<br>        String details = event.getAuthentication().getDetails().toString();<br>        <br>        securityLogger.info(&quot;Authentication successful: user={}, details={}&quot;, username, details);<br>    }<br>    <br>    @EventListener<br>    public void handleAuthenticationFailure(AbstractAuthenticationFailureEvent event) {<br>        String username = event.getAuthentication().getName();<br>        String reason = event.getException().getMessage();<br>        <br>        securityLogger.warn(&quot;Authentication failed: user={}, reason={}&quot;, username, reason);<br>    }<br>    <br>    @EventListener<br>    public void handleAccessDenied(AccessDeniedEvent event) {<br>        String username = event.getAuthentication().getName();<br>        String resource = event.getSource().toString();<br>        <br>        securityLogger.error(&quot;Access denied: user={}, resource={}&quot;, username, resource);<br>    }<br>}</pre><h3>Asgardeo OIDC Authentication Implementation</h3><h3>Backend OIDC Configuration</h3><p><strong>JWT Token Validation</strong>:</p><p>java</p><pre>@Component<br>public class AsgardeoJwtDecoder {<br>    <br>    @Value(&quot;${asgardeo.jwks-uri}&quot;)<br>    private String jwksUri;<br>    <br>    @Bean<br>    public JwtDecoder jwtDecoder() {<br>        return NimbusJwtDecoder.withJwkSetUri(jwksUri)<br>                .cache(Duration.ofMinutes(5))<br>                .build();<br>    }<br>    <br>    @Bean<br>    public JwtAuthenticationConverter jwtAuthenticationConverter() {<br>        JwtGrantedAuthoritiesConverter authoritiesConverter = new JwtGrantedAuthoritiesConverter();<br>        authoritiesConverter.setAuthorityPrefix(&quot;ROLE_&quot;);<br>        authoritiesConverter.setAuthoritiesClaimName(&quot;groups&quot;);<br>        <br>        JwtAuthenticationConverter jwtConverter = new JwtAuthenticationConverter();<br>        jwtConverter.setJwtGrantedAuthoritiesConverter(authoritiesConverter);<br>        return jwtConverter;<br>    }<br>}</pre><p><strong>User Profile Extraction</strong>:</p><p>java</p><pre>@RestController<br>public class AuthController {<br>    <br>    @GetMapping(&quot;/api/auth/profile&quot;)<br>    @PreAuthorize(&quot;hasRole(&#39;USER&#39;)&quot;)<br>    public ResponseEntity&lt;UserProfile&gt; getUserProfile(@AuthenticationPrincipal Jwt jwt) {<br>        UserProfile profile = UserProfile.builder()<br>                .username(jwt.getClaimAsString(&quot;preferred_username&quot;))<br>                .name(jwt.getClaimAsString(&quot;name&quot;))<br>                .email(jwt.getClaimAsString(&quot;email&quot;))<br>                .contactNumber(jwt.getClaimAsString(&quot;phone_number&quot;))<br>                .country(jwt.getClaimAsString(&quot;locale&quot;))<br>                .roles(extractRoles(jwt))<br>                .emailVerified(jwt.getClaimAsBoolean(&quot;email_verified&quot;))<br>                .build();<br>        <br>        return ResponseEntity.ok(profile);<br>    }<br>    <br>    private List&lt;String&gt; extractRoles(Jwt jwt) {<br>        Object groups = jwt.getClaim(&quot;groups&quot;);<br>        if (groups instanceof List&lt;?&gt;) {<br>            return ((List&lt;?&gt;) groups).stream()<br>                    .map(Object::toString)<br>                    .collect(Collectors.toList());<br>        }<br>        return List.of(&quot;USER&quot;);<br>    }<br>}</pre><h3>Frontend OIDC Integration</h3><p><strong>Authentication Provider</strong>:</p><p>typescript</p><pre>// Asgardeo authentication context<br>export function AsgardeoAuthProvider({ children }: { children: React.ReactNode }) {<br>  const asgardeoConfig = {<br>    signInRedirectURL: process.env.NEXT_PUBLIC_ASGARDEO_SIGN_IN_REDIRECT_URL!,<br>    signOutRedirectURL: process.env.NEXT_PUBLIC_ASGARDEO_SIGN_OUT_REDIRECT_URL!,<br>    clientID: process.env.NEXT_PUBLIC_ASGARDEO_CLIENT_ID!,<br>    baseUrl: process.env.NEXT_PUBLIC_ASGARDEO_BASE_URL!,<br>    scope: [&quot;openid&quot;, &quot;profile&quot;, &quot;email&quot;],<br>    resourceServerURLs: [process.env.NEXT_PUBLIC_API_BASE_URL!],<br>    enablePKCE: true,<br>    storage: &quot;sessionStorage&quot;,<br>  };</pre><pre>  return (<br>    &lt;AuthProvider config={asgardeoConfig}&gt;<br>      {children}<br>    &lt;/AuthProvider&gt;<br>  );<br>}</pre><p><strong>User Information Display</strong>:</p><p>typescript</p><pre>// User profile component<br>export function UserProfile() {<br>  const { state } = useAuthContext();<br>  const [profile, setProfile] = useState&lt;UserProfile | null&gt;(null);</pre><pre>  useEffect(() =&gt; {<br>    const fetchProfile = async () =&gt; {<br>      if (state.isAuthenticated) {<br>        try {<br>          const response = await fetch(&#39;/api/auth/profile&#39;, {<br>            headers: {<br>              &#39;Authorization&#39;: `Bearer ${await state.getAccessToken()}`,<br>            },<br>          });<br>          const profileData = await response.json();<br>          setProfile(profileData);<br>        } catch (error) {<br>          console.error(&#39;Failed to fetch profile:&#39;, error);<br>        }<br>      }<br>    };</pre><pre>    fetchProfile();<br>  }, [state.isAuthenticated]);</pre><pre>  if (!profile) return &lt;div&gt;Loading...&lt;/div&gt;;</pre><pre>  return (<br>    &lt;Card&gt;<br>      &lt;CardHeader&gt;<br>        &lt;CardTitle&gt;User Profile&lt;/CardTitle&gt;<br>      &lt;/CardHeader&gt;<br>      &lt;CardContent&gt;<br>        &lt;div className=&quot;space-y-4&quot;&gt;<br>          &lt;div&gt;<br>            &lt;Label&gt;Username&lt;/Label&gt;<br>            &lt;p&gt;{profile.username}&lt;/p&gt;<br>          &lt;/div&gt;<br>          &lt;div&gt;<br>            &lt;Label&gt;Name&lt;/Label&gt;<br>            &lt;p&gt;{profile.name}&lt;/p&gt;<br>          &lt;/div&gt;<br>          &lt;div&gt;<br>            &lt;Label&gt;Email&lt;/Label&gt;<br>            &lt;p&gt;{profile.email}&lt;/p&gt;<br>          &lt;/div&gt;<br>          &lt;div&gt;<br>            &lt;Label&gt;Contact Number&lt;/Label&gt;<br>            &lt;p&gt;{profile.contactNumber || &#39;Not provided&#39;}&lt;/p&gt;<br>          &lt;/div&gt;<br>          &lt;div&gt;<br>            &lt;Label&gt;Country&lt;/Label&gt;<br>            &lt;p&gt;{profile.country || &#39;Not provided&#39;}&lt;/p&gt;<br>          &lt;/div&gt;<br>          &lt;div&gt;<br>            &lt;Label&gt;Roles&lt;/Label&gt;<br>            &lt;div className=&quot;flex gap-2&quot;&gt;<br>              {profile.roles.map(role =&gt; (<br>                &lt;Badge key={role} variant=&quot;outline&quot;&gt;{role}&lt;/Badge&gt;<br>              ))}<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/CardContent&gt;<br>    &lt;/Card&gt;<br>  );<br>}</pre><h3>Access Token Validation for Order Management</h3><p><strong>Secure Order Operations</strong>:</p><p>java</p><pre>@RestController<br>@RequestMapping(&quot;/api/orders&quot;)<br>public class OrderController {<br>    <br>    @PostMapping<br>    @PreAuthorize(&quot;hasRole(&#39;USER&#39;)&quot;)<br>    public ResponseEntity&lt;OrderDTO&gt; createOrder(@Valid @RequestBody OrderDTO orderDTO,<br>                                                Authentication authentication) {<br>        // Extract username from authenticated token<br>        String username = AuthenticationUtil.extractUsernameFromAuth(authentication);<br>        <br>        // Set user context for the order<br>        orderDTO.setUserId(username);<br>        <br>        // Validate order data<br>        validateOrderData(orderDTO);<br>        <br>        OrderDTO createdOrder = orderService.createOrder(orderDTO);<br>        return ResponseEntity.status(HttpStatus.CREATED).body(createdOrder);<br>    }<br>    <br>    @GetMapping<br>    @PreAuthorize(&quot;hasRole(&#39;USER&#39;)&quot;)<br>    public ResponseEntity&lt;List&lt;OrderDTO&gt;&gt; getUserOrders(Authentication authentication) {<br>        String username = AuthenticationUtil.extractUsernameFromAuth(authentication);<br>        List&lt;OrderDTO&gt; orders = orderService.getOrdersByUserId(username);<br>        return ResponseEntity.ok(orders);<br>    }<br>    <br>    @GetMapping(&quot;/{id}&quot;)<br>    @PreAuthorize(&quot;hasRole(&#39;USER&#39;)&quot;)<br>    public ResponseEntity&lt;OrderDTO&gt; getOrder(@PathVariable String id, <br>                                             Authentication authentication) {<br>        String username = AuthenticationUtil.extractUsernameFromAuth(authentication);<br>        OrderDTO order = orderService.getOrderById(id);<br>        <br>        // Ensure user can only access their own orders<br>        if (!order.getUserId().equals(username) &amp;&amp; !AuthenticationUtil.isAdmin(authentication)) {<br>            throw new AccessDeniedException(&quot;Cannot access other user&#39;s orders&quot;);<br>        }<br>        <br>        return ResponseEntity.ok(order);<br>    }<br>    <br>    private void validateOrderData(OrderDTO orderDTO) {<br>        if (orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) {<br>            throw new IllegalArgumentException(&quot;Order must contain at least one item&quot;);<br>        }<br>        <br>        // Validate each order item<br>        for (OrderItemDTO item : orderDTO.getItems()) {<br>            if (item.getQuantity() &lt;= 0) {<br>                throw new IllegalArgumentException(&quot;Item quantity must be positive&quot;);<br>            }<br>            if (item.getUnitPrice().compareTo(BigDecimal.ZERO) &lt;= 0) {<br>                throw new IllegalArgumentException(&quot;Item price must be positive&quot;);<br>            }<br>        }<br>    }<br>}</pre><p><strong>Authentication Utility</strong>:</p><p>java</p><pre>@Component<br>public class AuthenticationUtil {<br>    <br>    public static String extractUsernameFromAuth(Authentication authentication) {<br>        if (authentication instanceof JwtAuthenticationToken jwtAuth) {<br>            Jwt jwt = jwtAuth.getToken();<br>            return extractUsernameFromJwt(jwt);<br>        }<br>        <br>        if (authentication.getPrincipal() instanceof String) {<br>            return (String) authentication.getPrincipal();<br>        }<br>        <br>        return authentication.getName();<br>    }<br>    <br>    private static String extractUsernameFromJwt(Jwt jwt) {<br>        String[] claimNames = {<br>            &quot;preferred_username&quot;, &quot;email&quot;, &quot;username&quot;, &quot;sub&quot;<br>        };<br>        <br>        for (String claimName : claimNames) {<br>            String value = jwt.getClaimAsString(claimName);<br>            if (value != null &amp;&amp; !value.trim().isEmpty()) {<br>                return value;<br>            }<br>        }<br>        <br>        return jwt.getSubject();<br>    }<br>    <br>    public static boolean isAdmin(Authentication authentication) {<br>        return authentication.getAuthorities().stream()<br>                .map(GrantedAuthority::getAuthority)<br>                .anyMatch(authority -&gt; <br>                    authority.equals(&quot;ROLE_ADMIN&quot;) || authority.equals(&quot;ADMIN&quot;));<br>    }<br>}</pre><p><strong>Frontend Order Management with Token Validation</strong>:</p><p>typescript</p><pre>// Order service with automatic token inclusion<br>export class OrdersService {<br>  constructor(private apiClient: ApiClient) {}<br>  <br>  async createOrder(orderData: CreateOrderRequest): Promise&lt;Order&gt; {<br>    console.log(&#39;Creating order with authenticated request&#39;);<br>    <br>    // ApiClient automatically includes Authorization header from auth context<br>    const response = await this.apiClient.post&lt;Order&gt;(&#39;/api/orders&#39;, orderData);<br>    <br>    console.log(&#39;Order created successfully:&#39;, response.id);<br>    return response;<br>  }<br>  <br>  async getUserOrders(): Promise&lt;Order[]&gt; {<br>    // Token validation happens automatically in API client<br>    return await this.apiClient.get&lt;Order[]&gt;(&#39;/api/orders&#39;);<br>  }<br>  <br>  async getOrder(orderId: string): Promise&lt;Order&gt; {<br>    return await this.apiClient.get&lt;Order&gt;(`/api/orders/${orderId}`);<br>  }<br>}</pre><pre>// API Client with automatic token management<br>export class ApiClient {<br>  private async getHeaders(): Promise&lt;Record&lt;string, string&gt;&gt; {<br>    const headers: Record&lt;string, string&gt; = {<br>      &#39;Content-Type&#39;: &#39;application/json&#39;,<br>      &#39;Accept&#39;: &#39;application/json&#39;,<br>    };</pre><pre>    if (this.authService.isAuthenticated()) {<br>      const token = await this.authService.getAccessToken();<br>      if (token) {<br>        headers.Authorization = `Bearer ${token}`;<br>        console.log(&#39;Authorization header set for API request&#39;);<br>      }<br>    }</pre><pre>    return headers;<br>  }<br>}</pre><h3>Purchase Order System with Sri Lankan Validation</h3><p><strong>Backend Purchase Validation</strong>:</p><p>java</p><pre>@RestController<br>@RequestMapping(&quot;/api/purchases&quot;)<br>public class PurchaseController {<br>    <br>    @PostMapping<br>    @PreAuthorize(&quot;hasRole(&#39;USER&#39;)&quot;)<br>    public ResponseEntity&lt;PurchaseDTO&gt; createPurchase(@Valid @RequestBody PurchaseDTO purchaseDTO,<br>                                                      Authentication authentication) {<br>        // Extract and validate user<br>        String username = AuthenticationUtil.extractUsernameFromAuth(authentication);<br>        purchaseDTO.setUsername(username);<br>        <br>        // Validate Sri Lankan specific data<br>        validateSriLankanData(purchaseDTO);<br>        <br>        PurchaseDTO createdPurchase = purchaseService.createPurchase(purchaseDTO);<br>        return ResponseEntity.status(HttpStatus.CREATED).body(createdPurchase);<br>    }<br>    <br>    private void validateSriLankanData(PurchaseDTO purchaseDTO) {<br>        // Validate delivery location (Sri Lankan districts)<br>        if (!DeliveryLocation.isValid(purchaseDTO.getDeliveryLocation())) {<br>            throw new IllegalArgumentException(&quot;Invalid delivery location for Sri Lanka&quot;);<br>        }<br>        <br>        // Validate delivery time<br>        if (!DeliveryTime.isValid(purchaseDTO.getDeliveryTime())) {<br>            throw new IllegalArgumentException(&quot;Invalid delivery time&quot;);<br>        }<br>        <br>        // Validate delivery date (no Sundays)<br>        if (purchaseDTO.getPurchaseDate().getDayOfWeek() == DayOfWeek.SUNDAY) {<br>            throw new IllegalArgumentException(&quot;Delivery not available on Sundays&quot;);<br>        }<br>        <br>        // Validate product name from predefined list<br>        if (!ProductName.isValid(purchaseDTO.getProductName())) {<br>            throw new IllegalArgumentException(&quot;Invalid product name&quot;);<br>        }<br>    }<br>}</pre><p><strong>Custom Validation Annotations</strong>:</p><p>java</p><pre>@Target({ElementType.FIELD})<br>@Retention(RetentionPolicy.RUNTIME)<br>@Constraint(validatedBy = DeliveryDateValidator.class)<br>public @interface ValidDeliveryDate {<br>    String message() default &quot;Delivery date must be today or in the future and not on Sunday&quot;;<br>    Class&lt;?&gt;[] groups() default {};<br>    Class&lt;? extends Payload&gt;[] payload() default {};<br>}</pre><pre>public class DeliveryDateValidator implements ConstraintValidator&lt;ValidDeliveryDate, LocalDate&gt; {<br>    <br>    @Override<br>    public boolean isValid(LocalDate date, ConstraintValidatorContext context) {<br>        if (date == null) return false;<br>        <br>        LocalDate today = LocalDate.now();<br>        <br>        // Must be today or future<br>        if (date.isBefore(today)) return false;<br>        <br>        // Cannot be Sunday<br>        return date.getDayOfWeek() != DayOfWeek.SUNDAY;<br>    }<br>}</pre><h3>Rate Limiting &amp; DDoS Protection</h3><p><strong>Implementation</strong>:</p><p>java</p><pre>@Component<br>public class RateLimitingFilter implements Filter {<br>    <br>    private final ConcurrentHashMap&lt;String, Bucket&gt; buckets = new ConcurrentHashMap&lt;&gt;();<br>    <br>    @Override<br>    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) <br>            throws IOException, ServletException {<br>        <br>        HttpServletRequest httpRequest = (HttpServletRequest) request;<br>        HttpServletResponse httpResponse = (HttpServletResponse) response;<br>        <br>        String clientIp = getClientIP(httpRequest);<br>        Bucket bucket = buckets.computeIfAbsent(clientIp, this::createBucket);<br>        <br>        if (bucket.tryConsume(1)) {<br>            chain.doFilter(request, response);<br>        } else {<br>            httpResponse.setStatus(429);<br>            httpResponse.setContentType(&quot;application/json&quot;);<br>            httpResponse.getWriter().write(<br>                &quot;{\&quot;error\&quot;: \&quot;Too many requests\&quot;, \&quot;message\&quot;: \&quot;Rate limit exceeded\&quot;}&quot;<br>            );<br>        }<br>    }<br>    <br>    private Bucket createBucket(String key) {<br>        Bandwidth limit = Bandwidth.classic(100, Refill.intervally(10, Duration.ofSeconds(1)));<br>        return Bucket.builder().addLimit(limit).build();<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e343c354515b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Spring Boot]]></title>
            <link>https://medium.com/@minindubim/getting-started-with-spring-boot-960be3665fc2?source=rss-67f2f7be01d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/960be3665fc2</guid>
            <dc:creator><![CDATA[Minindu Bimsara Abeywardena]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 19:37:01 GMT</pubDate>
            <atom:updated>2025-03-31T19:37:01.597Z</atom:updated>
            <content:encoded><![CDATA[<p>As a newcomer to the world of Spring Boot, you’re stepping into one of the most powerful frameworks for building Java-based applications. Its simplicity, scalability, and robust features make it a favorite among developers. However, diving into Spring Boot for the first time can feel overwhelming. This guide is designed to help you understand <strong>why Spring Boot is important</strong> and <strong>how to effectively get started</strong>.</p><h3>Why Spring Boot?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*mAq26rfUWCtLfOSE.png" /></figure><p>Spring Boot is built on top of the popular Spring Framework, simplifying its complexities while retaining its power. Here are some key reasons why it’s widely adopted:</p><ol><li><strong>Rapid Development</strong>:<br> Spring Boot eliminates the need for extensive configuration, allowing you to focus on writing business logic. Features like embedded servers and auto-configuration mean you can get started quickly.</li><li><strong>Microservices Made Easy</strong>:<br> With Spring Boot, you can develop standalone microservices that are lightweight, efficient, and scalable.</li><li><strong>Out-of-the-Box Tools</strong>:<br> Spring Boot comes with built-in tools for monitoring, security, and deployment, making it a comprehensive solution for modern application development.</li><li><strong>Community Support</strong>:<br> Backed by a vast community and excellent documentation, Spring Boot provides ample resources for troubleshooting and learning.</li><li><strong>Integration Ready</strong>:<br> Whether you’re working with databases, messaging queues, or cloud platforms, Spring Boot seamlessly integrates with various tools and technologies.</li></ol><h3>How to Tackle Spring Boot as a Beginner</h3><p>Starting with Spring Boot may seem daunting, but with the right approach, you can master it quickly. Here’s a step-by-step plan:</p><h4>1. Set Up Your Environment</h4><p>Before you write your first line of code, make sure you have everything ready:</p><ul><li><strong>Install Java Development Kit (JDK)</strong>: Ensure you have JDK 11 or later installed.</li><li><strong>Choose an IDE</strong>: IntelliJ IDEA or Eclipse are great for Spring Boot development.</li><li><strong>Install Maven or Gradle</strong>: These build tools are essential for managing dependencies and projects.</li><li><strong>Download Spring Tool Suite (STS)</strong>: A Spring-specific IDE, if you want additional support.</li></ul><h4>2. Understand the Basics</h4><p>Spend time understanding the core concepts:</p><ul><li><strong>Dependency Injection (DI)</strong>: A cornerstone of Spring that simplifies managing object dependencies.</li><li><strong>Annotations</strong>: Learn key Spring Boot annotations like @SpringBootApplication, @RestController, @Autowired, and @Service.</li><li><strong>Beans</strong>: Understand how Spring Boot manages objects using the Bean Factory.</li></ul><h4>3. Start Small</h4><p>Begin with a simple application to build your confidence:</p><ul><li>Use the <strong>Spring Initializr</strong> (start.spring.io) to generate a basic Spring Boot project with your chosen dependencies.</li><li>Create a basic REST API with a single endpoint. For example, a GET /hello endpoint that returns “Hello, World!”.</li><li>Learn to run your application using the embedded Tomcat server (java -jar &lt;your-application&gt;.jar).</li></ul><h4>4. Explore Key Features</h4><p>Once you’ve created a basic application, explore Spring Boot’s essential features:</p><ul><li><strong>Configuration</strong>: Learn about application.properties or application.yml for managing configurations.</li><li><strong>Spring Data JPA</strong>: Use this to connect to databases with minimal boilerplate code.</li><li><strong>Spring Security</strong>: Add basic authentication and authorization to your app.</li><li><strong>Actuator</strong>: Use this for monitoring and managing your application in production.</li></ul><h4>5. Learn Debugging and Testing</h4><p>Testing is crucial in modern development:</p><ul><li>Write <strong>unit tests</strong> for your services and controllers using JUnit and Mockito.</li><li>Use <strong>Spring Boot Test</strong> for integration testing to ensure your components work well together.</li><li>Learn how to debug issues using IDE tools and Spring Boot logs.</li></ul><h4>6. Gradually Scale Up</h4><p>As you grow more comfortable:</p><ul><li>Build a CRUD application that interacts with a database.</li><li>Introduce advanced features like caching, messaging (RabbitMQ/Kafka), or scheduling.</li><li>Explore how to containerize your application using Docker and deploy it to a cloud platform like AWS, Azure, or Google Cloud.</li></ul><h3>Tips for a Smooth Learning Journey</h3><ol><li><strong>Follow Tutorials</strong>: Start with beginner-friendly resources like Spring Boot documentation, video tutorials, and community blogs.</li><li><strong>Join the Community</strong>: Engage in Spring Boot communities on platforms like Stack Overflow, GitHub, and Reddit for advice and collaboration.</li><li><strong>Build Projects</strong>: Nothing solidifies learning like practice. Build small projects to test your knowledge.</li><li><strong>Stay Curious</strong>: As you master the basics, dive into advanced topics like Spring Cloud, reactive programming, or distributed systems.</li></ol><h3>Why Spring Boot Matters in Today’s Tech Landscape</h3><p>In the era of cloud-native applications and microservices, frameworks like Spring Boot have become indispensable. Here’s why it’s worth your time and effort:</p><ul><li><strong>Industry Demand</strong>: Knowledge of Spring Boot is often a key requirement for Java developer roles.</li><li><strong>Flexibility</strong>: Its modularity allows developers to build anything from a small REST API to a large-scale enterprise system.</li><li><strong>Future-Proof</strong>: Spring Boot is constantly evolving, keeping up with modern development trends and ensuring its relevance.</li></ul><h3>Conclusion</h3><p>Spring Boot is a game-changer for Java developers. It takes the complexities of the Spring Framework and packages them into an easy-to-use, streamlined solution. While the learning curve might seem steep initially, with the right approach and tools, you’ll soon be building powerful, scalable applications with confidence.</p><p>So, don’t be intimidated — embrace the journey. Start small, explore the possibilities, and let Spring Boot empower your development skills!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=960be3665fc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the MVC Architecture in Web Development]]></title>
            <link>https://medium.com/@minindubim/understanding-the-mvc-architecture-in-web-development-c704771184d5?source=rss-67f2f7be01d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c704771184d5</guid>
            <dc:creator><![CDATA[Minindu Bimsara Abeywardena]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 16:37:27 GMT</pubDate>
            <atom:updated>2024-12-03T16:37:27.398Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of web development, structuring your code for maintainability and efficiency is crucial. One of the most popular design patterns to achieve this is the <strong>Model-View-Controller (MVC)</strong> architecture. MVC is a software architectural pattern that divides an application into three interconnected components, each with distinct responsibilities. This separation makes it easier to organize code, improve scalability, and foster collaboration among developers working on different parts of the application.</p><h3>What is MVC?</h3><p>The MVC pattern is divided into three primary components:</p><ol><li><strong>Model</strong> — Represents the data logic.</li><li><strong>View</strong> — Represents the user interface.</li><li><strong>Controller</strong> — Acts as the brain, managing the interaction between the Model and View.</li></ol><p>These components work together to handle the data flow and rendering of content in a way that optimizes both user experience and code organization. Let’s dive deeper into each of these components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7RQ1sW3KfmTjhvZt.png" /></figure><h3>1. Model: The Data Logic</h3><p>The <strong>Model</strong> is where all the data-related logic resides. This component directly interacts with the database and processes the data that the application needs. For instance, if your application needs to fetch a list of users, the Model will query the database and return the results to the Controller.</p><p>The Model also provides methods for creating, reading, updating, and deleting data (commonly known as CRUD operations). It encapsulates the business logic and ensures that any changes to the data follow the rules defined within the application.</p><p><strong>Responsibilities of the Model:</strong></p><ul><li>Retrieve data and send it to the Controller.</li><li>Accept modifications from the Controller.</li><li>Maintain the structure and integrity of data within the application.</li></ul><h3>2. View: The User Interface (UI)</h3><p>The <strong>View</strong> is responsible for displaying data to the user. It represents the current state of the Model in a format that is easily understandable for users, whether through HTML, CSS, or JavaScript in web applications.</p><p>The View is designed to be dynamic and responsive, updating whenever there are changes in the underlying data model. For example, when a user adds a new item to a list, the View should immediately reflect this change without needing to reload the entire page.</p><p><strong>Responsibilities of the View:</strong></p><ul><li>Display data received from the Controller.</li><li>Update the interface in response to changes in the Model.</li><li>Offer an intuitive and interactive experience for users.</li></ul><h3>3. Controller: The Brain of the Operation</h3><p>The <strong>Controller</strong> is the intermediary that connects the Model and View. It handles user input, processes user actions, and decides how data should be displayed or updated. Whenever a user interacts with the application, the Controller interprets this action and determines what needs to happen next.</p><p>For instance, if a user submits a form, the Controller will validate the data, update the Model, and then instruct the View to display the updated information. Essentially, the Controller directs the flow of data between the Model and the View, ensuring that everything runs smoothly.</p><p><strong>Responsibilities of the Controller:</strong></p><ul><li>Interpret user actions and pass them to the Model or View.</li><li>Initiate the process of retrieving and updating data.</li><li>Coordinate the interaction between the Model and the View.</li></ul><h3>How MVC Works Together</h3><p>The interaction between Model, View, and Controller is structured to create a clear flow of data:</p><ol><li><strong>User Interaction with the View</strong>: When a user interacts with the View (e.g., clicking a button or submitting a form), the View notifies the Controller of this action.</li><li><strong>Controller Processes the Action</strong>: The Controller interprets the user’s action, performs necessary logic, and decides whether to interact with the Model.</li><li><strong>Model Updates Data</strong>: If the Controller needs to change or retrieve data, it communicates with the Model. The Model then updates itself or fetches the required data and sends it back to the Controller.</li><li><strong>View Updates the User Interface</strong>: After receiving data from the Model, the Controller sends it to the View, which then updates the UI to reflect the changes, creating a seamless experience for the user.</li></ol><p>The MVC architecture is popular in web development because it offers several key advantages:</p><ul><li><strong>Separation of Concerns</strong>: Each component has a clear responsibility, which simplifies code organization and makes it easier to maintain.</li><li><strong>Scalability</strong>: The MVC pattern allows for more straightforward scaling as the application grows, as each component can be extended independently.</li><li><strong>Reusability</strong>: Since each component is independent, they can often be reused in different parts of the application or even in other applications.</li><li><strong>Facilitated Collaboration</strong>: With a well-defined structure, multiple developers can work on the Model, View, and Controller components simultaneously, enhancing productivity in larger projects.</li></ul><h3>Conclusion</h3><p>The MVC architecture is a powerful design pattern that brings clarity and organization to web development. By dividing responsibilities between the Model, View, and Controller, MVC makes it easier to develop, maintain, and scale applications. Whether you’re building a simple web page or a complex web application, understanding and implementing MVC can be a game-changer, streamlining the development process and creating a more robust and user-friendly product.</p><p>For web developers, adopting MVC not only improves the quality of your code but also enhances the end-user experience, making it a fundamental pattern worth mastering.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c704771184d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the World of Software Licensing; An In Depth Overview]]></title>
            <link>https://medium.com/@minindubim/exploring-the-world-of-software-licensing-an-in-depth-overview-e9f412fa664e?source=rss-67f2f7be01d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9f412fa664e</guid>
            <dc:creator><![CDATA[Minindu Bimsara Abeywardena]]></dc:creator>
            <pubDate>Thu, 20 Jun 2024 18:45:30 GMT</pubDate>
            <atom:updated>2024-06-20T18:45:30.051Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of software, licensing is a key concept that governs how software can be used, modified, and distributed. Whether you’re a developer, a business owner, or a casual user, understanding software licensing is essential to navigate the legal and operational landscape of software use. This article dives into the complexities of software licenses, their types, and the wider legal landscape in which they work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BCPlAcXZKtbVdcYoJKt6Zg.jpeg" /></figure><h3><strong>What is a Software Licence?</strong></h3><p>A software license is a legal instrument that sets the terms under which software can be used, modified, and distributed. When you purchase or download software, you’re not actually buying the software itself but rather obtaining the right to use it according to specific conditions laid out in the license agreement.</p><p>Software licenses serve multiple purposes:</p><ul><li><strong>Protecting Intellectual Property</strong>: They ensure the developer or company retains control over their creation.</li><li><strong>Defining Usage Rights</strong>: They specify how the software can be used, whether for personal, commercial, or educational purposes.</li><li><strong>Limiting Liability</strong>: They often include disclaimers to protect the licensor from legal issues arising from software use.</li></ul><h3><strong>Types of Software Licenses</strong></h3><p>Software licenses can be categorized into proprietary licenses and open-source licenses. Each category has its own unique purpose and corresponds to different values regarding software distribution and use.</p><h4>1. Proprietary Licenses</h4><p>Proprietary licenses are restrictive in nature and do not allow users to access the source code or redistribute the software freely. The developer or company retains full control over the software.</p><p><strong>Examples of Proprietary Licenses</strong>:</p><ul><li><strong>Microsoft Windows License</strong>: Users can install and use the software but cannot modify or redistribute it.</li><li><strong>Adobe Creative Cloud</strong>: Users subscribe to use the software with restrictions on modification and distribution.</li></ul><p>Key Features:</p><ul><li>Users often need to purchase the license.</li><li>The software is typically distributed in binary form.</li><li>Users have limited rights to modify or share the software.</li></ul><h4>2. Open Source Licenses</h4><p>Open source licenses promote transparency and collaboration by allowing users to access, modify, and redistribute the source code. They vary widely in terms of the permissions and obligations they impose.</p><p><strong>Common Open Source Licenses</strong>:</p><ul><li><strong>GNU General Public License (GPL)</strong>: Requires any derivative work to also be open source and distributed under the same license.</li><li><strong>MIT License</strong>: Permits nearly unrestricted use, modification, and distribution.</li><li><strong>Apache License</strong>: Allows modifications and redistribution with minimal restrictions, often requiring only attribution to the original authors.</li></ul><p>Key Features:</p><ul><li>Source code is openly available.</li><li>Users can modify and distribute the software.</li><li>Licensing terms range from very permissive (like the MIT License) to more restrictive (like the GPL).</li></ul><h3>Copyright Law and Software</h3><p>Copyright law plays a crucial role in software licensing. By default, software is protected under copyright as a literary work, which grants the author exclusive rights to copy, modify, distribute, and publicly display the work.</p><p>Key aspects of copyright in software include:</p><ul><li><strong>Ownership</strong>: The creator or author holds the copyright unless they transfer it to someone else.</li><li><strong>Infringement</strong>: Unauthorized use, copying, or distribution of software is a violation of copyright law.</li><li><strong>Fair Use</strong>: Limited use of copyrighted material without permission may be allowed under specific circumstances, such as for criticism, comment, news reporting, or academic research.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r_ZrY9iGXU7tj0gKBn_jbw.jpeg" /></figure><h3>Ownership vs Licensing</h3><p>One of the most misunderstood aspects of software use is the distinction between owning software and licensing it.</p><h4>Ownership</h4><p>When you own something, you have full control over it. For physical products like a car or a book, ownership means you can use, modify, or sell the item as you please.</p><h4>Licensing</h4><p>With software, users typically do not own the software itself but are granted a license to use it. This license defines:</p><ul><li><strong>Scope of Use</strong>: How and where the software can be used.</li><li><strong>Duration</strong>: How long the license is valid.</li><li><strong>Modification and Redistribution Rights</strong>: Whether the user can alter the software or share it with others.</li></ul><h3>Other Considerations</h3><h4>1. End User License Agreements (EULAs)</h4><p>EULAs are the detailed terms and conditions that users must agree to before using the software. They are legally binding agreements that outline the user’s rights and responsibilities.</p><h4>2. Software as a Service (SaaS)</h4><p>SaaS is a model where software is provided as a service rather than a product. Users typically subscribe to access the software over the internet. Licensing in SaaS often involves ongoing payments and updates.</p><h4>3. Dual Licensing</h4><p>Some software is available under two different licenses, allowing users to choose the one that best meets their needs. This can include a combination of open-source and proprietary licenses.</p><h4>4. Copyleft vs Permissive Licenses</h4><ul><li><strong>Copyleft Licenses</strong>: All derivative works must be published under the same license (e.g., GPL).</li><li><strong>Permissive Licenses</strong>: Allow proprietary use of the software without requiring derivative works to remain open source (e.g., MIT, Apache).</li></ul><h3>Conclusion</h3><p>Understanding software licensing is vital for anyone who interacts with software, from casual users to professional developers. Licenses not only protect the rights of creators but also establish clear guidelines for how software can be used and shared. Whether you’re navigating the terms of a proprietary software purchase or choosing an open-source project to contribute to, a solid grasp of licensing principles will help you make informed decisions and stay compliant with legal requirements.</p><p>As the software landscape continues to evolve, so too will the complexities of licensing. Staying informed and adaptable is key to leveraging software effectively and ethically in an increasingly digital world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9f412fa664e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MySQL Stored Procedures: A Guide to Increasing Database Performance]]></title>
            <link>https://medium.com/@minindubim/mysql-stored-procedures-a-guide-to-increasing-database-performance-077d0f731c2b?source=rss-67f2f7be01d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/077d0f731c2b</guid>
            <dc:creator><![CDATA[Minindu Bimsara Abeywardena]]></dc:creator>
            <pubDate>Fri, 23 Feb 2024 17:22:23 GMT</pubDate>
            <atom:updated>2024-02-23T17:22:23.589Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>MySQL</strong> is one of the most widely used database management systems available, with a wealth of functionality to facilitate efficient data handling. Among its many features, stored procedures stand out as a potent instrument that can improve overall efficiency and streamline database operations. Let’s explore the world of stored procedures, learning about its fundamentals, benefits, drawbacks, and efficient use in MySQL.</p><h3><strong>What are Stored Procedures?</strong></h3><p>sets of SQL statements kept inside the MySQL database server are called stored procedures. With just a single call to the procedure, developers can carry out a variety of activities and sophisticated inquiries thanks to these precompiled and preserved procedures. They essentially promote modularity and ease maintenance by encapsulating a number of SQL commands into a reusable unit.</p><h3><strong>Advantages of Stored Procedures:</strong></h3><ol><li><strong>Improved Performance: </strong>By precompiling and storing stored procedures in the database, performance is improved by lowering the overhead of parsing and optimising queries while they are being executed.</li><li><strong>Enhanced Security:</strong> Administrators can more successfully establish access restrictions and enforce security rules by centralising data access using stored procedures, reducing the dangers connected with direct table access.</li><li><strong>Enhance Code Reusability: </strong>By allowing typical database actions to be encapsulated as stored procedures, developers can reduce redundancy and promote consistency by using these procedures across numerous applications.</li><li><strong>Simplified Maintenance:</strong> By removing the requirement to update application code, changes or additions to database logic may be made centrally within stored procedures, simplifying maintenance and lowering the chance of mistakes.</li><li><strong>Transaction Management:</strong> Stored procedures facilitate transaction management by allowing multiple SQL statements to be executed as a single atomic operation, ensuring data integrity and consistency.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fyp04kzdyGzQ9HNX9IS1ag.jpeg" /><figcaption>Old Database’s Stored Procedures.</figcaption></figure><h3><strong>Disadvantages of Stored Procedures:</strong></h3><p><strong>1.Vendor Dependency:</strong> Because stored procedures are database-specific, they might make it difficult to move data across different database systems and result in vendor lock-in. <br> <br>2.<strong>Debugging Complexity:</strong> Because stored procedures lack the debugging tools found in typical programming languages, debugging them can be difficult, particularly when working with vast codebases or sophisticated logic.</p><p>3.<strong>Restricted Language Support:</strong> The expressiveness and versatility of stored procedures may be limited by the fact that MySQL’s stored procedure language is not as feature-rich as programming languages like Java or Python.</p><p>4.<strong>Increased Database Load:</strong> Stored procedures can reduce network traffic and thereby enhance performance, but they can also add extra processing cost to the query compilation and execution process, which can put more strain on the database server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2QuT1502MC1uHHKMNpyRGw.jpeg" /><figcaption>Modern Database.</figcaption></figure><h3>How to Write and Execute Stored Procedures in MySQL:</h3><p>Writing and executing stored procedures in MySQL involves a series of steps:</p><ol><li>Create a Stored Procedure: Use the CREATE PROCEDURE statement to define a new stored procedure, specifying its name, parameters, and SQL statements within a block.</li></ol><pre>DELIMITER //<br>CREATE PROCEDURE GetEmployee(IN employee_id INT)<br>BEGIN<br>    SELECT * FROM employees WHERE id = employee_id;<br>END //<br>DELIMITER ;</pre><p>2. Execute a Stored Procedure: Use the CALL statement to execute a stored procedure, passing any required parameters.</p><pre>CALL GetEmployee(101);</pre><p>3. Drop a Stored Procedure: If necessary, you can drop a stored procedure using the DROP PROCEDURE statement.</p><pre>DROP PROCEDURE GetEmployee;</pre><h3>Example Use Case:</h3><p>Consider a scenario where a retail company needs to track inventory levels and generate reports on product sales. By leveraging stored procedures, the company can streamline these operations and improve efficiency.</p><ol><li>Inventory management: Whenever new stock arrives or goods are sold, a stored procedure called ‘UpdateInventory’ can be built to handle inventory updates. This process can change the number of products in the database and set off low stock level alarms.</li><li>Sales Reporting: To compile sales information, compute revenues, and provide thorough reports for management assessment, a different stored procedure called ‘GenerateSalesReport’ can be created. You can plan this process to run on a regular basis to get the most recent information about sales performance.</li></ol><p>By employing stored procedures, the retail company can automate critical tasks, minimize manual intervention, and maintain accurate inventory records, ultimately driving business growth and profitability.</p><p>In conclusion, In MySQL, stored procedures are essential resources for maximising database speed, strengthening security, and encouraging code reuse. Although they have certain disadvantages, they are nevertheless a very useful tool for database administrators and developers since they outweigh the disadvantages. Stored procedures have the potential to completely transform database management and open the door to more scalable and effective applications when implemented correctly and in accordance with best practices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=077d0f731c2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>