<?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 Kiran R on Medium]]></title>
        <description><![CDATA[Stories by Kiran R on Medium]]></description>
        <link>https://medium.com/@kiranchowdhary?source=rss-1c7dd04b732b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*169zIKF8DKcxnPRCJCRgJQ.jpeg</url>
            <title>Stories by Kiran R on Medium</title>
            <link>https://medium.com/@kiranchowdhary?source=rss-1c7dd04b732b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:30:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kiranchowdhary/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[Revolutionizing Enterprise Deal Negotiations with AI: How LLMs and MCP are Transforming Pricing…]]></title>
            <link>https://medium.com/@kiranchowdhary/revolutionizing-enterprise-deal-negotiations-with-ai-how-llms-and-mcp-are-transforming-pricing-6399998a8c80?source=rss-1c7dd04b732b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6399998a8c80</guid>
            <category><![CDATA[enterprise-sales]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[pricing-strategy]]></category>
            <category><![CDATA[sales-automation]]></category>
            <dc:creator><![CDATA[Kiran R]]></dc:creator>
            <pubDate>Sat, 13 Sep 2025 18:08:22 GMT</pubDate>
            <atom:updated>2025-09-26T20:05:31.618Z</atom:updated>
            <content:encoded><![CDATA[<h3>Revolutionizing Enterprise Deal Negotiations with AI: <em>How AI and LLMs Are Transforming Enterprise Deal Negotiations and Pricing Strategies</em></h3><blockquote>“Negotiation is no longer just an art — it’s becoming a science powered by AI.”</blockquote><h3>🌟 The Problem with Traditional Deal Negotiations</h3><p>Negotiation has always been a critical skill for enterprise growth, but traditional methods are slow, manual, and inconsistent.<br> In large organizations, deal negotiations involve multiple stakeholders, complex pricing models, and fast-changing market conditions.</p><p>Despite the availability of advanced analytics, many negotiations still depend on:</p><ul><li>Fragmented data living in silos.</li><li>Individual sales reps’ intuition and past experiences.</li><li>Manual coordination between departments like finance, legal, and operations.</li></ul><p>This leads to inefficiencies and missed opportunities:</p><ul><li>Delayed responses to customer inquiries.</li><li>Inconsistent pricing decisions, which erode trust and margins.</li><li>Limited scalability as organizations grow.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wblWwwX5tJJYL9ccaTOMIw.png" /><figcaption>Traditional deal negotiations rely heavily on manual steps, leading to inefficiencies.</figcaption></figure><h3>🤖 Our Solution: AI-Powered Automated Negotiation</h3><p>To address these challenges, we developed a <strong>multi-agent AI system</strong> that leverages <strong>Large Language Models (LLMs)</strong> and <strong>Model Context Protocol (MCP)</strong> to automate and optimize negotiation workflows.</p><h3>Why MCP?</h3><p>MCP acts as a bridge connecting multiple specialized AI agents and external data sources.<br> It ensures seamless communication between systems like:</p><ul><li>Market intelligence platforms</li><li>Financial health monitoring tools</li><li>Pricing databases</li><li>Negotiation strategy models</li></ul><p>This allows for real-time, data-driven decisions, reducing the dependency on manual processes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RfFGLufq1t_eocRcIDzNsw.png" /><figcaption>Our system integrates specialized agents through the MCP framework to automate negotiation.</figcaption></figure><h3>🔍 How It Works</h3><p>Imagine a sales representative preparing for a high-stakes negotiation.<br> Instead of scrambling to gather data manually, they simply submit a query like:</p><blockquote>“What’s the optimal pricing strategy for Enterprise Customer XYZ?”</blockquote><p>The system automatically:</p><ol><li><strong>Fetches relevant data</strong> — Historical pricing, current market trends, competitor moves.</li><li><strong>Analyzes customer sentiment</strong> using AI-driven NLP on news and social feeds.</li><li><strong>Forecasts potential margin scenarios</strong> using advanced predictive models.</li><li><strong>Runs simulations</strong> to identify floor and ceiling prices for negotiation.</li><li><strong>Delivers actionable recommendations</strong> directly to the sales dashboard.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J7-OkdxhLmndULJv5fhT-Q.png" /><figcaption>End-to-end workflow for automated negotiation powered by LLMs and MCP.</figcaption></figure><h3>📈 Business Impact</h3><p>The results of implementing this system are <strong>transformative</strong>, not just incremental.<br> By automating negotiation intelligence, organizations can achieve:</p><ul><li><strong>25–40% improvement in deal margins</strong> thanks to better pricing strategies.</li><li><strong>40–60% faster negotiation cycle times</strong>, shortening sales pipelines.</li><li><strong>20–35% increase in win rates</strong>, due to smarter, data-backed decisions.</li><li><strong>Higher customer trust</strong> with transparent and consistent pricing.</li></ul><h3>⚙️ Technical Architecture</h3><p>Our system is built on a <strong>layered, modular design</strong> to ensure scalability and ease of integration.</p><h3>Layers Explained:</h3><ol><li><strong>Top Layer — Sales Interface</strong></li></ol><ul><li>Tools like CRM dashboards, chatbots, or Copilot integrations where sales reps interact with the system.</li></ul><p><strong>2. Middle Layer — Orchestration Engine</strong></p><ul><li>The <strong>LLM + MCP Host</strong>, which manages communication between all components.</li></ul><p><strong>3. Bottom Layer — Specialized Agents</strong></p><p>a. Independent AI modules focused on specific functions:</p><ul><li>Pricing Intelligence</li><li>Financial Sentiment Analysis</li><li>Margin Forecasting</li><li>Scenario Simulation</li></ul><p>This structure ensures that new data sources or AI capabilities can be added without disrupting the overall workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GBz_Wxsn5uY5Sh-CRzenow.png" /><figcaption>Technical structure showing MCP as the backbone connecting AI agents.</figcaption></figure><h3>🧠 Real-World Example</h3><p>Imagine a payment services provider negotiating with a large retail chain:</p><ul><li>The <strong>Financial Health Agent</strong> detects declining quarterly revenue for the retailer.</li><li><strong>Market Sentiment Agent</strong> notices negative social media chatter about recent price hikes.</li><li><strong>Pricing Simulation Agent</strong> models different discount structures, showing how a 12% discount would improve retention while maintaining profit margins.</li></ul><p>Within seconds, the sales rep receives:</p><ul><li>A <strong>recommended negotiation script</strong></li><li>A <strong>clear price range</strong>, allowing them to act confidently and close the deal.</li></ul><h3>🚀 Looking Ahead</h3><p>This research is just the <strong>first step</strong> toward fully autonomous negotiations.<br> Future directions include:</p><ul><li><strong>Reinforcement learning</strong> to continuously refine negotiation tactics.</li><li>Support for <strong>multi-party negotiations</strong>, not just one-on-one deals.</li><li>Advanced <strong>real-time adaptive pricing</strong> as market conditions change.</li></ul><p>Organizations adopting these systems early will gain a <strong>sustainable competitive edge</strong> in an increasingly data-driven marketplace.</p><h3>🎉 Acknowledgments</h3><p>This work was made possible by a talented team: <strong>Chirag Soni, Swati Shah, Avi Reddy, Mahesh Toro, Rishab Rishi Sharma &amp; Me</strong></p><p>Special thanks to our colleagues at PayPal for supporting this research.</p><p>Read the full paper here:<br> <a href="https://doi.org/10.5121/ijaia.2025.16504">https://doi.org/10.5121/ijaia.2025.16504</a></p><h3>🌐 Final Thoughts</h3><p>Negotiations will always require a human touch — building trust, relationships, and shared value.<br> But with <strong>AI handling the complexity</strong>, sales teams can focus on what they do best: <strong>closing deals and delighting customers</strong>.</p><p>The future of enterprise negotiation is <strong>autonomous, intelligent, and deeply human-centered — </strong>And it’s already here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6399998a8c80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Artificial Intelligence: Advantages, Limitations, and the Road Ahead]]></title>
            <link>https://medium.com/@kiranchowdhary/artificial-intelligence-advantages-limitations-and-the-road-ahead-0c6899bd6e90?source=rss-1c7dd04b732b------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c6899bd6e90</guid>
            <category><![CDATA[ai-specialist]]></category>
            <category><![CDATA[ai-advantage]]></category>
            <category><![CDATA[ai-limitation]]></category>
            <category><![CDATA[ai-future]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Kiran R]]></dc:creator>
            <pubDate>Wed, 06 Aug 2025 18:09:35 GMT</pubDate>
            <atom:updated>2025-08-06T18:26:05.956Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“AI is not here to replace humans — it’s here to amplify what we can achieve together.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zuz-4DwmfdrOvESEBXLD2A.png" /><figcaption>Specialist AI models working together can outperform a single all-purpose model.</figcaption></figure><p>Artificial Intelligence (AI) has moved from science fiction to everyday reality.<br> From Netflix recommendations to medical diagnostics and self-driving cars, AI is reshaping industries at lightning speed.</p><p>But like any powerful tool, AI comes with <strong>strengths</strong> that inspire innovation and <strong>limitations</strong> that demand caution.<br> Let’s break it down.</p><h3>🚀 Advantages of Artificial Intelligence</h3><h4>1. Automation of Repetitive Tasks</h4><p>AI thrives on routine, rule-based work.<br> Think <strong>customer service chatbots</strong>, <strong>automated claims processing</strong>, or <strong>inventory tracking</strong>.<br> This frees humans to focus on creativity and strategy.</p><h4>2. Data-Driven Decision Making</h4><p>AI can crunch <strong>massive datasets</strong> in seconds, revealing patterns and insights invisible to humans.<br> This leads to smarter decisions in finance, healthcare, logistics, and more.</p><h4>3. Always-On Availability</h4><p>Unlike humans, AI doesn’t need breaks, weekends, or holidays.<br> Perfect for <strong>24/7 customer support</strong> and <strong>real-time monitoring</strong> systems.</p><h4>4. Personalization at Scale</h4><p>From <strong>e-commerce recommendations</strong> to <strong>adaptive learning platforms</strong>, AI tailors experiences to individuals — at a scale impossible for humans to match.</p><h4>5. Enhanced Accuracy</h4><p>In areas like <strong>medical imaging</strong>, AI often matches or surpasses human accuracy.<br> In manufacturing, AI detects microscopic defects humans might miss.</p><h4>6. Operating in Dangerous Environments</h4><p>AI-powered machines explore <strong>deep oceans</strong>, <strong>outer space</strong>, and <strong>disaster zones</strong> — keeping humans out of harm’s way.</p><h3>⚠️ Limitations of Artificial Intelligence</h3><h4>1. Data Dependence</h4><p>Without <strong>large, high-quality datasets</strong>, AI performance plummets.<br> Biased or incomplete data leads to flawed decisions.</p><h4>2. Narrow Intelligence</h4><p>Today’s AI is “narrow” — built for specific tasks.<br> An AI that detects cancer in X-rays can’t also write poetry or drive a car.</p><h4>3. Lack of Explainability</h4><p>Many AI models are <strong>black boxes</strong>.<br> They give answers but can’t easily explain how they arrived at them — a major hurdle for regulated industries.</p><h4>4. Bias and Fairness Issues</h4><p>AI inherits human bias from its training data.<br> This can cause <strong>unfair outcomes</strong> in hiring, lending, and law enforcement.</p><h4>5. The Multi-Source Integration Gap</h4><p>Right now, no single AI model can effortlessly access all your data — <strong>private, public, real-time, and historical</strong> — in one place.</p><ul><li>Data silos make integration hard.</li><li>Context window limits restrict how much a model can process at once.</li><li>Tools like <strong>RAG</strong>, <strong>MCP</strong>, and <strong>agent-based AI</strong> are bridging the gap, but it’s still a work in progress.</li></ul><h4>6. High Computational Cost</h4><p>Training large models demands <strong>huge computing power</strong>, making AI expensive and energy-intensive.</p><h4>7. Vulnerability to Adversarial Attacks</h4><p>Small, malicious tweaks to input data can trick AI into making dangerous mistakes.</p><h4>8. Ethical and Legal Challenges</h4><p>From privacy to accountability, AI raises <strong>tough questions</strong> about responsibility when things go wrong.</p><h3>🧠 A Smarter Philosophy: Specialist AI Models</h3><p>A common misconception is that we should train <strong>every model on everything</strong> — but this is inefficient, costly, and often less accurate.</p><p>Instead, imagine <strong>specialist AI models</strong>:</p><ul><li>Each trained deeply on a <strong>specific concept or domain</strong>.</li><li>Acting as an <strong>expert</strong> in its field.</li><li>Coordinated by an <strong>orchestration framework</strong> to solve complex problems together.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CyvUukKZeucfYIv0Q03ZwA.png" /><figcaption><strong><em>Why one giant model when a team of AI specialists can do it better?</em></strong></figcaption></figure><h3>Why This Philosophy Works</h3><h4>1. It Overcomes LLM Memory &amp; Storage Limits</h4><p>Large Language Models (LLMs) have <strong>finite context windows</strong> — they can’t “remember” or process unlimited data at once. By training smaller, domain-focused models, each can store <strong>only what’s necessary</strong> for its specialty.</p><h4>2. It’s Cost-Efficient</h4><p>Training one massive model on every topic is extremely expensive in compute, time, and storage.<br> Smaller expert models require fewer resources, making them <strong>cheaper to train and update</strong>.</p><h4>3. Accuracy Improves in Specialized Tasks</h4><p>Generalist models sometimes get distracted by irrelevant patterns. Specialists, focused on a single domain, <strong>make cleaner, more reliable predictions</strong>.</p><h4>4. Easier Updates</h4><p>If new medical research comes out, you only retrain the <strong>medical AI expert</strong>, not the entire ecosystem. This is faster and reduces risk of breaking unrelated capabilities.</p><h4>5. Mirrors Human Collaboration</h4><p>This architecture works like <strong>real-world organizations</strong> — specialists (lawyers, doctors, engineers) working together through a coordinator.<br> In AI, an <strong>orchestrator</strong> routes queries to the right expert and merges their responses for the user.</p><blockquote>Think of it like a hospital: you don’t have one doctor for everything — you have specialists who collaborate to deliver the best care.</blockquote><h3>🔮 The Road Ahead</h3><p>Here’s where AI is headed:</p><ul><li><strong>Unified Data Access</strong> — Secure, real-time integration across silos.</li><li><strong>Explainable AI (XAI)</strong> — Models that show their reasoning.</li><li><strong>Hybrid AI Systems</strong> — Combining symbolic reasoning with deep learning.</li><li><strong>Specialist AI Ecosystems</strong> — Multiple expert models working in harmony.</li><li><strong>Green AI</strong> — Lowering the environmental impact of AI training.</li><li><strong>Stronger Regulation</strong> — Balancing safety with innovation.</li></ul><h3>🏁 Conclusion</h3><p>AI’s advantages can <strong>revolutionize industries</strong>, but its limitations can’t be ignored.<br> The <strong>future of AI</strong> may not be about one giant model that knows everything, but a network of <strong>specialized experts</strong> that collaborate — just like humans do.</p><p>By embracing this <strong>specialist AI philosophy</strong>, we can make systems that are:</p><ul><li>More accurate</li><li>More cost-effective</li><li>Easier to maintain</li><li>Better aligned with how humans actually solve problems</li></ul><p>The challenge is clear: <strong>build AI that’s accurate, responsible, and truly helpful</strong>.<br> The opportunity? Even greater.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c6899bd6e90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bridging the AI Governance Gap: A Framework for Real-Time Cybersecurity and Adaptive Privacy…]]></title>
            <link>https://medium.com/@kiranchowdhary/bridging-the-ai-governance-gap-a-framework-for-real-time-cybersecurity-and-adaptive-privacy-3c2f6261aa4f?source=rss-1c7dd04b732b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c2f6261aa4f</guid>
            <category><![CDATA[data-privacy]]></category>
            <category><![CDATA[data-governance]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Kiran R]]></dc:creator>
            <pubDate>Wed, 04 Jun 2025 18:07:43 GMT</pubDate>
            <atom:updated>2025-06-04T18:07:43.049Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Bridging the AI Governance Gap: A Framework for Real-Time Cybersecurity and Adaptive Privacy Compliance</strong></h3><p><em>Addressing the 56.4% Surge in AI-Related Incidents Through Unified Technical-Policy Solutions</em></p><p><strong>1. Introduction</strong></p><p>Despite significant progress in artificial intelligence (AI) capabilities and data governance tooling, organizations face a growing implementation gap. While AI systems continue to generate value through automation and insights, they also introduce unprecedented risks in data privacy, cybersecurity, and regulatory compliance.</p><p>Recent studies highlight this widening chasm:</p><ul><li>56.4% increase in AI-related incidents (Stanford AI Index, 2025)</li><li>40% of enterprises lack adequate tools to secure AI-accessible data (Forbes, 2025)</li><li>Regulatory evolution lags behind AI inference complexity (Cloud Security Alliance, 2025)</li></ul><p>This paper proposes “AI TRiSM 2.0,” an integrated framework addressing three primary challenges:</p><ol><li>Real-time governance of AI/ML data pipelines</li><li>Automated compliance across evolving jurisdictions</li><li>Ethical auditing for inferred attributes in black-box models</li></ol><p><strong>2. Related Work and Gaps</strong></p><p>Existing frameworks such as NIST AI RMF and ISO/IEC 42001 provide high-level risk and governance principles but lack implementation clarity for streaming AI workflows. Similarly, many current data protection mechanisms are designed for static PII, not inferred or behavioral data generated in real-time by AI.</p><p>There is a critical need for:</p><ul><li>Real-time compliance solutions integrated into data flows</li><li>Mechanisms for transparency in model inference</li><li>Tools for adaptive consent and ethical controls in black-box AI</li></ul><p><strong>3. AI TRiSM 2.0 Framework Overview</strong></p><p>AI TRiSM (AI Trust, Risk, and Security Management) 2.0 consists of three core layers:</p><p><strong>3.1 Dynamic Threat Mitigation Layer</strong></p><ul><li><em>AI-Powered Anomaly Detection</em>: Lightweight models based on MIT’s PAC Privacy codebase monitor data flows, reducing breach response from hours to seconds.</li><li><em>Adversarial Resistance</em>: Incorporates synthetic data techniques from Microsoft’s Phi-3 to mitigate model inversion attacks.</li></ul><p><em>Case Study:</em> Applied to healthcare IoT devices, this layer achieved:</p><ul><li>63% reduction in false positives</li><li>&lt;50ms detection of ransomware encryption</li></ul><p><strong>3.2 Adaptive Compliance Engine</strong></p><p>Feature GDPR / CCPA Alignment AI-Specific Enhancements Data Mapping Traditional PII tracking Governance of inferred attributes Consent Management Opt-in/out mechanisms Dynamic consent for AI inferences Reporting Periodic audits Real-time compliance dashboards</p><p><em>Implementation:</em> Hybrid blockchain logs AI decision trails, supporting automated compliance with the draft EU AI Act and CPRA.</p><p><strong>3.3 Ethics-by-Design Protocol</strong></p><ul><li><em>Bias Auditing</em>: Extends IBM AI Fairness 360 with NIST’s algorithmic stability metrics.</li><li><em>Explainability</em>: Utilizes Microsoft’s Orca 2 for post-training rationales, improving model transparency.</li></ul><p><strong>4. Evaluation and Results</strong></p><p>Tested on anonymized financial transaction datasets:</p><p>Metric Baseline (2024 Tools) AI TRiSM 2.0 Improvement False Compliance Flags 22% 6% 72.7% ↓ Attack Detection Rate 84% 97% 15.5% ↑ Audit Preparation Time 14 hours 1.2 hours 91.4% ↓</p><p><strong>5. Policy Contributions</strong></p><p>AI TRiSM 2.0 addresses critical gaps in existing AI regulations:</p><ul><li>Enables transparency for inferred health and financial attributes</li><li>Supports real-time opt-out from algorithmic profiling</li><li>Standardizes incident reporting timelines for AI breaches (e.g., CPRA alignment)</li></ul><p><strong>6. Future Research Directions</strong></p><ul><li><em>Quantum-Resistant AI Models</em>: Incorporating lattice-based cryptography in federated learning.</li><li><em>Global Governance Harmonization</em>: Proposing ISO/IEC 27001 extensions for generative AI pipelines.</li></ul><p><strong>7. Conclusion</strong></p><p>AI TRiSM 2.0 offers a pragmatic approach to bridging the AI governance gap. By combining technical and policy innovations, it enables organizations to mitigate risks, reduce regulatory exposure, and enhance public trust in AI systems. Its modular architecture also ensures scalability across industries and jurisdictions.</p><p>As 87% of organizations report challenges in managing AI-related threats (Stanford AI Index, 2025), this framework provides a necessary and timely blueprint for secure, compliant, and ethical AI deployment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c2f6261aa4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[S.O.L.I.D: The First 5 Principles of Object Oriented Design]]></title>
            <link>https://medium.com/@kiranchowdhary/s-o-l-i-d-the-first-5-principles-of-object-oriented-design-5378e12a8b4c?source=rss-1c7dd04b732b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5378e12a8b4c</guid>
            <dc:creator><![CDATA[Kiran R]]></dc:creator>
            <pubDate>Sun, 27 Oct 2024 15:51:34 GMT</pubDate>
            <atom:updated>2024-10-27T15:51:34.565Z</atom:updated>
            <content:encoded><![CDATA[<p>S.O.L.I.D is an acronym for the first five object-oriented design(OOD) principles by Robert C. Martin, popularly known as <a href="https://en.wikipedia.org/wiki/Robert_Cecil_Martin">Uncle Bob</a>.</p><p>These principles, when combined together, make it easy for a programmer to develop software that are easy to maintain and extend. They also make it easy for developers to avoid code smells, easily refactor code, and are also a part of the agile or adaptive software development.</p><p><strong>Note</strong>: <em>this is just a simple “welcome to </em><strong><em>S.O.L.I.D</em></strong><em>” article, it simply sheds light on what </em><strong><em>S.O.L.I.D</em></strong><em> is</em>.</p><h3>S.O.L.I.D stands for:</h3><p>When expanded the acronyms might seem complicated, but they are pretty simple to grasp.</p><ul><li><strong>S</strong> — Single-responsiblity principle</li><li><strong>O</strong> — Open-closed principle</li><li><strong>L</strong> — Liskov substitution principle</li><li><strong>I</strong> — Interface segregation principle</li><li><strong>D</strong> — Dependency Inversion Principle</li></ul><p>Let’s look at each principle individually to understand why S.O.L.I.D can help make us better developers.</p><h3>Single-responsibility Principle</h3><p><strong>S.R.P</strong> for short — this principle states that:</p><blockquote><em>A class should have one and only one reason to change, meaning that a class should have only one job.</em></blockquote><p>For example, say we have some shapes and we wanted to sum all the areas of the shapes. Well this is pretty simple right?</p><pre>class Circle { public $radius; public function __construct($radius) { $this-&gt;radius = $radius; } } class Square { public $length; public function __construct($length) { $this-&gt;length = $length; } }</pre><p>First, we create our shapes classes and have the constructors setup the required parameters. Next, we move on by creating the <strong>AreaCalculator</strong> class and then write up our logic to sum up the areas of all provided shapes.</p><pre>class AreaCalculator { protected $shapes; public function __construct($shapes = array()) { $this-&gt;shapes = $shapes; } public function sum() { // logic to sum the areas } public function output() { return implode(&#39;&#39;, array( &quot;</pre><p>&quot; )); } }</p><p>To use the <strong>AreaCalculator</strong> class, we simply instantiate the class and pass in an array of shapes, and display the output at the bottom of the page.</p><pre>$shapes = array( new Circle(2), new Square(5), new Square(6) ); $areas = new AreaCalculator($shapes); echo $areas-&gt;output();</pre><p>The problem with the output method is that the <strong>AreaCalculator</strong> handles the logic to output the data. Therefore, what if the user wanted to output the data as json or something else?</p><p>All of that logic would be handled by the <strong>AreaCalculator</strong> class, this is what SRP frowns against; the <strong>AreaCalculator</strong> class should only sum the areas of provided shapes, it should not care whether the user wants json or HTML.</p><p>So, to fix this you can create an <strong>SumCalculatorOutputter</strong> class and use this to handle whatever logic you need to handle how the sum areas of all provided shapes are displayed.</p><p>The <strong>SumCalculatorOutputter</strong> class would work like this:</p><pre>$shapes = array( new Circle(2), new Square(5), new Square(6) ); $areas = new AreaCalculator($shapes); $output = new SumCalculatorOutputter($areas); echo $output-&gt;JSON(); echo $output-&gt;HAML(); echo $output-&gt;HTML(); echo $output-&gt;JADE();</pre><p>Now, whatever logic you need to output the data to the user is now handled by the <strong>SumCalculatorOutputter</strong> class.</p><blockquote><em>Objects or entities should be open for extension, but closed for modification.</em></blockquote><p>This simply means that a class should be easily extendable without modifying the class itself. Let’s take a look at the <strong>AreaCalculator</strong> class, especially it’s <strong>sum</strong> method.</p><pre>public function sum() { foreach($this-&gt;shapes as $shape) { if(is_a($shape, &#39;Square&#39;)) { $area[] = pow($shape-&gt;length, 2); } else if(is_a($shape, &#39;Circle&#39;)) { $area[] = pi() * pow($shape-&gt;radius, 2); } } return array_sum($area); }</pre><p>If we wanted the <strong>sum</strong> method to be able to sum the areas of more shapes, we would have to add more <strong>if/else blocks</strong> and that goes against the Open-closed principle.</p><p>A way we can make this <strong>sum</strong> method better is to remove the logic to calculate the area of each shape out of the sum method and attach it to the shape’s class.</p><pre>class Square { public $length; public function __construct($length) { $this-&gt;length = $length; } public function area() { return pow($this-&gt;length, 2); } }</pre><p>The same thing should be done for the <strong>Circle</strong> class, an <strong>area</strong> method should be added. Now, to calculate the sum of any shape provided should be as simple as:</p><pre>public function sum() { foreach($this-&gt;shapes as $shape) { $area[] = $shape-&gt;area(); } return array_sum($area); }</pre><p>Now we can create another shape class and pass it in when calculating the sum without breaking our code. However, now another problem arises, how do we know that the object passed into the <strong>AreaCalculator</strong> is actually a shape or if the shape has a method named <strong>area</strong>?</p><p>Coding to an interface is an integral part of <strong>S.O.L.I.D</strong>, a quick example is we create an interface, that every shape implements:</p><pre>interface ShapeInterface { public function area(); } class Circle implements ShapeInterface { public $radius; public function __construct($radius) { $this-&gt;radius = $radius; } public function area() { return pi() * pow($this-&gt;radius, 2); } }</pre><p>In our <strong>AreaCalculator</strong> sum method we can check if the shapes provided are actually instances of the <strong>ShapeInterface</strong>, otherwise we throw an exception:</p><pre>public function sum() { foreach($this-&gt;shapes as $shape) { if(is_a($shape, &#39;ShapeInterface&#39;)) { $area[] = $shape-&gt;area(); continue; } throw new AreaCalculatorInvalidShapeException; } return array_sum($area); }</pre><h3>Liskov substitution principle</h3><blockquote><em>Let </em><strong><em>q(x)</em></strong><em> be a property provable about objects of </em><strong><em>x</em></strong><em> of type </em><strong><em>T</em></strong><em>. Then </em><strong><em>q(y)</em></strong><em> should be provable for objects </em><strong><em>y</em></strong><em> of type </em><strong><em>S</em></strong><em> where </em><strong><em>S</em></strong><em> is a subtype of </em><strong><em>T</em></strong><em>.</em></blockquote><p>All this is stating is that every subclass/derived class should be substitutable for their base/parent class.</p><p>Still making use of out <strong>AreaCalculator</strong> class, say we have a <strong>VolumeCalculator</strong> class that extends the <strong>AreaCalculator</strong> class:</p><pre>class VolumeCalculator extends AreaCalulator { public function __construct($shapes = array()) { parent::__construct($shapes); } public function sum() { // logic to calculate the volumes and then return and array of output return array($summedData); } }</pre><p>In the <strong>SumCalculatorOutputter</strong> class:</p><pre>class SumCalculatorOutputter { protected $calculator; public function __constructor(AreaCalculator $calculator) { $this-&gt;calculator = $calculator; } public function JSON() { $data = array( &#39;sum&#39; =&gt; $this-&gt;calculator-&gt;sum(); ); return json_encode($data); } public function HTML() { return implode(&#39;&#39;, array( &#39;</pre><p>&#39; )); } }</p><p>If we tried to run an example like this:</p><pre>$areas = new AreaCalculator($shapes); $volumes = new AreaCalculator($solidShapes); $output = new SumCalculatorOutputter($areas); $output2 = new SumCalculatorOutputter($volumes);</pre><p>The program does not squawk, but when we call the <strong>HTML</strong> method on the <strong>$output2</strong> object we get an <strong>E_NOTICE</strong> error informing us of an array to string conversion.</p><p>To fix this, instead of returning an array from the <strong>VolumeCalculator</strong> class sum method, you should simply:</p><pre>public function sum() { // logic to calculate the volumes and then return and array of output return $summedData; }</pre><p>The summed data as a float, double or integer.</p><h3>Interface segregation principle</h3><blockquote><em>A client should never be forced to implement an interface that it doesn’t use or clients shouldn’t be forced to depend on methods they do not use.</em></blockquote><p>Still using our shapes example, we know that we also have solid shapes, so since we would also want to calculate the volume of the shape, we can add another contract to the <strong>ShapeInterface</strong>:</p><pre>interface ShapeInterface { public function area(); public function volume(); }</pre><p>Any shape we create must implement the <strong>volume</strong> method, but we know that squares are flat shapes and that they do not have volumes, so this interface would force the <strong>Square</strong> class to implement a method that it has no use of.</p><p><strong>ISP</strong> says no to this, instead you could create another interface called <strong>SolidShapeInterface</strong> that has the <strong>volume</strong> contract and solid shapes like cubes e.t.c can implement this interface:</p><pre>interface ShapeInterface { public function area(); } interface SolidShapeInterface { public function volume(); } class Cuboid implements ShapeInterface, SolidShapeInterface { public function area() { // calculate the surface area of the cuboid } public function volume() { // calculate the volume of the cuboid } }</pre><p>This is a much better approach, but a pitfall to watch out for is when type-hinting these interfaces, instead of using a <strong>ShapeInterface</strong> or a <strong>SolidShapeInterface</strong>.</p><p>You can create another interface, maybe <strong>ManageShapeInterface</strong>, and implement it on both the flat and solid shapes, this way you can easily see that it has a single API for managing the shapes. For example:</p><pre>interface ManageShapeInterface { public function calculate(); } class Square implements ShapeInterface, ManageShapeInterface { public function area() { /*Do stuff here*/ } public function calculate() { return $this-&gt;area(); } } class Cuboid implements ShapeInterface, SolidShapeInterface, ManageShapeInterface { public function area() { /*Do stuff here*/ } public function volume() { /*Do stuff here*/ } public function calculate() { return $this-&gt;area() + $this-&gt;volume(); } }</pre><p>Now in <strong>AreaCalculator</strong> class, we can easily replace the call to the <strong>area</strong> method with <strong>calculate</strong> and also check if the object is an instance of the <strong>ManageShapeInterface</strong> and not the <strong>ShapeInterface</strong>.</p><h3>Dependency Inversion principle</h3><p>The last, but definitely not the least states that:</p><blockquote><em>Entities must depend on abstractions not on concretions. It states that the high level module must not depend on the low level module, but they should depend on abstractions.</em></blockquote><p>This might sound bloated, but it is really easy to understand. This principle allows for decoupling, an example that seems like the best way to explain this principle:</p><pre>class PasswordReminder { private $dbConnection; public function __construct(MySQLConnection $dbConnection) { $this-&gt;dbConnection = $dbConnection; } }</pre><p>First the <strong>MySQLConnection</strong> is the low level module while the <strong>PasswordReminder</strong> is high level, but according to the definition of <strong>D</strong> in S.O.L.I.D. which states that <em>Depend on Abstraction not on concretions</em>, this snippet above violates this principle as the <strong>PasswordReminder</strong> class is being forced to depend on the <strong>MySQLConnection</strong> class.</p><p>Later if you were to change the database engine, you would also have to edit the <strong>PasswordReminder</strong> class and thus violates <strong>Open-close principle</strong>.</p><p>The <strong>PasswordReminder</strong> class should not care what database your application uses, to fix this again we “code to an interface”, since high level and low level modules should depend on abstraction, we can create an interface:</p><pre>interface DBConnectionInterface { public function connect(); }</pre><p>The interface has a connect method and the <strong>MySQLConnection</strong> class implements this interface, also instead of directly type-hinting <strong>MySQLConnection</strong> class in the constructor of the <strong>PasswordReminder</strong>, we instead type-hint the interface and no matter the type of database your application uses, the <strong>PasswordReminder</strong> class can easily connect to the database without any problems and <strong>OCP</strong> is not violated.</p><pre>class MySQLConnection implements DBConnectionInterface { public function connect() { return &quot;Database connection&quot;; } } class PasswordReminder { private $dbConnection; public function __construct(DBConnectionInterface $dbConnection) { $this-&gt;dbConnection = $dbConnection; } }</pre><p>According to the little snippet above, you can now see that both the high level and low level modules depend on abstraction.</p><h3>Conclusion</h3><p>Honestly, <strong>S.O.L.I.D</strong> might seem to be a handful at first, but with continuous usage and adherence to its guidelines, it becomes a part of you and your code which can easily be extended, modified, tested, and refactored without any problemes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5378e12a8b4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create your own maven archetype from the archetype “maven-archetype-archetype”.]]></title>
            <link>https://medium.com/@kiranchowdhary/create-your-own-maven-archetype-from-the-archetype-maven-archetype-archetype-ab1300c877c7?source=rss-1c7dd04b732b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab1300c877c7</guid>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[archetypes]]></category>
            <dc:creator><![CDATA[Kiran R]]></dc:creator>
            <pubDate>Wed, 01 May 2019 07:47:21 GMT</pubDate>
            <atom:updated>2019-05-01T07:47:21.921Z</atom:updated>
            <content:encoded><![CDATA[<h3>Create your own maven archetype from the archetype “maven-archetype-archetype”. Confused? Huh? Then read the full story…</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*lYdCmxnlJiJ6NReXXpWVfw.jpeg" /></figure><h3>Let’s start with the basic question, <strong>What is Maven?</strong></h3><p>Maven is build and dependency management tool for Java-based projects. Maven was originally started as an attempt to simplify the build processes in the Jakarta Turbine project. And the result is a tool that can now be used for building and managing any Java-based project.</p><p>Maven’s primary goal is to allow a developer to reduce the development effort. In order to attain this goal there are several areas of concern that Maven attempts to deal with:</p><ul><li>Making the build process easy</li><li>Providing a uniform build system</li><li>Providing quality project information</li><li>Providing guidelines for best practices development</li><li>Allowing transparent migration to new features</li></ul><p>Maven allows a project to build using its project object model (<strong>POM — pom.xml</strong>) and a set of plugins that are shared by all projects using Maven, providing a uniform build system.</p><p>The POM has all the quality project information, see few of them below</p><ul><li>Dependency list</li><li>Plugin dependencies</li><li>Build configuration</li><li>Project meta-data like name, version, group etc..</li><li>Profiles for different occasions.</li></ul><p><a href="https://www.javatpoint.com/maven-pom-xml">Link to sample file <strong>pom.xml</strong></a></p><p>By default all the dependencies are referred and downloaded from the central maven repository located at <a href="https://mvnrepository.com/">https://mvnrepository.com/</a></p><p>Maven caches all the dependencies in your local repository, which is located in MacOS/Linux at <strong>~/.m2/repository</strong></p><h3>Central maven repository</h3><p>The central maven repository hosts all the third-party open source libraries/dependencies at <a href="https://mvnrepository.com/">https://mvnrepository.com</a>. At present it hosed few millions of artifacts. And there are many corporate private repositories and other 3rd party public repositories. The developer can change the configuration to point to different repository by editing the file <strong>~/.m2/settings.xml </strong>like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d-S9girmKYIVghy_AcWxKQ.png" /></figure><h3><strong><em>Here is how you can use dependencies in your project.</em></strong></h3><p>Let’s say you need to use <strong>JUnit</strong> framework in your project, go to central repository, search for <strong>JUnit</strong> and select a version of your interest. Here you will find some xml snipped under a maven tab, copy and paste it in your project’s <strong>pom.xml, </strong>You are almost done!</p><p>Then run <strong>mvn clean install</strong> you are done now!</p><h3><strong>Then what is Maven archetype?</strong></h3><p>Archetype in short is Maven project templating toolkit. And it is again a maven project created from the archetype <strong>maven-archetype-archetype</strong>. And we call it a <strong>seed</strong> or the <strong>start point </strong>too.</p><p>Archetype helps in quickly creating a project/artifact using a template, where all the configurations and dependencies are specified already instead of creating from the scratch. This would save much of development time. Sometimes developer might not know the dependencies of the project that he is trying to create, he might not know the specific structure of the project to follow and hence he need to create the build script himself. Archetype solves these problems, and makes developer life easy.</p><p>The full working code to demonstrate creating a maven archetype and using local archetype is published in GitHub repository. <a href="https://github.com/rkiranchowdhary/my-maven-archetypes">Here is the link</a></p><h3>Now lets find the solution to — creating your own maven archetype..</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab1300c877c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JAVA memory management and Garbage Collection…]]></title>
            <link>https://medium.com/@kiranchowdhary/java-memory-management-and-garbage-collection-e29d3c313d05?source=rss-1c7dd04b732b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e29d3c313d05</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[garbage-collection]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kiran R]]></dc:creator>
            <pubDate>Sun, 30 Dec 2018 08:16:00 GMT</pubDate>
            <atom:updated>2023-08-02T06:14:29.934Z</atom:updated>
            <content:encoded><![CDATA[<p>Java Memory Management, with its built-in garbage collection, is one of the language’s finest achievements. It allows developers to create new objects without worrying explicitly about memory allocation and deallocation, because the garbage collector automatically reclaims memory for reuse. This enables faster development with less boilerplate code, while eliminating memory leaks and other memory-related problems. At least in theory.</p><p>Ironically, Java garbage collection seems to work too well, creating and removing too many objects. Most memory-management issues are solved, but often at the cost of creating serious performance problems. Making garbage collection adaptable to all kinds of situations has led to a complex and hard-to-optimize system. In order to wrap your head around garbage collection, you need first to understand how memory management works in a Java Virtual Machine (JVM).</p><h3>Hotspot JVM</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*33v2kJGb1e4sCOXa.png" /></figure><h3>What is Automatic Garbage Collection?</h3><blockquote>Automatic garbage collection is the process of looking at heap memory, identifying objects are in use and deleting the unreferenced objects. An unused/unreferenced object, is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed.</blockquote><blockquote>In Java, process of deallocating memory is handled automatically by the garbage collector.</blockquote><h3>JVM Generations</h3><p>The information learned from the object allocation behavior can be used to enhance the performance of the JVM. Therefore, the heap is broken up into smaller parts or generations. The heap parts are: Young Generation, Old or Tenured Generation, and Permanent Generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*41teb5eiVYKS4Fbj.png" /></figure><p>The <strong>Young Generation</strong> is where all new objects are allocated and aged. When the young generation fills up, this causes a <strong><em>minor garbage collection</em></strong>. Minor collections can be optimized assuming a high object mortality rate. A young generation full of dead objects is collected very quickly. Some surviving objects are aged and eventually move to the old generation.</p><p><strong>Stop the World Event</strong> — All minor garbage collections are “Stop the World” events. This means that all application threads are stopped until the operation completes. Minor garbage collections are <em>always</em> Stop the World events.</p><p>The <strong>Old Generation</strong> is used to store long surviving objects. Typically, a threshold is set for young generation object and when that age is met, the object gets moved to the old generation. Eventually the old generation needs to be collected. This event is called a <strong><em>major garbage collection</em></strong>.</p><p>Major garbage collection are also<strong> Stop the World events.</strong> Often a major collection is much slower because it involves all live objects. So for Responsive applications, major garbage collections should be minimized. Also note, that the length of the Stop the World event for a major garbage collection is affected by the kind of garbage collector that is used for the old generation space.</p><p>The <strong>Permanent generation</strong> contains metadata required by the JVM to describe the classes and methods used in the application. The permanent generation is populated by the JVM at runtime based on classes in use by the application. In addition, Java SE library classes and methods may be stored here.</p><p>Classes may get collected (unloaded) if the JVM finds they are no longer needed and space may be needed for other classes. The permanent generation is included in a full garbage collection.</p><h3>The Generational Garbage Collection Process</h3><p><strong>Minor GC</strong></p><p>Now that you understand why the heap is separated into different generations, it is time to look at how exactly these spaces interact. The pictures that follow walks through the object allocation and aging process in the JVM.</p><p><strong>Step 1 :</strong>First, any new objects are allocated to the eden space. Both survivor spaces start out empty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*aLaB7VNQsW_c5As8.png" /></figure><p><strong>Step 2 : </strong>When the eden space fills up, a minor garbage collection is triggered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*9-GA28_Ot2tvw1P9.png" /></figure><p><strong>Step 3 : </strong>Referenced objects are moved to the first survivor space. Unreferenced objects are deleted when the eden space is cleared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*hPhWJb6AGmrp0GtE.png" /></figure><p><strong>Step 4 : </strong>At the next minor GC, the same thing happens for the eden space. Unreferenced objects are deleted and referenced objects are moved to a survivor space. However, in this case, they are moved to the second survivor space (S1). In addition, objects from the last minor GC on the first survivor space (S0) have their age incremented and get moved to S1. Once all surviving objects have been moved to S1, both S0 and eden are cleared. Notice we now have differently aged object in the survivor space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*VYSfJFqeHEeBvg_m.png" /></figure><p><strong>Step 5 : </strong>At the next minor GC, the same process repeats. However this time the survivor spaces switch. Referenced objects are moved to S0. Surviving objects are aged. Eden and S1 are cleared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*HexAOzqStcxjVSRN.png" /></figure><p><strong>Step 6 : </strong>This slide demonstrates promotion. After a minor GC, when aged objects reach a certain age threshold (8 in this example) they are promoted from young generation to old generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*U0j_lBGzj2EfmcPa.png" /></figure><p><strong>Step 7 :</strong> As minor GCs continue to occur objects will continue to be promoted to the old generation space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*6cRVZ6qazCD3JC4K.png" /></figure><p><strong>Step 8 : </strong>So that pretty much covers the entire process with the young generation. Eventually, a major GC will be performed on the old generation which cleans up and compacts that space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*Erly60hbZmd0_9sQ.png" /></figure><h3>Marking Process</h3><p>The first step in the process is called marking. This is where the garbage collector identifies which pieces of memory are in use and which are not.</p><p>Referenced objects are shown in blue. Unreferenced objects are shown in gold. All objects are scanned in the marking phase to make this determination. This can be a very time consuming process if all objects in a system must be scanned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*zQNh1EUPEuDBQ7NZ.png" /></figure><h3>Deletion without Compacting(Minor GC on young gen)</h3><p>Deletion removes unreferenced objects leaving referenced objects and pointers to free space.The memory allocator holds references to blocks of free space where new object can be allocated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*n8c2TYVvPIWoflDi.png" /></figure><h3>Deletion with Compacting(Major GC on Old gen)</h3><p>To further improve performance, in addition to deleting unreferenced objects, you can also compact the remaining referenced objects. By moving referenced object together, this makes new memory allocation much easier and faster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*dv5yt9m6hJcJIt8Z.png" /></figure><h3>Why Generational Garbage Collection?</h3><p>As stated earlier, having to mark and compact all the objects in a JVM is inefficient. As more and more objects are allocated, the list of objects grows and grows leading to longer and longer garbage collection time. However, empirical analysis of applications has shown that most objects are short lived.</p><p>Here is an example of such data. The Y axis shows the number of bytes allocated and the X access shows the number of bytes allocated over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/0*1N596O0UWuxWGytP.gif" /></figure><p>As you can see, fewer and fewer objects remain allocated over time. In fact most objects have a very short life as shown by the higher values on the left side of the graph.</p><h3>Summary</h3><p>In this Article, you have been given an overview of garbage collection system on the Java JVM. First you learned how the Heap and the Garbage Collector are key parts of any Java JVM. Automatic garbage collection is accomplished using generational garbage collection approach.</p><p>In this tutorial, you have learned:</p><ul><li>The components of the Java JVM</li><li>How automatic garbage collection works</li><li>The generational garbage collection process</li></ul><p>Image and content credits: Oracle and Google.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e29d3c313d05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OAuth 2.0 (A & A)]]></title>
            <link>https://medium.com/@kiranchowdhary/oauth-2-0-a-a-8f08e116974c?source=rss-1c7dd04b732b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f08e116974c</guid>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[application-server]]></category>
            <category><![CDATA[authorization]]></category>
            <dc:creator><![CDATA[Kiran R]]></dc:creator>
            <pubDate>Mon, 28 May 2018 08:24:13 GMT</pubDate>
            <atom:updated>2019-01-24T09:52:24.868Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/180/0*wuozj6YKJpU-iBDG.png" /><figcaption>Open Standard Authentication</figcaption></figure><p><strong><em>OAuth</em></strong> is an <a href="https://en.wikipedia.org/wiki/Open_standard">open standard</a> for access delegation, commonly used as a way for Internet users to grant websites or applications access to their information on other websites but without giving them the passwords.</p><p>Generally, OAuth provides to clients a “secure delegated access” to server resources on behalf of a resource owner.</p><p>It specifies a process for resource owners to authorize third-party access to their server resources without sharing their credentials.</p><p>Designed specifically to work with <a href="https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol">Hypertext Transfer Protocol</a> (HTTP), OAuth essentially allows <a href="https://en.wikipedia.org/wiki/Access_token">access tokens</a> to be issued to third-party clients by an authorization server, with the approval of the resource owner. The third party then uses the access token to access the protected resources hosted by the resource server.</p><h3>Contents</h3><ol><li>History</li><li><a href="https://en.wikipedia.org/wiki/OAuth#OAuth_2.0">OAuth 2.0</a></li><li>Security terms with reference to legacy JEE systems.</li><li>Traditional JEE Application Server Anatomy.</li><li>Drawbacks of traditional system.</li><li>OAuth in Action…</li><li>References</li></ol><h3>History</h3><p>OAuth began in November 2006 when <a href="https://en.wikipedia.org/wiki/Blaine_Cook_(programmer)">Blaine Cook</a> was developing the <a href="https://en.wikipedia.org/wiki/Twitter">Twitter</a> <a href="https://en.wikipedia.org/wiki/OpenID">OpenID</a> implementation. Meanwhile, <a href="https://en.wikipedia.org/wiki/Ma.gnolia">Ma.</a> needed a solution to allow its members with OpenIDs to authorize <a href="https://en.wikipedia.org/wiki/Dashboard_(Mac_OS)">Dashboard Widgets</a> to access their service. Cook, <a href="https://en.wikipedia.org/wiki/Chris_Messina_(open_source_advocate)">Chris Messina</a> and Larry Halff from Magnolia met with <a href="https://en.wikipedia.org/wiki/David_Recordon">David Recordon</a> to discuss using OpenID with the Twitter and Ma.gnolia <a href="https://en.wikipedia.org/wiki/Application_Programming_Interface">APIs</a> to delegate authentication. They concluded that there were no <a href="https://en.wikipedia.org/wiki/Open_standard">open standards</a> for <a href="https://en.wikipedia.org/wiki/Application_Programming_Interface">API</a>access delegation.</p><p>The OAuth <a href="https://en.wikipedia.org/wiki/Discussion_group">discussion group</a> was created in April 2007, for the small group of implementers to write the draft proposal for an open protocol. DeWitt Clinton from <a href="https://en.wikipedia.org/wiki/Google">Google</a> learned of the OAuth project, and expressed his interest in supporting the effort. In July 2007, the team drafted an initial specification. <a href="https://en.wikipedia.org/w/index.php?title=Eran_Hammer&amp;action=edit&amp;redlink=1">Eran Hammer</a> joined and coordinated the many OAuth contributions creating a more formal specification. On December 4, 2007, the OAuth Core 1.0 final draft was released.<a href="https://en.wikipedia.org/wiki/OAuth#cite_note-4">[4]</a></p><p>At the 73rd Internet Engineering Task Force (IETF) meeting in <a href="https://en.wikipedia.org/wiki/Minneapolis">Minneapolis</a> in November 2008, an OAuth <a href="https://en.wikipedia.org/wiki/Birds_of_a_feather_(computing)">BoF</a> was held to discuss bringing the protocol into the IETF for further standardization work. The event was well attended and there was wide support for formally chartering an OAuth working group within the IETF.</p><p>The OAuth 1.0 protocol was published as <a href="https://tools.ietf.org/html/rfc5849">RFC 5849</a>, an informational <a href="https://en.wikipedia.org/wiki/Request_for_Comments">Request for Comments</a>, in April 2010.</p><p>Since August 31, 2010, all third party Twitter applications have been required to use OAuth.</p><p>The OAuth 2.0 framework was published as <a href="https://tools.ietf.org/html/rfc6749">RFC 6749</a>, and the Bearer Token Usage as <a href="https://tools.ietf.org/html/rfc6750">RFC 6750</a>, both standards track <a href="https://en.wikipedia.org/wiki/Requests_for_Comments">Requests for Comments</a>, in October 2012.</p><h3>OAuth 2.0</h3><p>OAuth 2.0 is not backwards compatible with OAuth 1.0. OAuth 2.0 provides specific authorization flows for web applications, desktop applications, mobile phones, and living room devices. The specification and associated RFCs are developed by the IETF OAuth WG;<a href="https://en.wikipedia.org/wiki/OAuth#cite_note-6">[6]</a> the main framework was published in October 2012.</p><p><a href="https://en.wikipedia.org/wiki/Facebook">Facebook</a>’s <a href="https://en.wikipedia.org/wiki/Facebook_Platform#Graph_API">Graph API</a> only supports OAuth 2.0.<a href="https://en.wikipedia.org/wiki/OAuth#cite_note-7">[7]</a> <a href="https://en.wikipedia.org/wiki/Google">Google</a> supports OAuth 2.0 as the recommended authorization mechanism for all of its APIs.<a href="https://en.wikipedia.org/wiki/OAuth#cite_note-8">[8]</a> <a href="https://en.wikipedia.org/wiki/Microsoft">Microsoft</a><a href="https://en.wikipedia.org/wiki/OAuth#cite_note-9">[9]</a> also supports OAuth 2.0 for various <a href="https://en.wikipedia.org/wiki/Application_Programming_Interface">APIs</a> and its Azure Active Directory service, which is used to secure many Microsoft and third party <a href="https://en.wikipedia.org/wiki/Application_Programming_Interface">APIs</a>.</p><p>The OAuth 2.0 Framework<a href="https://en.wikipedia.org/wiki/OAuth#cite_note-Dick_Hardt-10">[10]</a> and Bearer Token Usage<a href="https://en.wikipedia.org/wiki/OAuth#cite_note-11">[11]</a> were published in October 2012.</p><h3>Security terms with reference to legacy JEE systems</h3><ul><li><strong>Web server : </strong>A Web <a href="https://whatis.techtarget.com/definition/server">server</a> is a program (or a daemon process) that uses <a href="https://searchwindevelopment.techtarget.com/definition/HTTP">HTTP</a> (Hypertext Transfer Protocol) to serve the files that form Web pages to users, in response to their requests. <strong>Ex. </strong>Apache, Tomcat, Glassfish etc..</li><li><strong>HTTP listener : </strong>Each virtual server provides connections between the server and clients through one or more HTTP listeners. Each HTTP listener is a listen socket that has an IP address, a port number, a server name, and a default virtual server.</li><li><strong>Public URI’s vs protected URI’s : </strong>Public URI’s are generally accessible by public Ex. A web site data (<a href="https://www.google.com/">https://www.google.com</a>) . Access to protected URI’s are limited to certain users, certain roles or for certain users groups. Ex. your social account information (<a href="https://mail.google.com/">https://mail.google.com</a>).</li><li><strong>Authentication : </strong>Authentication is a process that ensures and confirms a user’s identity. Authentication is one of the five pillars of information assurance (IA). The other four are integrity, availability, confidentiality and nonrepudiation.</li><li><strong>Authorization : </strong>Authorization is a security mechanism used to determine user/client privileges or access levels related to system resources, including computer programs, files, services, data and application features.</li><li><strong>Realms, Users, Groups, and Roles : </strong>A <strong><em>realm</em></strong> is a security policy domain defined for a web or application server. A realm contains a collection of users, who may or may not be assigned to a group. A <strong><em>user</em></strong> is an individual or application program identity that has been defined in the server. A <strong><em>group</em></strong> is a set of authenticated users, classified by common traits, defined in the Server. A <strong><em>role</em></strong> is an abstract name for the permission to access a particular set of resources in an application</li><li><strong>Security filter : </strong>Security filters enable you to control what data (or what urls) users can access when that data is accessed through MicroStrategy. <strong><em>Ex. Apache Shiro security filter.</em></strong></li></ul><p><em>Web.xml</em></p><pre>&lt;filter&gt; <br>    &lt;filter-name&gt;ShiroFilter&lt;/filter-name&gt; <br>    &lt;filter-class&gt;org.apache.shiro.web.servlet.ShiroFilter&lt;/filter-class&gt; <br>&lt;/filter&gt; </pre><pre><br>&lt;filter-mapping&gt; <br>    &lt;filter-name&gt;ShiroFilter&lt;/filter-name&gt; <br>    &lt;url-pattern&gt;/*&lt;/url-pattern&gt; <br>&lt;/filter-mapping&gt;</pre><p><em>Shiro.ini</em></p><pre>[main]</pre><pre># password matcher</pre><pre>#passwordMatcher = org.apache.shiro.authc.credential.PasswordMatcher</pre><pre>#passwordService = org.apache.shiro.authc.credential.DefaultPasswordService</pre><pre>#passwordMatcher.passwordService = $passwordService</pre><pre>sha256Matcher = org.apache.shiro.authc.credential.HashedCredentialsMatcher</pre><pre>sha256Matcher.hashAlgorithmName = SHA-256</pre><pre>sha256Matcher.hashIterations=1</pre><pre># base64 encoding</pre><pre>sha256Matcher.storedCredentialsHexEncoded = false</pre><pre>#matcher = org.apache.shiro.authc.credential.SimpleCredentialsMatcher</pre><pre>#datasource type</pre><pre>ds = org.apache.shiro.jndi.JndiObjectFactory</pre><pre>#datasourcename</pre><pre>ds.resourceName = jdbc/testresource</pre><pre>#datasourcetype</pre><pre>ds.requiredType = javax.sql.DataSource</pre><pre>#fbCredentialsMatcher = com.connectifier.authc.facabook.FaceBookCreadentialsMatcher</pre><pre>#FaceBookRealm = com.connectifier.authc.realm.FaceBookRealm</pre><pre>#FaceBookRealm.credentialsMatcher = $fbCredentialsMatcher</pre><pre>#configuring jdbc realm</pre><pre>jdbcRealm = com.connectifier.authc.realm.CustomJDBCRealm</pre><pre>#jdbcRealm.credentialsMatcher = $matcher</pre><pre>jdbcRealm.credentialsMatcher = $sha256Matcher</pre><pre>jdbcRealm.dataSource=$ds</pre><pre>jdbcRealm.userRolesQuery=select name from role where email = ? and isactive=1</pre><pre>jdbcRealm.authenticationQuery=select hash, salt from user where email = ? and isactive=1</pre><pre>jdbcRealm.permissionsLookupEnabled=false</pre><pre>#securityManager.realms = $jdbcRealm,$FaceBookRealm</pre><pre>securityManager.realms = $jdbcRealm</pre><pre>#login url</pre><pre>authc.loginUrl = /</pre><pre>#page to redirected to after logout</pre><pre>logout.redirectUrl = /</pre><pre>#page to where to land after login</pre><pre>authc.successUrl = /</pre><pre>#username parameter name in the loginform</pre><pre>authc.usernameParam = username</pre><pre>#password parameter name in the loginform</pre><pre>authc.passwordParam = password</pre><pre>#rememberme parameter name in the loginform</pre><pre>authc.rememberMeParam=rememberme</pre><pre>#cacheManager = org.apache.shiro.cache.ehcache.EhCacheManager</pre><pre>#securityManager.cacheManager = $cacheManager</pre><pre>#jdbcRealm.authenticationCachingEnabled = true</pre><pre>[urls]</pre><pre># The /login.jsp is not restricted to authenticated users (otherwise no one could log in!), but</pre><pre># the &#39;authc&#39; filter must still be specified for it so it can process that url&#39;s</pre><pre># login submissions. It is &#39;smart&#39; enough to allow those requests through as specified by the</pre><pre># shiro.loginUrl above.</pre><pre>/logout = logout</pre><pre>/index.jsp = anon</pre><pre>/login = anon</pre><pre>/action = anon</pre><pre>/* = authc</pre><p><em>CustomJDBCRealm.java</em></p><pre>import java.sql.Connection;<br>import java.sql.PreparedStatement;<br>import java.sql.ResultSet;<br>import java.sql.SQLException;</pre><pre>import org.apache.shiro.authc.AccountException;<br>import org.apache.shiro.authc.AuthenticationException;<br>import org.apache.shiro.authc.AuthenticationInfo;<br>import org.apache.shiro.authc.AuthenticationToken;<br>import org.apache.shiro.authc.SimpleAuthenticationInfo;<br>import org.apache.shiro.authc.UnknownAccountException;<br>import org.apache.shiro.authc.UsernamePasswordToken;<br>import org.apache.shiro.codec.Base64;<br>import org.apache.shiro.realm.jdbc.JdbcRealm;<br>import org.apache.shiro.util.ByteSource;<br>import org.apache.shiro.util.JdbcUtils;<br>import org.apache.shiro.util.SimpleByteSource;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;</pre><pre>/**<br> * <a href="http://twitter.com/author">@author</a> kkumar1<br> * <br> *         Application specific JDBC realm. If required override methods of {<a href="http://twitter.com/link">@link</a> JdbcRealm} to load users, roles and<br> *         permissions from database.<br> * <br> *         Do not override configuration in code if it can be done via shiro.ini file.<br> */<br>public class CustomJDBCRealm extends JdbcRealm {</pre><pre>private static final Logger log = LoggerFactory.getLogger(JdbcRealm.class);</pre><pre>public CustomJDBCRealm() {<br>        super();<br>        setSaltStyle(SaltStyle.COLUMN);<br>    }</pre><pre>/**<br>     * overriding the method which is in JdbcRealm. If SaltStyle is COLUMN, then gets String salt value from database<br>     * and forms salt byte array of type {<a href="http://twitter.com/link">@link</a> ByteSource} with decoded string salt value and sets it to salt value of<br>     * AuthenticationInfo.<br>     */<br>    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {</pre><pre>UsernamePasswordToken upToken = (UsernamePasswordToken) token;<br>        String username = upToken.getUsername();</pre><pre>// Null username is invalid<br>        if (username == null) {<br>            throw new AccountException(&quot;Null usernames are not allowed by this realm.&quot;);<br>        }</pre><pre>Connection conn = null;<br>        SimpleAuthenticationInfo info = null;<br>        try {<br>            conn = dataSource.getConnection();</pre><pre>String password = null;<br>            String salt = null;<br>            switch (saltStyle) {<br>            case NO_SALT:<br>            case CRYPT:<br>            case EXTERNAL:<br>                return super.doGetAuthenticationInfo(token);<br>            case COLUMN:<br>                String[] queryResults = getPasswordForUser(conn, username);<br>                password = queryResults[0];<br>                salt = queryResults[1];<br>                break;<br>            }</pre><pre>if (password == null) {<br>                throw new UnknownAccountException(&quot;No account found for user [&quot; + username + &quot;]&quot;);<br>            }</pre><pre>info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName());</pre><pre>if (salt != null) {<br>                info.setCredentialsSalt(new SimpleByteSource(Base64.decode(salt)));<br>            }</pre><pre>} catch (SQLException e) {<br>            final String message = &quot;There was a SQL error while authenticating user [&quot; + username + &quot;]&quot;;<br>            if (log.isErrorEnabled()) {<br>                log.error(message, e);<br>            }<br>            throw new AuthenticationException(message, e);<br>        } finally {<br>            JdbcUtils.closeConnection(conn);<br>        }</pre><pre>return info;<br>    }</pre><pre>private String[] getPasswordForUser(Connection conn, String username) throws SQLException {</pre><pre>String[] result;<br>        boolean returningSeparatedSalt = false;<br>        switch (saltStyle) {<br>        case NO_SALT:<br>        case CRYPT:<br>        case EXTERNAL:<br>            result = new String[1];<br>            break;<br>        default:<br>            result = new String[2];<br>            returningSeparatedSalt = true;<br>        }</pre><pre>PreparedStatement ps = null;<br>        ResultSet rs = null;<br>        try {<br>            ps = conn.prepareStatement(authenticationQuery);<br>            ps.setString(1, username);<br>            rs = ps.executeQuery();<br>            boolean foundResult = false;<br>            while (rs.next()) {<br>                if (foundResult) {<br>                    throw new AuthenticationException(&quot;More than one <br>                      user row found for user [&quot; + username<br>                      + &quot;]. Usernames must be unique.&quot;);<br>                }</pre><pre>                result[0] = rs.getString(1);<br>                if (returningSeparatedSalt) {<br>                    result[1] = rs.getString(2);<br>                }</pre><pre>                foundResult = true;<br>            }<br>        } finally {<br>            JdbcUtils.closeResultSet(rs);<br>            JdbcUtils.closeStatement(ps);<br>        }</pre><pre>        return result;<br>    }<br>}</pre><ul><li><strong>Session (Http session): Session</strong> is a conversional state between client and server and it can consists of multiple request and response between client and server. <strong><em>Session Ids</em></strong> are unique, transient and non-guessable numbers / string. <strong>Ex. </strong>sessionId = SHA2(userId + ipAddr) + prngRandomNumber.</li></ul><pre>/* JSP example of a session */<br>&lt;%@ taglib prefix=&quot;shiro&quot; uri=&quot;http://shiro.apache.org/tags&quot; %&gt;<br>&lt;%<br>session.getId();</pre><pre>session.getMaxInactiveInterval();</pre><pre>session.getLastAccessedTime();</pre><pre>session.invalidate();</pre><pre>%&gt;</pre><pre>/*Authentication tags*/</pre><pre>&lt;shiro:guest&gt;<br>/* guest user, -- show him login page.*/</pre><pre>&lt;/shiro:guest&gt;<br>&lt;shiro:user&gt;<br>/*Authenticated user, show him dashboard. */</pre><pre>&lt;/shiro:user&gt;</pre><pre>/*Permisssion tags*/</pre><pre>&lt;<strong>shiro:hasPermission</strong> name=&quot;users:manage&quot;&gt;         <br>   &lt;<strong>a</strong> href=&quot;manageUsers.jsp&quot;&gt;Click here to manage users&lt;/<strong>a</strong>&gt;     &lt;/<strong>shiro:hasPermission</strong>&gt;     <br>&lt;<strong>shiro:lacksPermission</strong> name=&quot;users:manage&quot;&gt;         <br>   No user management for you!     <br>&lt;/<strong>shiro:lacksPermission</strong>&gt;</pre><p><strong><em>Annotations for access control</em></strong></p><pre>@RequiresRoles(&quot;administrator&quot;) <br><strong>public</strong> <strong>void</strong> <strong>deleteUser</strong>(User user) {     <br>//this method will only be invoked by an administrator     ... <br>}</pre><pre>@RequiresGuest <br><strong>public</strong> <strong>void</strong> <strong>signUp</strong>(User newUser) {     <br>  //this method will only be invoked by a Subject that is unknown/anonymous     ... <br>}</pre><p><strong><em>Accessing session in servlet</em></strong></p><pre>/* Accessing session in servlet */</pre><pre>public void doPost(HttpServletRequest req, HttpServletResponse res)<br>throws ServletException, IOException {<br><br>    req.getSession();<br>}</pre><p>Take look at the source code of simple session here <a href="https://github.com/apache/shiro/blob/2.0-api-design-changes/core/src/main/java/org/apache/shiro/session/mgt/SimpleSession.java">https://github.com/apache/shiro/blob/2.0-api-design-changes/core/src/main/java/org/apache/shiro/session/mgt/SimpleSession.java</a></p><ul><li><strong>Cookies (HTTP cookies): </strong>An HTTP cookie (<em>web cookie, browser cookie</em>) is a small piece of data that a server sends to the web browser. The browser may store it and send it back with the next request to the same server. Typically, it’s used to tell if two requests came from the same browser — keeping a user logged-in, for example. It remembers stateful information for the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview#HTTP_is_stateless_but_not_sessionless">stateless</a> HTTP protocol.</li></ul><blockquote><strong>How Session is managed? Know the cookie?</strong></blockquote><blockquote>When a client visits the web-app for the first time and/or the HttpSession is to be obtained for the first time by request.getSession(), then the servlet container will create it, generate a long and unique ID (which you can get by session.getId()) and store it in server’s memory. The servlet container will also set a Cookie in the HTTP response with JSESSIONID as cookie name and the unique session ID as cookie value.</blockquote><blockquote>As per the <a href="http://www.faqs.org/rfcs/rfc2965.html">HTTP cookie specification</a> (a contract a decent web browser and web server has to adhere), the client (the web browser) is required to send this cookie back in the subsequent requests as long as the cookie is valid. The servlet container will determine every incoming HTTP request header for the presence of the cookie with the name JSESSIONID and use its value to get the associated HttpSession from server’s memory.</blockquote><blockquote>The HttpSession lives until it has not been used for more than the time, a setting you can specify in web.xml, which defaults to 30 minutes. So when the client doesn’t visit the web application anymore for over 30 minutes, then the servlet container will trash the session. Every subsequent request, even though with the cookie specified, will not have access to the same session anymore. The servlet container will create a new one.</blockquote><p>For more information on session management, take a look at the source code <a href="https://github.com/apache/shiro/blob/master/web/src/main/java/org/apache/shiro/web/session/mgt/ServletContainerSessionManager.java">https://github.com/apache/shiro/blob/master/web/src/main/java/org/apache/shiro/web/session/mgt/ServletContainerSessionManager.java</a></p><ul><li><strong>Domains, DNS and Virtual hosting : <em>Domain</em></strong> <strong><em>names</em></strong> are used to identify one or more IP addresses, <strong><em>DNS</em></strong> is Internet’s system for converting alphabetic domain names into numeric IP addresses. <strong><em>Virtual hosting</em></strong> is a method for hosting multiple domain names (with separate handling of each name) on a single server (or pool of servers). This allows one server to share its resources, such as memory and processor cycles, without requiring all services provided to use the same host name.</li><li><strong>Principal : </strong>The term <strong><em>principal</em></strong> is just a fancy security term for any identifying attribute(s) of an application user, such as a username, or user id, or public key, or anything else you might use in your application to identify a user.</li><li><strong>Subject (or Web Subject) : </strong>To authorize access to resources, applications first need to authenticate the source of the request. The JAAS framework defines the term <strong><em>subject</em></strong> to represent the source of a request. A subject may be any entity, such as a person or service. A subject is represented by the <a href="https://docs.oracle.com/javase/7/docs/api/javax/security/auth/Subject.html">javax.security.auth.Subject</a>class. Web subject will be bound to a thread which executes the request using thread locals.</li></ul><pre>/* JSP example of a Shiro SecurityUtils */<br>&lt;%<br>SecurityUtils.getSubject();</pre><pre>%&gt;</pre><p><strong><em>Subject interface source code example.</em></strong></p><pre>public interface Subject {<br>  Object getPrincipal();<br>  PrincipalCollection getPrincipals();<br>  boolean isPermitted(String permission);<br>  boolean isPermitted(Permission permission);<br>  boolean[] isPermitted(String… permissions);<br>  boolean[] isPermitted(List&lt;Permission&gt; permissions);<br>  boolean isPermittedAll(String… permissions);<br>  boolean isPermittedAll(Collection&lt;Permission&gt; permissions);</pre><pre>  void checkPermission(String permission) throws AuthorizationException;</pre><pre>  void checkPermission(Permission permission) throws AuthorizationException;</pre><pre>  void checkPermissions(String… permissions) throws AuthorizationException;</pre><pre>  void checkPermissions(Collection&lt;Permission&gt; permissions) throws AuthorizationException;</pre><pre>  boolean hasRole(String roleIdentifier);<br>  boolean[] hasRoles(List&lt;String&gt; roleIdentifiers);<br>  boolean hasAllRoles(Collection&lt;String&gt; roleIdentifiers);<br>  void checkRole(String roleIdentifier) throws AuthorizationException;</pre><pre>  void checkRoles(Collection&lt;String&gt; roleIdentifiers) throws AuthorizationException;</pre><pre>  void checkRoles(String… roleIdentifiers) throws AuthorizationException;</pre><pre>  void login(AuthenticationToken token) throws AuthenticationException;</pre><pre>  boolean isAuthenticated();<br>  boolean isRemembered();<br>  Session getSession();<br>  Session getSession(boolean create);<br>  void logout();<br>  &lt;V&gt; V execute(Callable&lt;V&gt; callable) throws ExecutionException;<br>  void execute(Runnable runnable);<br>  &lt;V&gt; Callable&lt;V&gt; associateWith(Callable&lt;V&gt; callable);<br>  Runnable associateWith(Runnable runnable);<br>  void runAs(PrincipalCollection principals) throws NullPointerException, IllegalStateException;</pre><pre>  boolean isRunAs();<br>  PrincipalCollection getPreviousPrincipals();<br>  PrincipalCollection releaseRunAs();<br>}</pre><p><strong><em>Implementation of WebSubject interface.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Msw7YIjktj3FMz3MCPUfXw.png" /><figcaption><strong><em>WebSubject binding to current thread</em></strong></figcaption></figure><p><a href="https://github.com/apache/shiro/blob/76416edfbb4cb82560ab08870c81230c0fa64907/core/src/main/java/org/apache/shiro/subject/support/DelegatingSubject.java">apache/shiro</a></p><p><strong><em>Example of ThreadLocals</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*Jtz09jdlsr0lMTDld8KEqA.jpeg" /></figure><p>Java provides an <a href="http://download.oracle.com/javase/6/docs/api/java/lang/ThreadLocal.html">ThreadLocal</a> object using which you can set/get <em>thread scoped </em>variables. Below is a code example demonstrating what I’d explained above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*umeE8zktt7wQ7v2xdqjmbQ.gif" /><figcaption><strong>UML diagram of Thread, ThreadLocal and ThreadLocalMap</strong></figcaption></figure><p>Lets first have the Context.java file which will hold the transactionId field.</p><pre><strong>package</strong> com.globalauth<strong>;</strong>  </pre><pre><strong>public</strong> <strong>class</strong> <strong>Context</strong> <strong>{</strong>   <br>    <strong>private</strong> StringtransactionId <strong>=</strong> <strong>null;</strong>          <br>    <em>/* getters and setters here */</em>  <br><strong>}</strong></pre><p>Now create the MyThreadLocal.java file which will act as a container to hold our context object.</p><pre><strong>package</strong> com<strong>.</strong>globalauth<strong>;</strong></pre><pre><em>/**  * this class acts as a container to our thread local variables.  * @author kkumar1  *  */</em> <br><strong>public</strong> <strong>class</strong> <strong>MyThreadLocal</strong> <strong>{</strong>   <br>    <strong>public</strong> <strong>static</strong> <strong>final</strong> ThreadLocal userThreadLocal <strong>=</strong> <strong>new</strong> ThreadLocal<strong>();</strong>   <br>    <strong>public</strong> <strong>static</strong> <strong>void</strong> <strong>set(</strong>Context user<strong>)</strong> <strong>{</strong>  <br>       userThreadLocal<strong>.</strong>set<strong>(</strong>user<strong>);</strong>  <br>    <strong>}</strong>   <br>    <strong>public</strong> <strong>static</strong> <strong>void</strong> <strong>unset()</strong> <strong>{</strong>   <br>        userThreadLocal<strong>.</strong>remove<strong>();</strong>  <br>    <strong>}</strong>   <br>    <strong>public</strong> <strong>static</strong> Context <strong>get()</strong> <strong>{</strong>   <br>       <strong>return</strong> userThreadLocal<strong>.</strong>get<strong>();</strong>  <br>    <strong>}</strong> <br><strong>}</strong></pre><p>In the above code, you are creating a ThreadLocal object as a static field which can be used by rest of the code to set/get thread local variables.</p><p>Let’s create our main class file which will generate and set the transaction ID in thread local and then call the business method.</p><pre><strong>package</strong> com<strong>.</strong>globalauth<strong>;</strong></pre><pre><strong>public</strong> <strong>class</strong> <strong>ThreadLocalDemo</strong> <strong>extends</strong> Thread <strong>{</strong>   <br>    <strong>public</strong> <strong>static</strong> <strong>void</strong> <strong>main(</strong>String args<strong>[])</strong> <strong>{</strong>    <br>        Thread threadOne <strong>=</strong> <strong>new</strong> ThreadLocalDemo<strong>();<br></strong>        threadOne<strong>.</strong>start<strong>();</strong>    <br>        Thread threadTwo <strong>=</strong> <strong>new</strong> ThreadLocalDemo<strong>();</strong>  <br>        threadTwo<strong>.</strong>start<strong>();</strong>  <br>    <strong>}</strong>   </pre><pre>    <strong>@</strong>Override  <br>    <strong>public</strong> <strong>void</strong> <strong>run()</strong> <strong>{</strong>   <em>// sample code to simulate transaction id <br>     </em>   Context context <strong>=</strong> <strong>new</strong> Context<strong>();</strong>   <br>        context<strong>.</strong>setTransactionId<strong>(</strong>getName<strong>());</strong>    <em>// set the context object in thread local to access it somewhere else <br>    </em>   MyThreadLocal<strong>.</strong>set<strong>(</strong>context<strong>);</strong>    <em>/* note that we are not explicitly passing the transaction id */</em>   <br>        <strong>new</strong> <strong>BusinessService().</strong>businessMethod<strong>();</strong>   <br>        MyThreadLocal<strong>.</strong>unset<strong>();</strong>   <br>    <strong>}</strong> <br><strong>}</strong></pre><p>Finally, here’s the code for the BusinessService.java which will read from thread local and use the value.</p><pre><strong>package</strong> com<strong>.</strong>globalauth<strong>;</strong></pre><pre><strong>public</strong> <strong>class</strong> <strong>BusinessService</strong> <strong>{</strong>   <br>    <strong>public</strong> <strong>void</strong> <strong>businessMethod()</strong> <strong>{</strong>   <em>// get the context from thread local </em>   <br>        Context context <strong>=</strong> MyThreadLocal<strong>.</strong>get<strong>();<br></strong>        System<strong>.</strong>out<strong>.</strong>println<strong>(</strong>context<strong>.</strong>getTransactionId<strong>());</strong>  <br>    <strong>}</strong> <br><strong>}</strong></pre><p>When you run the ThreadLocalDemo file, you’ll get the below output:</p><pre>Thread<strong>-</strong>0 <br>Thread<strong>-</strong>1</pre><ul><li><strong>Resource owner : </strong>An entity capable of granting access to a protected resource. When the resource owner is a person, it is referred to as an<br> end-user.</li><li><strong>Resource server : </strong>The server hosting the protected resources, capable of accepting and responding to protected resource requests using access tokens.</li><li><strong>Application/client : </strong>An application making protected resource requests on behalf of the resource owner and with its authorization. The term “client” does not imply any particular implementation characteristics (e.g.,<br> whether the application executes on a server, a desktop, or other<br> devices).</li><li><strong>Authorization server : </strong>The server issuing access tokens to the client after successfully authenticating the resource owner and obtaining authorization.</li><li><strong>Access token : Access token </strong>is what is issued to the client once the client successfully authenticates itself (using the consumer key &amp; secret). This access token defines the privileges of the client (what data the client can and cannot access). Now every time the client wants to access the end-user’s data, the <strong><em>access token secret</em></strong> is sent with the access token as a password.</li><li><strong>Refresh token : </strong>A <strong><em>Refresh Token</em></strong> is a special kind of token that can be used to obtain a renewed access token — that allows accessing a protected resource — at any time.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h2vY2bWuC6_6jiCKMBrykg.png" /></figure><h3>Traditional JEE Application Server Anatomy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*8rdW6ndqULqTzC4pStQmpw.png" /><figcaption><strong>Traditional JEE application server</strong></figcaption></figure><ol><li><strong><em>Web browser </em>: </strong>A <strong><em>web browser</em></strong> (commonly referred to as a <strong><em>browser</em></strong>) is a <a href="https://en.wikipedia.org/wiki/Software_application">software application</a> for accessing information on the <a href="https://en.wikipedia.org/wiki/World_Wide_Web">World Wide Web</a>. Which acts as a mediator between web server and user.</li><li><strong><em>HTTP listener </em>: </strong>Is a daemon process listening on specific port for <strong><em>HTTP</em> requests</strong>. On receiving a request it will create new thread and delegates the request to <strong><em>request handler</em></strong> (or <strong><em>request processor</em></strong>).</li><li><strong><em>Filter chains : </em></strong>It is a bunch of filters organized in specific order, where each of the filters has a particular responsibility and filters are added or removed from the configuration depending on which services are required.The ordering of the filters is important as there are dependencies between them.</li><li><strong><em>Application: </em></strong>Your JEE application containing servlets, MVC controllers or REST controllers, based on the request URI, the request dispatcher or servlet mapper dispatcher routes request to appropriate controller using information defined in <strong><em>deployment descriptor</em>.</strong></li><li><strong><em>Deployment descriptor &amp; application context : </em></strong>Deployment descriptor is a <strong><em>configuration file</em></strong> for an <strong><em>artifact</em></strong> that is deployed to some container/engine. It describes how a component, module or application should be deployed. It directs a deployment tool to deploy a module or application with specific container options, security settings and describes specific configuration requirements. XML is used for the syntax of these deployment descriptor files. For web applications, the deployment descriptor must be called <strong><em>web.xml</em></strong> and must reside in the <strong><em>WEB-INF</em> </strong>directory in the web application root. For Java EE applications, the deployment descriptor must be named <strong><em>application.xml</em></strong> and must be placed directly in the <strong><em>META-INF</em></strong> directory at the top level of the <strong><em>application.ear</em></strong><a href="https://en.wikipedia.org/wiki/EAR_(file_format)"><em> </em>file</a>. The <strong><em>ApplicationContext</em> </strong>is the central interface within a Spring Application for providing configuration information to the application. It is read-only at run time , but can be reloaded if necessary and supported by the application.</li><li><strong><em>Request processor</em> : </strong>On receiving a request, it validates the request and binds correct <strong><em>session</em></strong> to the current thread.</li></ol><blockquote><strong>Request processor</strong> is an abstract term, It consists of several modules or micro modules depending on the vendor. The below are few of them.</blockquote><blockquote><strong>Location Manager</strong>–The location manager parses the incoming IP address, as well as IP addresses present in alternate tracking headers, such as the X-Forwarded-For header.</blockquote><blockquote><strong>Environment Manager</strong>–The environment manager parses the incoming user-agent header, if present.</blockquote><h3>Drawbacks of traditional system.</h3><p>In the traditional client-server authentication model, the client<br> requests an access-restricted resource (protected resource) on the<br> server by authenticating with the server using the resource owner’s<br> credentials. In order to provide third-party applications access to<br> restricted resources, the resource owner shares its credentials with<br> the third party. This creates several problems and limitations:</p><ul><li>Third-party applications are <strong><em>required to store the resource<br> owner’s credentials</em></strong> for future use, typically a password in<br> clear-text.</li><li>Servers are <strong><em>required to support password authentication</em></strong>, despite<br> the security weaknesses inherent in passwords.</li><li>Third-party applications gain overly broad access to the resource<br> owner’s protected resources, leaving resource owners without any<br> <strong><em>ability to restrict duration or access to a limited subset of<br> resources</em></strong>.</li><li><strong><em>Resource owners cannot revoke access</em></strong> to an individual third party<br> without revoking access to all third parties, and must do so by<br> changing the third party’s password.</li><li><strong><em>Compromise of any third-party application</em></strong> results in compromise of<br> the end-user’s password and all of the data protected by that<br> password.</li></ul><h3>OAuth in Action…</h3><p>OAuth addresses these issues by introducing an <strong><em>authorization layer</em></strong><br> and <strong><em>separating the role of the client from that of the resource<br> owner</em></strong>. In OAuth, the client requests access to resources controlled<br> by the resource owner and hosted by the resource server, and is<br> issued a different set of credentials than those of the resource<br> owner.</p><p>Instead of using the resource owner’s credentials to access protected<br> resources, the client obtains an <strong><em>access token </em></strong>— a string denoting a<br> specific scope, lifetime, and other access attributes. Access tokens<br> are issued to third-party clients by an authorization server with the<br> approval of the resource owner. The client uses the access token to<br> access the protected resources hosted by the resource server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lm2uFrQNSHw4-82Mj-CRzQ.png" /></figure><p><strong><em>Authorization grant : </em></strong>An <strong><em>authorization grant</em></strong> is a credential representing the resource owner’s authorization (to access its protected resources) used by the client to obtain an access token. This specification defines four<br> grant types — <strong><em>authorization code, implicit, resource owner password<br> credentials, and client credentials </em></strong>— as well as an extensibility<br> mechanism for defining additional types.</p><ul><li><strong><em>Authorization code : </em></strong>The authorization code is obtained by using an authorization server as an intermediary between the client and resource owner. Instead of requesting authorization directly from the resource owner, the client directs the resource owner to an authorization server, which in turn directs the resource owner back to the client with the authorization code.</li></ul><blockquote><em>Before directing the resource owner back to the client with the authorization code, the authorization server authenticates the resource owner and obtains authorization. Because the resource owner only authenticates with the authorization server, the resource owner&#39;s credentials are never shared with the client.</em></blockquote><blockquote><em>The authorization code provides a few important security benefits, such as the ability to authenticate the client, as well as the transmission of the access token directly to the client without passing it through the resource owner&#39;s user-agent and potentially exposing it to others, including the resource owner.</em></blockquote><ul><li><strong><em>Implicit : </em></strong>The implicit grant is a simplified authorization code flow <strong><em>optimized for clients implemented in a browser using a scripting language such as JavaScript</em></strong>. In the implicit flow, instead of issuing the client an authorization code, <strong><em>the client is issued an access token directly</em></strong>. The grant type is implicit, as no intermediate credentials are issued.</li></ul><blockquote>When issuing an access token during the implicit grant flow, the authorization server does not authenticate the client. In some cases, the client identity can be verified via the redirection URI used to deliver the access token to the client. The access token may be exposed to the resource owner or other applications with access to the resource owner&#39;s user-agent.</blockquote><blockquote>Implicit grants improve the responsiveness and efficiency of some clients, since it reduces the number of round trips required to obtain an access token. However, this convenience should be weighed against the security implications of using implicit grants, such as those described in Sections <a href="https://tools.ietf.org/html/rfc6749#section-10.3">10.3</a> and <a href="https://tools.ietf.org/html/rfc6749#section-10.16">10.16</a>, especially when the authorization code grant type is available.</blockquote><ul><li><strong><em>Resource owner password credentials : </em></strong>The resource owner password credentials can be used directly as an authorization grant to obtain an access token. The credentials should only be used when there is a high degree of trust between the resource owner and the client (e.g., the client is part of the device operating system or a highly privileged application), and when other authorization grant types are not available (such as an authorization code).</li></ul><blockquote>Even though this grant type requires direct client access to the<br> resource owner credentials, the resource owner credentials are used<br> for a single request and are exchanged for an access token. This<br> grant type can eliminate the need for the client to store the<br> resource owner credentials for future use, by exchanging the<br> credentials with a long-lived access token or refresh token.</blockquote><ul><li><strong><em>Client credentials : </em></strong>The client credentials (or other forms of client authentication) can be used as an authorization grant when the authorization scope is limited to the protected resources under the control of the client, or to protected resources previously arranged with the authorization server. Client credentials are used as an authorization grant typically when the client is acting on its own behalf (the client is also the resource owner) or is requesting access to protected resources based on an authorization previously arranged with the authorization server.</li></ul><h3>Interoperability</h3><p>OAuth 2.0 provides a rich authorization framework with well-defined security properties. However, as a rich and highly extensible framework with many optional components, on its own, this specification is likely to produce a wide range of non-interoperable implementations.</p><p>In addition, this specification leaves a few required components partially or fully undefined (e.g., client registration, authorization server capabilities, endpoint discovery). Without these components, clients must be manually and specifically configured against a specific authorization server and resource server in order to interoperate.</p><h3>Client Types</h3><p><strong>Public : </strong>Clients incapable of maintaining the confidentiality of their<br> credentials (e.g., clients executing on the device used by the<br> resource owner, such as an installed native application or a web<br> browser-based application), and incapable of secure client<br> authentication via any other means.</p><p><strong>Confidential : </strong>Clients capable of maintaining the confidentiality of their<br> credentials (e.g., client implemented on a secure server with<br> restricted access to the client credentials), or capable of secure<br> client authentication using other means.</p><h3>Client Registration</h3><p>Before initiating the protocol, the client registers with the authorization server. The means through which the client registers with the authorization server are beyond the scope of this specification but typically involve end-user interaction with an HTML registration form.<br>Client registration does not require a direct interaction between the client and the authorization server. When supported by the authorization server, registration can rely on other means for establishing trust and obtaining the required client properties (e.g., redirection URI, client type). For example, registration can be accomplished using a self-issued or third-party-issued assertion, or by the authorization server performing client discovery using a trusted channel.</p><h3><strong>Appendix</strong></h3><p><strong><em>Validating access token : </em></strong>Validating access token by resource server is beyond the scope of this article and is specific to the vendor/implementor . However, the open standard implementation to validate the access token is JWT(JSON Web Token).</p><p><a href="https://jwt.io/">Learn more</a>, <a href="https://jwt.io/introduction/">Know more</a></p><p><strong><em>Re-using Web subject and stacking previous principals : </em></strong>Since the user permissions, user roles and user groups will not change often, Hence shiro will retain the subject in cache and binds the new principal to the cached Web subject.</p><h3>References</h3><ul><li><a href="https://shiro.apache.org/web.html">Apache Shiro | Simple. Java. Security.</a></li><li><a href="https://www.journaldev.com/1907/java-session-management-servlet-httpsession-url-rewriting">Session Management in Java - HttpServlet, Cookies, URL Rewriting - JournalDev</a></li><li><a href="https://docs.oracle.com/cd/E19830-01/819-4712/ablta/index.html">HTTP Listeners (Sun Java System Application Server Platform Edition 8.2 Administration Guide)</a></li><li><a href="https://docs.oracle.com/cd/E19798-01/821-1841/bnbxk/index.html">What Are Realms, Users, Groups, and Roles? (The Java EE 6 Tutorial)</a></li><li><a href="https://dzone.com/articles/painless-introduction-javas-threadlocal-storage">A Painless Introduction to Java&#39;s ThreadLocal Storage - DZone Java</a></li><li><a href="https://blog.smartbear.com/programming/how-and-when-to-use-javas-threadlocal-object/">How and When to Use Java&#39;s ThreadLocal Object</a></li><li><a href="https://github.com/apache/shiro/blob/master/web/src/main/java/org/apache/shiro/web/session/mgt/DefaultWebSessionManager.java">apache/shiro</a></li><li><a href="https://github.com/apache/shiro/blob/2.0-api-design-changes/core/src/main/java/org/apache/shiro/session/mgt/SimpleSession.java">apache/shiro</a></li><li><a href="https://tools.ietf.org/html/rfc6749">RFC 6749: The OAuth 2.0 Authorization Framework</a></li><li><a href="https://github.com/javaee/glassfish/blob/master/appserver/core/javaee-kernel/src/main/java/org/glassfish/kernel/javaee/WebContainerStarter.java">javaee/glassfish</a></li><li><a href="https://github.com/javaee/glassfish/blob/master/appserver/transaction/jta/src/main/java/com/sun/enterprise/transaction/JavaEETransactionManagerSimplified.java#L1012">javaee/glassfish</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f08e116974c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with nemo…..]]></title>
            <link>https://medium.com/@kiranchowdhary/getting-started-with-nemo-e034030fe06e?source=rss-1c7dd04b732b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e034030fe06e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[selenium]]></category>
            <dc:creator><![CDATA[Kiran R]]></dc:creator>
            <pubDate>Wed, 19 Jul 2017 06:03:27 GMT</pubDate>
            <atom:updated>2018-05-17T08:45:16.885Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Nemo</strong></h3><p><a href="http://nemo.js.org/">Nemo</a> is an open-source, NodeJS automation framework that was developed by PayPal. Nemo provides a simple way to add selenium automation to your NodeJS web projects. With a powerful configuration ability provided by <a href="https://github.com/krakenjs/confit">krakenjs/confit</a>, and plugin architecture, Nemo is flexible enough to handle any browser/device automation need.</p><p>Nemo is built to easily plug into any task runner and test runner. But in this README we will only cover setup and architecture of Nemo as a standalone entity.</p><p>Nemo is a framework and set of conventions for automated testing of web and even native applications. How you use it is only limited by your imagination. A common starting point is to pair Nemo with a task runner (e.g. Grunt) and a test runner (e.g. Mocha). But if you have a different task and test runner, Nemo will work with that as well.</p><p>To know more about mocha please refer to <a href="https://mochajs.org/">https://mochajs.org/</a></p><p><strong>Nemo docs</strong></p><p><a href="https://github.com/paypal/nemo-docs">paypal/nemo-docs</a></p><h3>Getting started</h3><h3>Install</h3><pre>npm install --save-dev nemo</pre><h3>Pre-requisites</h3><h4>Webdriver</h4><p>As long as you have the appropriate browser or browser driver (selenium-standalone, chromedriver) on your PATH, the rest of this should work fine. <a href="https://github.com/paypal/nemo-docs/blob/master/driver-setup.md">Please see here for more information about setting up a webdriver</a>.</p><h4>Direct configuration</h4><p>If you install this repo you’ll get the following in examples/setup.js. Note the Nemo() constructor is directly accepting the needed configuration, along with a callback function.</p><p><em>Take a look at below code:</em></p><pre>Nemo({<br>  &quot;driver&quot;: {<br>    &quot;browser&quot;: &quot;firefox&quot;<br>  },<br>  &#39;data&#39;: {<br>    &#39;baseUrl&#39;: &#39;https://www.paypal.com&#39;<br>  }<br>}, function (err, nemo) {<br>  //always check for errors!<br>  if (!!err) {<br>    console.log(&#39;Error during Nemo setup&#39;, err);<br>  }<br>  nemo.driver.get(nemo.data.baseUrl);<br>  nemo.driver.getCapabilities().<br>    then(function (caps) {<br>      console.info(&quot;Nemo successfully launched&quot;, caps.caps_.browserName);<br>    });<br>  nemo.driver.quit();<br>});</pre><p><em>Run it:</em></p><pre>$ node examples/setup.js<br>Nemo successfully launched firefox</pre><h4>Using config files</h4><p><em>Look at </em><em>examples/setupWithConfigFiles.js</em></p><pre>//passing __dirname as the first argument tells confit to<br>//look in __dirname + &#39;/config&#39; for config files<br>Nemo(__dirname, function (err, nemo) {<br>  //always check for errors!<br>  if (!!err) {<br>    console.log(&#39;Error during Nemo setup&#39;, err);<br>  }</pre><pre>  nemo.driver.get(nemo.data.baseUrl);<br>  nemo.driver.getCapabilities().<br>    then(function (caps) {<br>      console.info(&quot;Nemo successfully launched&quot;, caps.caps_.browserName);<br>    });<br>  nemo.driver.quit();<br>});</pre><p>Note the comment above that passing a filesystem path as the first argument to Nemo() will tell confit to look in that directory + /config for config files.</p><p><em>Look at </em><em>examples/config/config.json</em></p><pre>{<br>  &quot;driver&quot;: {<br>    &quot;browser&quot;: &quot;config:BROWSER&quot;<br>  },<br>  &quot;data&quot;: {<br>    &quot;baseUrl&quot;: &quot;https://www.paypal.com&quot;<br>  },<br>  &quot;BROWSER&quot;: &quot;firefox&quot;<br>}</pre><p>That is almost the same config as the first example. But notice &quot;config:BROWSER&quot;. Yes, confit will resolve that to the config property &quot;BROWSER&quot;.</p><p><em>Run this and it will open the Firefox browser:</em></p><pre>$ node examples/setup.js<br>Nemo successfully launched firefox</pre><p><em>Now run this command:</em></p><pre>$ node examples/setupWithConfigDir.js --BROWSER=chrome<br>Nemo successfully launched chrome</pre><p>Here, confit resolves the --BROWSER=chrome command line argument and overrides the BROWSER value from config.json</p><p><em>Now this command:</em></p><pre>$ BROWSER=chrome node examples/setupWithConfigDir.js<br>Nemo successfully launched chrome</pre><p>Here, confit resolves the BROWSER environment variable and overrides BROWSER from config.json</p><p><em>What if we set both?</em></p><pre>$ BROWSER=chrome node examples/setupWithConfigDir.js --BROWSER=phantomjs<br>Nemo successfully launched chrome</pre><p>You can see that the environment variable wins.</p><p><em>Now try this command:</em></p><pre>$ NODE_ENV=special node examples/setupWithConfigDir.js<br>Nemo successfully launched phantomjs</pre><p>Note that confit uses the value of NODE_ENV to look for an override config file. In this case config/special.json:</p><pre>{<br>  &quot;driver&quot;: {<br>    &quot;browser&quot;: &quot;phantomjs&quot;<br>  },<br>  &quot;data&quot;: {<br>    &quot;baseUrl&quot;: &quot;https://www.paypal.com&quot;<br>  }<br>}</pre><p>Hopefully this was an instructive dive into the possibilities of Nemo + confit. There is more to learn but hopefully this is enough to whet your appetite for now!</p><h3>Nemo and Plugins</h3><p><em>Look at the </em><em>example/setupWithPlugin.js file:</em></p><pre>Nemo(basedir, function (err, nemo) {<br>  //always check for errors!<br>  if (!!err) {<br>    console.log(&#39;Error during Nemo setup&#39;, err);<br>  }<br>  nemo.driver.getCapabilities().<br>    then(function (caps) {<br>      console.info(&quot;Nemo successfully launched&quot;, caps.caps_.browserName);<br>    });<br>  nemo.driver.get(nemo.data.baseUrl);<br>  nemo.cookie.deleteAll();<br>  nemo.cookie.set(&#39;foo&#39;, &#39;bar&#39;);<br>  nemo.cookie.getAll().then(function (cookies) {<br>    console.log(&#39;cookies&#39;, cookies);<br>    console.log(&#39;=======================&#39;);<br>  });<br>  nemo.cookie.deleteAll();<br>  nemo.cookie.getAll().then(function (cookies) {<br>    console.log(&#39;cookies&#39;, cookies);<br>  });<br>  nemo.driver.quit();<br>});</pre><p>Notice the nemo.cookie namespace. This is actually a plugin, and if you look at the config for this setup:</p><pre>{<br>  &quot;driver&quot;: {<br>    &quot;browser&quot;: &quot;firefox&quot;<br>  },<br>  &quot;data&quot;: {<br>    &quot;baseUrl&quot;: &quot;https://www.paypal.com&quot;<br>  },<br>  &quot;plugins&quot;: {<br>    &quot;cookie&quot;: {<br>      &quot;module&quot;: &quot;path:./nemo-cookie&quot;<br>    }<br>  }<br>}</pre><p><em>You’ll see the </em><em>plugins.cookie section, which is loading </em><em>examples/plugin/nemo-cookie.js as a plugin:</em></p><pre>&#39;use strict&#39;;</pre><pre>module.exports = {<br>  &quot;setup&quot;: function (nemo, callback) {<br>    nemo.cookie = {};<br>    nemo.cookie.delete = function (name) {<br>      return nemo.driver.manage().deleteCookie(name);<br>    };<br>    nemo.cookie.deleteAll = function () {<br>      return nemo.driver.manage().deleteAllCookies();<br>    };<br>    nemo.cookie.set = function (name, value, path, domain, isSecure, expiry) {<br>      return nemo.driver.manage().addCookie(name, value, path, domain, isSecure, expiry)<br>    };<br>    nemo.cookie.get = function (name) {<br>      return nemo.driver.manage().getCookie(name);<br>    };<br>    nemo.cookie.getAll = function () {<br>      return nemo.driver.manage().getCookies();<br>    };<br>    callback(null);</pre><pre>  }<br>};</pre><p><em>Running this example:</em></p><pre>$ node examples/setupWithPlugin.js<br>Nemo successfully launched firefox<br>cookies [ { name: &#39;foo&#39;,<br>   value: &#39;bar&#39;,<br>   path: &#39;&#39;,<br>   domain: &#39;www.paypal.com&#39;,<br>   secure: false,<br>   expiry: null } ]<br>=======================<br>cookies []<br>$</pre><p>This illustrates how you can create a plugin, and the sorts of things you might want to do with a plugin.</p><h3>API</h3><h3>Nemo</h3><p>function Nemo([[nemoBaseDir, ][config, ][callback]] | [Confit object]) { ... }</p><p>@argument nemoBaseDir {String} (optional) - If provided, should be a filesystem path to your test suite. Nemo will expect to find a /config directory beneath that. &lt;nemoBaseDir&gt;/config/config.json should have your default configuration (described below). nemoBaseDir can alternatively be set as an environment variable. If it is not set, you need to pass your configuration as the config parameter (see below).</p><p>@argument config {Object} (optional) - Can be a full configuration (if nemoBaseDir not provided) or additional/override configuration to what&#39;s in your config files.</p><p>@argument callback {Function} (optional) - This function will be called once the nemo object is fully resolved. It may be called with an error as the first argument which has important debugging information. So make sure to check for an error. The second argument is the resolved nemo object.</p><p>@argument Confit object {Object} (optional) - If a Confit object is passed, the configuration step is skipped and the passed object is used directly.</p><p>@returns nemo {Object|Promise} - Promise returned if no callback provided. Promise resolves with the same nemo object as would be given to the callback. The nemo object has the following properties:</p><ul><li><strong>driver -</strong> The live selenium-webdriver API. See WebDriver API Doc: <a href="http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebDriver.html">http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebDriver.html</a></li><li><strong>wd -</strong> This is a reference to the selenium-webdriver module: <a href="http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/index.html">http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/index.html</a></li><li><strong>data -</strong> Pass through of any data included in the data property of the configuration</li><li><strong>_config -</strong> This is the confit configuration object. Documented here: <a href="https://github.com/krakenjs/confit#config-api">https://github.com/krakenjs/confit#config-api</a></li><li><strong>plugin namespace(s) -</strong> Plugins are responsible for registering their own namespace under nemo. The convention is that the plugin should register the same namespace as is specified in the plugin configuration. <em>E.g. the </em><em>nemo-view module registers itself as </em><em>nemo.view and is configured like this:</em></li></ul><pre>{<br>  &quot;driver&quot;: ...<br>  &quot;plugins&quot;: {<br>    &quot;view&quot;: {<br>      &quot;module&quot;: &quot;nemo-view&quot;<br>    }<br>  }</pre><p>Typical usage of Nemo constructor</p><p>A typical pattern would be to use mocha as a test runner, resolve nemo in the context of the mocha before function, and use the mocha done function as the callback:</p><pre>var nemo;<br>describe(&#39;my nemo suite&#39;, function () {<br>  before(function (done) {<br>    Nemo(config, function (err, resolvedNemo) {<br>        nemo = resolvedNemo;<br>        done(err)<br>    });<br>  });<br>  it(&#39;will launch browsers!&#39;, function (done) {<br>    nemo.driver.get(&#39;https://www.paypal.com&#39;);<br>    nemo.driver.quit().then(function () {<br>       done();<br>    });<br>  });<br>});</pre><h3>Configure</h3><p>Calling Configure will return a promise which resolves as a Confit object. This is the same method Nemo calls internally in the basic use case. You might want to call Configure if you are interested in the resolved configuration object but not yet ready to start the webdriver. An example would be if you want to make further changes to the configuration based on what gets resolved, prior to starting the webdriver.</p><p>function Configure([nemoBaseDir, ][configOverride]) { ... }</p><p>@argument nemoBaseDir {String} (optional) - If provided, should be a filesystem path. There should be a /configdirectory beneath that. &lt;nemoBaseDir&gt;/config/config.json should have your default configuration. nemoBaseDir can alternatively be set as an environment variable. If it is not set, you need to pass your configuration as the configparameter (see below).</p><p>@argument config {Object} (optional) - Can be a full configuration (if nemoBaseDir not provided) or additional/override configuration to what&#39;s in your config files.</p><p>@returns {Promise} - Promise resolves as a confit object:</p><h3>Configuration Input</h3><pre>{<br>  &quot;driver&quot;: { /** properties used by Nemo to setup the driver instance **/ },<br>  &quot;plugins&quot;: { /** plugins to initialize **/},<br>  &quot;data&quot;: { /** arbitrary data to pass through to nemo instance **/ }<br>}</pre><p>This configuration object is optional, as long as you’ve got nemoData set as an environment variable (see below).</p><h3>driver</h3><p>Here are the driver properties recognized by Nemo. This is ALL of them. Please be aware that you really only need to supply &quot;browser&quot; to get things working initially.</p><h4>browser (optional)</h4><p>Browser you wish to automate. Make sure that your chosen webdriver has this browser option available. While this is “optional” you must choose a browser. Either use this property or the builders.forBrowser option (see below). If both are specified, builders.forBrowser takes precedence.</p><h4>local (optional, defaults to false)</h4><p>Set local to true if you want Nemo to attempt to start a standalone binary on your system (like selenium-standalone-server) or use a local browser/driver like Chrome/chromedriver or PhantomJS.</p><h4>server (optional)</h4><p>Webdriver server URL you wish to use. This setting will be overridden if you are using builders.usingServer</p><h4>serverProps (optional/conditional)</h4><p>Additional server properties required of the ‘targetServer’</p><p><em>You can also set args and jvmArgs to the selenium jar process as follows:</em></p><pre>&quot;serverProps&quot;: {<br>  &quot;port&quot;: 4444,<br>  &quot;args&quot;: [&quot;-firefoxProfileTemplate&quot;,&quot;/Users/medelman/Desktop/ffprofiles&quot;],<br>  &quot;jvmArgs&quot;: [&quot;-someJvmArg&quot;, &quot;someJvmArgValue&quot;]<br>}</pre><h4>jar (optional/conditional)</h4><p>Path to your webdriver server Jar file. Leave unset if you aren’t using a local selenium-standalone Jar (or similar).</p><h4>serverCaps (optional)</h4><p>serverCaps would map to the capabilities here: <a href="http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_Capabilities.html">http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_Capabilities.html</a></p><p>Some webdrivers (for instance ios-driver, or appium) would have additional capabilities which can be set via this variable. As an example, you can connect to saucelabs by adding this serverCaps:</p><pre>&quot;serverCaps&quot;: {<br>	&quot;username&quot;: &quot;medelman&quot;,<br>	&quot;accessKey&quot;: &quot;b38e179e-079a-417d-beb8-xyz&quot;, //not my real access key<br>	&quot;name&quot;: &quot;Test Suite Name&quot;, //sauce labs session name<br>	&quot;tags&quot;: [&#39;tag1&#39;,&#39;tag2&#39;] //sauce labs tag names<br>}</pre><h4>proxyDetails (optional)</h4><p>If you want to run test by setting proxy in the browser, you can use ‘proxyDetails’ configuration. Following options are available: direct, manual, pac and system. Default is ‘direct’. For more information refer : <a href="http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/proxy.html">http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/proxy.html</a></p><pre>&quot;proxyDetails&quot; : {<br>    &quot;method&quot;: &quot;manual&quot;,<br>    &quot;args&quot;: [{&quot;http&quot;: &quot;localhost:9001&quot;,&quot;ftp&quot;:&quot;localhost:9001&quot;,&quot;https&quot;:&quot;localhost:9001&quot;}]<br>}</pre><h4>builders (optional)</h4><p>This is a JSON interface to any of the Builder methods which take simple arguments and return the builder. See the Builder class here: <a href="http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_Builder.html">http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_Builder.html</a></p><p>Useful such functions are:</p><ul><li>forBrowser (can take the place of “browser”, “local” and “jar” properties above)</li><li>withCapabilities (can take the place of “serverCaps” above)</li></ul><p>The nemo setup routine will prefer these “builder” properties over other abstracted properties above, if there is a conflict.</p><h4>selenium.version (optional)</h4><p>Since nemo requires a narrow range of versions of selenium-webdriver, you may have a need to upgrade selenium-webdriver (or downgrade) outside of the supported versions that nemo uses. You can do that by using selenium.version. E.g.</p><pre>&quot;driver&quot;: {<br>  &quot;browser&quot;: &quot;firefox&quot;,<br>  &quot;selenium.version&quot;: &quot;^2.53.1&quot;<br>}</pre><p>Nemo will upgrade its internal dependency to what is set in this property. The npm install will only run if the version specified is not already installed.</p><h3>plugins</h3><p>Plugins are registered with JSON like the following (will vary based on your plugins)</p><pre>{<br>	&quot;plugins&quot;: {<br>		&quot;samplePlugin&quot;: {<br>			&quot;module&quot;: &quot;path:plugin/sample-plugin&quot;,<br>			&quot;arguments&quot;: [...],<br>			&quot;priority&quot;: 99<br>		},<br>		&quot;view&quot;: {<br>			&quot;module&quot;: &quot;nemo-view&quot;<br>		}<br>	}<br>}</pre><p>Plugin.pluginName parameters:</p><ul><li>module {String} — Module must resolve to a require’able module, either via name (in the case it is in your dependency tree) or via path to the file or directory.</li><li>arguments {Array} (optional, depending on plugin) — Your plugin will be called via its setup method with these arguments: [configArg1, configArg2, ..., ]nemo, callback. Please note that the braces there indicate &quot;optional&quot;. The arguments will be applied via Function.apply</li><li>priority {Number} (optional, depending on plugin) — A priority value of &lt; 100 will register this plugin BEFORE the selenium driver object is created. This means that such a plugin can modify config properties prior to driver setup. Leaving priority unset will register the plugin after the driver object is created.</li></ul><h3>data</h3><p>Data will be arbitrary stuff that you might like to use in your tests. In a lot of the examples we set data.baseUrl but again, that&#39;s arbitrary and not required. You could pass and use data.cupcakes if you want. Cupcakes are awesome.</p><h3>Shortstop handlers</h3><p>Shortstop handlers are data processors that key off of directives in the JSON data. Ones that are enabled in nemo are:</p><h3>path</h3><p>use path to prepend the nemoBaseDir (or process.cwd()) to a value. E.g. if nemoBaseDir is .../myApp/tests then a config value of &#39;path:plugin/myPlugin&#39; will resolve to .../myApp/tests/plugin/myPlugin</p><h3>env</h3><p>use env to reference environment variables. E.g. a config value of &#39;env:PATH&#39; will resolve to/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:...</p><h3>argv</h3><p>use argv to reference argv variables. E.g. a config value of &#39;argv:browser&#39; will resolve to firefox if you set --browser firefox as an argv on the command line</p><h3>config</h3><p>Use config to reference data in other parts of the JSON configuration. E.g. in the following config.json:</p><pre>{<br>  &quot;driver&quot;: {<br>    ...<br>  },<br>  &quot;plugins&quot;: {<br>    &quot;myPlugin&quot;: {<br>      &quot;module&quot;: &quot;nemo-some-plugin&quot;,<br>      &quot;arguments&quot;: [&quot;config:data.someProp&quot;]<br>    }<br>  },<br>  &quot;data&quot;: {<br>    &quot;someProp&quot;: &quot;someVal&quot;<br>  }<br>}</pre><p>The value of plugins.myPlugin.arguments[0] will be someVal</p><h3>file</h3><p>Please see <a href="https://github.com/krakenjs/shortstop-handlers#handlersfilebasedir-options">https://github.com/krakenjs/shortstop-handlers#handlersfilebasedir-options</a></p><h3>base64</h3><p>Please see <a href="https://github.com/krakenjs/shortstop-handlers#handlersbase64">https://github.com/krakenjs/shortstop-handlers#handlersbase64</a></p><h3>require</h3><p>Please see <a href="https://github.com/krakenjs/shortstop-handlers#handlersrequirebasedir">https://github.com/krakenjs/shortstop-handlers#handlersrequirebasedir</a></p><h3>exec</h3><p>Please see <a href="https://github.com/krakenjs/shortstop-handlers#handlersexecbasedir">https://github.com/krakenjs/shortstop-handlers#handlersexecbasedir</a></p><h3>glob</h3><p>Please see <a href="https://github.com/krakenjs/shortstop-handlers#handlersglobbasediroptions">https://github.com/krakenjs/shortstop-handlers#handlersglobbasediroptions</a></p><h3>Plugins</h3><p>Authoring a plugin, or using an existing plugin, is a great way to increase the power and usefulness of your Nemo installation. A plugin should add its API to the nemo object it receives and passes on in its constructor (see &quot;plugin interface&quot; below)</p><h3>Plugin interface</h3><p><em>A plugin should export a setup function with the following interface:</em></p><pre>module.exports.setup = function myPlugin([arg1, arg2, ..., ]nemo, callback) {<br>  ...<br>  //add your plugin to the nemo namespace<br>  nemo.myPlugin = myPluginFactory([arg1, arg2, ...]); //adds myMethod1, myMethod2</pre><pre>  //error in your plugin setup<br>  if (err) {<br>    callback(err);<br>    return;<br>  }<br>  //continue<br>  callback(null);<br>};</pre><p>When nemo initializes your plugin, it will call the setup method with any arguments supplied in the config plus the nemo object, plus the callback function to continue plugin initialization.</p><p>Then in your module where you use Nemo, you will be able to access the plugin functionality:</p><pre>var Nemo = require(&#39;nemo&#39;);<br>Nemo({<br>  &#39;driver&#39;: {<br>    &#39;browser&#39;: &#39;firefox&#39;,<br>    &#39;local&#39;: true,<br>    &#39;jar&#39;: &#39;/usr/local/bin/selenium-server-standalone.jar&#39;<br>  },<br>  &#39;data&#39;: {<br>    &#39;baseUrl&#39;: &#39;https://www.paypal.com&#39;<br>  },<br>  &#39;plugins&#39;: {<br>    &#39;myPlugin&#39;: {<br>      &#39;module&#39;: &#39;path:plugin/my-plugin&#39;,<br>      &#39;arguments&#39;: [...]<br>      &#39;priority&#39;: 99<br>    },<br>  }<br>}, function (err, nemo) {<br>  nemo.driver.get(nemo.data.baseUrl);<br>  nemo.myPlugin.myMethod1();<br>  nemo.myPlugin.myMethod2();<br>  nemo.driver.sleep(5000).<br>    then(function() {<br>      console.info(&#39;Nemo was successful!!&#39;);<br>      nemo.driver.quit();<br>    });<br>});</pre><h3>Logging and debugging</h3><p>Nemo uses the <a href="https://github.com/visionmedia/debug.git">debug</a> module for console logging and error output. There are two classes of logging, nemo:log and nemo:error</p><p>If you want to see both classes of output, simply use the appropriate value of the DEBUG environment variable when you run nemo:</p><pre>$ DEBUG=nemo:* &lt;nemo command&gt;</pre><p><em>To see just one:</em></p><pre>$ DEBUG=nemo:error &lt;nemo command&gt;</pre><h3>Unit Tests</h3><ul><li>Unit tests run by default using headless browser <a href="http://phantomjs.org/">PhantomJS</a>. To run unit tests out of box, You must have PhantomJS installed on your system and must be present in the path</li><li>Download PhantomJS from <a href="http://phantomjs.org/download.html">here</a></li><li>On OSX, you can optionally use brew to install PhantomJS like brew install phantomjs</li><li>PhantomJS installation detailed guide on Ubuntu can be found <a href="https://gist.github.com/julionc/7476620">here</a></li><li>If you want to run unit tests on your local browser, like lets say Firefox/Chrome (make sure ChromeDriver is in current path), you need to update browser in unit test configuration, for example the browser section under test/config/config.json like <a href="https://github.com/paypal/nemo/blob/master/test/config/config.json#L19">here</a></li><li>How to run unit tests?</li><li>npm test will run unit tests as well as lint task</li><li>grunt simplemocha will just run unit tests</li><li>grunt - default grunt task will run linting as well as unit tests</li><li>To run directly using mocha assuming its globally installed on your system mocha -t 60s</li><li>Or a specific test, mocha --grep @allArgs@ -t 60s</li><li>Or post npm install on nemo module, you can run node_modules/.bin/mocha --grep @allArgs@ -t 60s</li></ul><p>For more information on Nemo take a look at here <a href="http://nemo.js.org/">http://nemo.js.org/</a></p><h3><strong>See also</strong></h3><ul><li>PhantomJS</li><li>Jasmine</li><li>Protractor</li><li>Nightwatch.js</li><li>CasperJS</li><li>Nemo.js</li><li>Buster.JS</li><li>DalekJS</li></ul><h3><strong>References</strong></h3><ul><li><a href="http://nemo.js.org/">Nemo</a></li><li><a href="https://mochajs.org/">Mocha - the fun, simple, flexible JavaScript test framework</a></li><li><a href="https://github.com/krakenjs/confit">krakenjs/confit</a></li><li><a href="https://seleniumhq.github.io/selenium/docs/api/javascript/index.html">Index</a></li><li><a href="https://www.npmjs.com/package/mocha-test-runner">mocha-test-runner</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e034030fe06e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>