<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-162532840988979012</id><updated>2025-08-31T05:14:35.410-07:00</updated><category term="Rx"/><category term="FileSystemWatcher"/><category term="Hadoop"/><category term="Jquery"/><category term="Kafka"/><category term="MVC"/><category term="OTAClient"/><title type='text'>potluri&#39;s Code Blog</title><subtitle type='html'>code</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://krishnapotluri.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://krishnapotluri.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>14</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-162532840988979012.post-7206692142987561123</id><published>2023-01-31T16:02:00.000-08:00</published><updated>2024-12-31T16:02:41.252-08:00</updated><title type='text'></title><content type='html'>&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;title&gt;SPARQL Property Paths: Advanced Graph Traversal Made Easy&lt;/title&gt;
    &lt;link href=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/themes/prism-tomorrow.min.css&quot; rel=&quot;stylesheet&quot; /&gt;
    &lt;style&gt;
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #3498db;
            --accent-color: #e74c3c;
            --bg-color: #f5f5f5;
            --text-color: #333;
            --code-bg: #282c34;
        }

        body {
            font-family: &#39;Segoe UI&#39;, Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.8;
            color: var(--text-color);
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            background-color: var(--bg-color);
        }

        .container {
            background: white;
            padding: 40px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        h1, h2, h3 {
            color: var(--primary-color);
        }

        h1 {
            font-size: 2.5em;
            text-align: center;
            margin-bottom: 1em;
            padding-bottom: 0.5em;
            border-bottom: 3px solid var(--secondary-color);
        }

        .intro {
            font-size: 1.2em;
            color: #666;
            text-align: center;
            margin-bottom: 2em;
        }

        .code-container {
            position: relative;
            margin: 20px 0;
            background: var(--code-bg);
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .code-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 20px;
            background: var(--primary-color);
            color: white;
            border-radius: 8px 8px 0 0;
        }

        .copy-button {
            background: var(--secondary-color);
            color: white;
            border: none;
            padding: 5px 15px;
            border-radius: 4px;
            cursor: pointer;
            transition: background 0.3s;
        }

        .copy-button:hover {
            background: #2980b9;
        }

        pre {
            margin: 0;
            padding: 20px;
            overflow-x: auto;
        }

        code {
            font-family: &#39;Fira Code&#39;, monospace;
            font-size: 0.9em;
        }

        .path-diagram {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
            text-align: center;
        }

        .note {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
            padding: 15px;
            margin: 20px 0;
            border-radius: 0 4px 4px 0;
        }

        .tip {
            background: #d4edda;
            border-left: 4px solid #28a745;
            padding: 15px;
            margin: 20px 0;
            border-radius: 0 4px 4px 0;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }

        th, td {
            padding: 12px;
            border: 1px solid #ddd;
            text-align: left;
        }

        th {
            background-color: var(--primary-color);
            color: white;
        }

        .success-message {
            position: fixed;
            top: 20px;
            right: 20px;
            background: #2ecc71;
            color: white;
            padding: 10px 20px;
            border-radius: 4px;
            display: none;
            z-index: 1000;
        }

        .path-operator {
            font-family: monospace;
            background: #f8f9fa;
            padding: 2px 6px;
            border-radius: 4px;
            color: var(--accent-color);
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div class=&quot;container&quot;&gt;
        &lt;h1&gt;SPARQL Property Paths: Advanced Graph Traversal Made Easy&lt;/h1&gt;
        
        &lt;p class=&quot;intro&quot;&gt;
            Master SPARQL property paths to efficiently traverse and query complex graph relationships.
        &lt;/p&gt;

        &lt;div id=&quot;copy-success&quot; class=&quot;success-message&quot;&gt;Code copied!&lt;/div&gt;

        &lt;h2&gt;🎯 What are Property Paths?&lt;/h2&gt;
        &lt;p&gt;
            Property paths in SPARQL allow you to express complex graph traversal patterns concisely. 
            They&#39;re particularly useful for finding connections between resources that may be several steps apart.
        &lt;/p&gt;

        &lt;h2&gt;🔧 Basic Path Operators&lt;/h2&gt;
        &lt;table&gt;
            &lt;tr&gt;
                &lt;th&gt;Operator&lt;/th&gt;
                &lt;th&gt;Description&lt;/th&gt;
                &lt;th&gt;Example Use Case&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td class=&quot;path-operator&quot;&gt;/&lt;/td&gt;
                &lt;td&gt;Sequence Path&lt;/td&gt;
                &lt;td&gt;Finding grandparents (parent of parent)&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td class=&quot;path-operator&quot;&gt;|&lt;/td&gt;
                &lt;td&gt;Alternative Path&lt;/td&gt;
                &lt;td&gt;Finding either authors or scientists&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td class=&quot;path-operator&quot;&gt;?&lt;/td&gt;
                &lt;td&gt;Zero or One Path&lt;/td&gt;
                &lt;td&gt;Optional relationships&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td class=&quot;path-operator&quot;&gt;*&lt;/td&gt;
                &lt;td&gt;Zero or More Path&lt;/td&gt;
                &lt;td&gt;All ancestors in a family tree&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td class=&quot;path-operator&quot;&gt;+&lt;/td&gt;
                &lt;td&gt;One or More Path&lt;/td&gt;
                &lt;td&gt;All descendants in a family tree&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td class=&quot;path-operator&quot;&gt;!&lt;/td&gt;
                &lt;td&gt;Negated Property Path&lt;/td&gt;
                &lt;td&gt;Finding relationships that are not of a specific type&lt;/td&gt;
            &lt;/tr&gt;
        &lt;/table&gt;

        &lt;h2&gt;📝 Basic Examples&lt;/h2&gt;

        &lt;h3&gt;Finding Grandparents&lt;/h3&gt;
        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;Sequence Path Example&lt;/span&gt;
                &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-sparql&quot;&gt;SELECT ?person ?grandparent
WHERE {
    ?person dbo:parent/dbo:parent ?grandparent .
}&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;div class=&quot;note&quot;&gt;
            The &lt;code&gt;/&lt;/code&gt; operator connects two properties in sequence, similar to following two separate relationships.
        &lt;/div&gt;

        &lt;h3&gt;Finding Authors or Scientists&lt;/h3&gt;
        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;Alternative Path Example&lt;/span&gt;
                &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-sparql&quot;&gt;SELECT ?person ?name
WHERE {
    ?person rdf:type/(dbo:Author|dbo:Scientist) ;
           foaf:name ?name .
}&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;h2&gt;🌟 Advanced Path Patterns&lt;/h2&gt;

        &lt;h3&gt;Academic Genealogy&lt;/h3&gt;
        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;One or More Path Example&lt;/span&gt;
                &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-sparql&quot;&gt;SELECT ?student ?advisor ?generation
WHERE {
    ?student dbo:doctoralAdvisor+ ?advisor .
    BIND(LENGTH(STR(?advisor)) AS ?generation)
}&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;div class=&quot;tip&quot;&gt;
            The &lt;code&gt;+&lt;/code&gt; operator finds one or more repetitions of the relationship, perfect for tracing academic lineage.
        &lt;/div&gt;

        &lt;h3&gt;Finding Connected Artists&lt;/h3&gt;
        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;Complex Path Example&lt;/span&gt;
                &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-sparql&quot;&gt;SELECT ?artist1 ?artist2 ?path
WHERE {
    ?artist1 rdf:type dbo:Artist .
    ?artist2 rdf:type dbo:Artist .
    ?artist1 (dbo:collaborator|dbo:influenced)* ?intermediate .
    ?intermediate (dbo:collaborator|dbo:influenced)* ?artist2 .
    BIND(CONCAT(?artist1, &quot; -&gt; &quot;, ?intermediate, &quot; -&gt; &quot;, ?artist2) AS ?path)
    FILTER(?artist1 != ?artist2)
}&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;h2&gt;💡 Best Practices&lt;/h2&gt;
        &lt;div class=&quot;tip&quot;&gt;
            &lt;strong&gt;Follow these guidelines for effective property paths:&lt;/strong&gt;
            &lt;ul&gt;
                &lt;li&gt;Use property paths for traversing known relationship patterns&lt;/li&gt;
                &lt;li&gt;Be careful with &lt;code&gt;*&lt;/code&gt; and &lt;code&gt;+&lt;/code&gt; on large datasets&lt;/li&gt;
                &lt;li&gt;Consider using LIMIT to restrict results when using recursive paths&lt;/li&gt;
                &lt;li&gt;Use named graphs to limit the scope of path traversal&lt;/li&gt;
                &lt;li&gt;Combine property paths with FILTER for more precise results&lt;/li&gt;
            &lt;/ul&gt;
        &lt;/div&gt;

        &lt;h2&gt;⚠️ Common Pitfalls&lt;/h2&gt;
        &lt;div class=&quot;warning&quot; style=&quot;background: #f8d7da; border-left-color: #dc3545;&quot;&gt;
            &lt;strong&gt;Watch out for:&lt;/strong&gt;
            &lt;ul&gt;
                &lt;li&gt;Unbounded path expressions (&lt;code&gt;*&lt;/code&gt; and &lt;code&gt;+&lt;/code&gt;) on large datasets&lt;/li&gt;
                &lt;li&gt;Complex path patterns that may timeout&lt;/li&gt;
                &lt;li&gt;Forgetting to filter out self-references in cyclic paths&lt;/li&gt;
                &lt;li&gt;Not considering the direction of relationships&lt;/li&gt;
            &lt;/ul&gt;
        &lt;/div&gt;

        &lt;h2&gt;🎯 Use Cases&lt;/h2&gt;
        &lt;ul&gt;
            &lt;li&gt;Social network analysis (finding connections between people)&lt;/li&gt;
            &lt;li&gt;Genealogical research (family trees)&lt;/li&gt;
            &lt;li&gt;Citation networks (academic papers and their references)&lt;/li&gt;
            &lt;li&gt;Organizational hierarchies&lt;/li&gt;
            &lt;li&gt;Knowledge graph navigation&lt;/li&gt;
        &lt;/ul&gt;

        &lt;h2&gt;🚀 Advanced Techniques&lt;/h2&gt;
        &lt;h3&gt;Limited Length Paths&lt;/h3&gt;
        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;Path Length Restriction Example&lt;/span&gt;
                &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-sparql&quot;&gt;SELECT DISTINCT ?author1 ?author2
WHERE {
    ?author1 rdf:type dbo:Author .
    ?author2 rdf:type dbo:Author .
    ?author1 (dbo:coAuthor){1,3} ?author2 .
    FILTER(?author1 != ?author2)
}&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;div class=&quot;note&quot;&gt;
            The &lt;code&gt;{1,3}&lt;/code&gt; syntax restricts the path length to between 1 and 3 steps.
        &lt;/div&gt;

    &lt;/div&gt;

    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/prism.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-sparql.min.js&quot;&gt;&lt;/script&gt;
    
    &lt;script&gt;
        function copyCode(button) {
            const codeBlock = button.parentElement.nextElementSibling.querySelector(&#39;code&#39;);
            const text = codeBlock.innerText;
            
            navigator.clipboard.writeText(text).then(() =&gt; {
                const successMessage = document.getElementById(&#39;copy-success&#39;);
                successMessage.style.display = &#39;block&#39;;
                setTimeout(() =&gt; {
                    successMessage.style.display = &#39;none&#39;;
                }, 2000);
            });
        }
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</content><link rel='replies' type='application/atom+xml' href='http://krishnapotluri.blogspot.com/feeds/7206692142987561123/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://krishnapotluri.blogspot.com/2023/01/sparql-property-paths-advanced-graph.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/7206692142987561123'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/7206692142987561123'/><link rel='alternate' type='text/html' href='http://krishnapotluri.blogspot.com/2023/01/sparql-property-paths-advanced-graph.html' title=''/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-162532840988979012.post-7846332025478764105</id><published>2022-12-31T15:59:00.000-08:00</published><updated>2024-12-31T16:13:44.171-08:00</updated><title type='text'></title><content type='html'>&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;title&gt;Mastering SPARQL: A Comprehensive Guide to Querying RDF Data&lt;/title&gt;
    &lt;link href=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/themes/prism-tomorrow.min.css&quot; rel=&quot;stylesheet&quot; /&gt;
    &lt;style&gt;
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #3498db;
            --accent-color: #e74c3c;
            --bg-color: #f5f5f5;
            --text-color: #333;
            --code-bg: #282c34;
        }

        body {
            font-family: &#39;Segoe UI&#39;, Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.8;
            color: var(--text-color);
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            background-color: var(--bg-color);
        }

        .container {
            background: white;
            padding: 40px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        h1, h2, h3 {
            color: var(--primary-color);
        }

        h1 {
            font-size: 2.5em;
            text-align: center;
            margin-bottom: 1em;
            padding-bottom: 0.5em;
            border-bottom: 3px solid var(--secondary-color);
        }

        .intro {
            font-size: 1.2em;
            color: #666;
            text-align: center;
            margin-bottom: 2em;
        }

        .code-container {
            position: relative;
            margin: 20px 0;
            background: var(--code-bg);
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .code-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 20px;
            background: var(--primary-color);
            color: white;
            border-radius: 8px 8px 0 0;
            font-size: 0.9em;
        }

        .copy-button {
            background: var(--secondary-color);
            color: white;
            border: none;
            padding: 5px 15px;
            border-radius: 4px;
            cursor: pointer;
            transition: background 0.3s;
        }

        .copy-button:hover {
            background: #2980b9;
        }

        pre {
            margin: 0;
            padding: 20px;
            overflow-x: auto;
        }

        code {
            font-family: &#39;Fira Code&#39;, monospace;
            font-size: 0.9em;
        }

        .note {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
            padding: 15px;
            margin: 20px 0;
            border-radius: 0 4px 4px 0;
        }

        .tip {
            background: #d4edda;
            border-left: 4px solid #28a745;
            padding: 15px;
            margin: 20px 0;
            border-radius: 0 4px 4px 0;
        }

        .example-output {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            margin: 10px 0;
            font-family: monospace;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }

        th, td {
            padding: 12px;
            border: 1px solid #ddd;
            text-align: left;
        }

        th {
            background-color: var(--primary-color);
            color: white;
        }

        tr:nth-child(even) {
            background-color: #f2f2f2;
        }

        .success-message {
            position: fixed;
            top: 20px;
            right: 20px;
            background: #2ecc71;
            color: white;
            padding: 10px 20px;
            border-radius: 4px;
            display: none;
            z-index: 1000;
        }

        @media (max-width: 768px) {
            .container {
                padding: 20px;
            }
            
            h1 {
                font-size: 2em;
            }
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div class=&quot;container&quot;&gt;
        &lt;h1&gt;Mastering SPARQL: A Comprehensive Guide to Querying RDF Data&lt;/h1&gt;
        
        &lt;p class=&quot;intro&quot;&gt;
            Learn how to effectively query RDF data using SPARQL, from basic queries to advanced federated searches.
        &lt;/p&gt;

        &lt;div id=&quot;copy-success&quot; class=&quot;success-message&quot;&gt;Code copied!&lt;/div&gt;

        &lt;h2&gt;📚 Introduction to SPARQL&lt;/h2&gt;
        &lt;p&gt;
            SPARQL (SPARQL Protocol and RDF Query Language) is the standard query language for RDF (Resource Description Framework) data.
            It allows you to query and manipulate data stored in RDF format across different data sources.
        &lt;/p&gt;

        &lt;h2&gt;🔍 Basic Queries&lt;/h2&gt;
        &lt;p&gt;Let&#39;s start with some basic SPARQL queries:&lt;/p&gt;

        &lt;h3&gt;Finding Capital Cities in Europe&lt;/h3&gt;
        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;Basic SELECT Query&lt;/span&gt;
                &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-sparql&quot;&gt;PREFIX rdf: &lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#&gt;
PREFIX dbo: &lt;http://dbpedia.org/ontology/&gt;

SELECT ?city ?country ?population
WHERE {
    ?city rdf:type dbo:City ;
          dbo:country ?country ;
          dbo:populationTotal ?population .
    ?country dbo:capital ?city ;
             dbo:continent dbr:Europe .
}
ORDER BY DESC(?population)
LIMIT 10&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;div class=&quot;note&quot;&gt;
            &lt;strong&gt;Key Points:&lt;/strong&gt;
            &lt;ul&gt;
                &lt;li&gt;PREFIX declarations define shortcuts for URIs&lt;/li&gt;
                &lt;li&gt;SELECT specifies which variables to include in results&lt;/li&gt;
                &lt;li&gt;WHERE clause defines the pattern to match&lt;/li&gt;
                &lt;li&gt;ORDER BY and LIMIT control result ordering and quantity&lt;/li&gt;
            &lt;/ul&gt;
        &lt;/div&gt;

        &lt;h2&gt;🔄 Advanced Queries&lt;/h2&gt;
        &lt;h3&gt;Using OPTIONAL and FILTER&lt;/h3&gt;
        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;Advanced Query Example&lt;/span&gt;
                &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-sparql&quot;&gt;SELECT ?scientist ?discovery ?year
WHERE {
    ?scientist rdf:type dbo:Scientist .
    OPTIONAL {
        ?discovery dbo:discoverer ?scientist ;
                  dbo:discoveryYear ?year .
    }
    FILTER(?year &gt; 1900)
}&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;div class=&quot;tip&quot;&gt;
            &lt;strong&gt;Pro Tip:&lt;/strong&gt; Use OPTIONAL when some data might be missing and you still want results for the main pattern.
        &lt;/div&gt;

        &lt;h2&gt;✏️ Update Operations&lt;/h2&gt;
        &lt;h3&gt;Inserting and Modifying Data&lt;/h3&gt;
        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;Update Query Example&lt;/span&gt;
                &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-sparql&quot;&gt;PREFIX ex: &lt;http://example.org/&gt;

INSERT DATA {
    ex:JohnDoe rdf:type ex:Person ;
               ex:name &quot;John Doe&quot; ;
               ex:age 30 .
}

DELETE {
    ex:JohnDoe ex:age ?oldAge .
}
INSERT {
    ex:JohnDoe ex:age 31 .
}
WHERE {
    ex:JohnDoe ex:age ?oldAge .
}&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;h2&gt;🌐 Federated Queries&lt;/h2&gt;
        &lt;p&gt;
            Federated queries allow you to query multiple SPARQL endpoints in a single query:
        &lt;/p&gt;
        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;Federated Query Example&lt;/span&gt;
                &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-sparql&quot;&gt;SELECT ?person ?dbpediaBirth ?wikidataBirth
WHERE {
    # DBpedia part
    ?person rdf:type dbo:Scientist ;
            dbo:birthDate ?dbpediaBirth .
    
    # Wikidata part
    SERVICE &lt;https://query.wikidata.org/sparql&gt; {
        ?wikidataPerson wdt:P31 wd:Q5 ;
                        wdt:P569 ?wikidataBirth .
    }
}&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;h2&gt;📊 Common SPARQL Patterns&lt;/h2&gt;
        &lt;table&gt;
            &lt;tr&gt;
                &lt;th&gt;Pattern&lt;/th&gt;
                &lt;th&gt;Use Case&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td&gt;FILTER&lt;/td&gt;
                &lt;td&gt;Restrict results based on conditions&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td&gt;OPTIONAL&lt;/td&gt;
                &lt;td&gt;Include optional patterns without failing the query&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td&gt;UNION&lt;/td&gt;
                &lt;td&gt;Combine results from alternative patterns&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td&gt;GROUP BY&lt;/td&gt;
                &lt;td&gt;Aggregate results based on variables&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td&gt;SERVICE&lt;/td&gt;
                &lt;td&gt;Query external SPARQL endpoints&lt;/td&gt;
            &lt;/tr&gt;
        &lt;/table&gt;

        &lt;h2&gt;🎯 Best Practices&lt;/h2&gt;
        &lt;div class=&quot;tip&quot;&gt;
            &lt;strong&gt;Follow these guidelines for better queries:&lt;/strong&gt;
            &lt;ul&gt;
                &lt;li&gt;Always use appropriate PREFIX declarations&lt;/li&gt;
                &lt;li&gt;Start with specific patterns and add OPTIONAL patterns later&lt;/li&gt;
                &lt;li&gt;Use LIMIT and OFFSET for pagination&lt;/li&gt;
                &lt;li&gt;Include FILTER clauses as early as possible&lt;/li&gt;
                &lt;li&gt;Use named graphs for better data organization&lt;/li&gt;
            &lt;/ul&gt;
        &lt;/div&gt;

      

    &lt;/div&gt;

    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/prism.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-sparql.min.js&quot;&gt;&lt;/script&gt;
    
    &lt;script&gt;
        function copyCode(button) {
            const codeBlock = button.parentElement.nextElementSibling.querySelector(&#39;code&#39;);
            const text = codeBlock.innerText;
            
            navigator.clipboard.writeText(text).then(() =&gt; {
                const successMessage = document.getElementById(&#39;copy-success&#39;);
                successMessage.style.display = &#39;block&#39;;
                setTimeout(() =&gt; {
                    successMessage.style.display = &#39;none&#39;;
                }, 2000);
            });
        }
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</content><link rel='replies' type='application/atom+xml' href='http://krishnapotluri.blogspot.com/feeds/7846332025478764105/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://krishnapotluri.blogspot.com/2022/12/mastering-sparql-comprehensive-guide-to.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/7846332025478764105'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/7846332025478764105'/><link rel='alternate' type='text/html' href='http://krishnapotluri.blogspot.com/2022/12/mastering-sparql-comprehensive-guide-to.html' title=''/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-162532840988979012.post-5586755770691760863</id><published>2020-12-31T15:55:00.000-08:00</published><updated>2024-12-31T16:14:00.192-08:00</updated><title type='text'>graphql</title><content type='html'>&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;title&gt;Building a Scalable GraphQL API with Apollo Server and DataLoader&lt;/title&gt;
    &lt;link href=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/themes/prism-tomorrow.min.css&quot; rel=&quot;stylesheet&quot; /&gt;
    &lt;style&gt;
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #3498db;
            --accent-color: #e74c3c;
            --text-color: #333;
            --light-bg: #f5f5f5;
            --code-bg: #282c34;
        }

        body {
            font-family: &#39;Segoe UI&#39;, Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.8;
            color: var(--text-color);
            max-width: 900px;
            margin: 0 auto;
            padding: 20px;
            background-color: var(--light-bg);
        }

        .container {
            background: white;
            padding: 40px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        h1, h2, h3 {
            color: var(--primary-color);
            margin-top: 2em;
        }

        h1 {
            font-size: 2.5em;
            text-align: center;
            margin-bottom: 1em;
            border-bottom: 3px solid var(--secondary-color);
            padding-bottom: 0.5em;
        }

        .intro {
            font-size: 1.2em;
            color: #666;
            text-align: center;
            margin-bottom: 2em;
        }

        .code-container {
            position: relative;
            margin: 20px 0;
            background: var(--code-bg);
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .code-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 20px;
            background: var(--primary-color);
            color: white;
            border-radius: 8px 8px 0 0;
            font-size: 0.9em;
        }

        .copy-button {
            background: var(--secondary-color);
            color: white;
            border: none;
            padding: 5px 15px;
            border-radius: 4px;
            cursor: pointer;
            transition: background 0.3s;
        }

        .copy-button:hover {
            background: #2980b9;
        }

        pre {
            margin: 0;
            padding: 20px;
            border-radius: 0 0 8px 8px;
            overflow-x: auto;
        }

        code {
            font-family: &#39;Fira Code&#39;, monospace;
            font-size: 0.9em;
        }

        .success-message {
            position: fixed;
            top: 20px;
            right: 20px;
            background: #2ecc71;
            color: white;
            padding: 10px 20px;
            border-radius: 4px;
            display: none;
            z-index: 1000;
        }

        .note {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
            padding: 15px;
            margin: 20px 0;
            border-radius: 0 4px 4px 0;
        }

        .tip {
            background: #d4edda;
            border-left: 4px solid #28a745;
            padding: 15px;
            margin: 20px 0;
            border-radius: 0 4px 4px 0;
        }

        .warning {
            background: #f8d7da;
            border-left: 4px solid #dc3545;
            padding: 15px;
            margin: 20px 0;
            border-radius: 0 4px 4px 0;
        }

        .diagram {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
            text-align: center;
        }

        .diagram img {
            max-width: 100%;
            height: auto;
        }

        @media (max-width: 768px) {
            body {
                padding: 10px;
            }

            .container {
                padding: 20px;
            }

            h1 {
                font-size: 2em;
            }
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div class=&quot;container&quot;&gt;
        &lt;h1&gt;Building a Scalable GraphQL API with Apollo Server and DataLoader&lt;/h1&gt;
        
        &lt;p class=&quot;intro&quot;&gt;
            Learn how to build an efficient GraphQL API using Apollo Server and DataLoader. 
            We&#39;ll create a blog-like system with users, posts, and comments while avoiding the N+1 query problem.
        &lt;/p&gt;

        &lt;div id=&quot;copy-success&quot; class=&quot;success-message&quot;&gt;Code copied!&lt;/div&gt;

        &lt;h2&gt;🎯 What We&#39;re Building&lt;/h2&gt;
        &lt;p&gt;
            We&#39;ll create a GraphQL API that handles relationships between:
        &lt;/p&gt;
        &lt;ul&gt;
            &lt;li&gt;Users who write posts and comments&lt;/li&gt;
            &lt;li&gt;Posts that belong to users and have comments&lt;/li&gt;
            &lt;li&gt;Comments that belong to posts and users&lt;/li&gt;
        &lt;/ul&gt;

        &lt;div class=&quot;diagram&quot;&gt;
            &lt;pre&gt;
User ──┬── Posts
       └── Comments ── Posts
            &lt;/pre&gt;
        &lt;/div&gt;

        &lt;h2&gt;🚀 Getting Started&lt;/h2&gt;
        &lt;p&gt;First, let&#39;s set up our project with the necessary dependencies:&lt;/p&gt;

        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;package.json&lt;/span&gt;
                &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-json&quot;&gt;{
  &quot;name&quot;: &quot;graphql-apollo-tutorial&quot;,
  &quot;version&quot;: &quot;1.0.0&quot;,
  &quot;type&quot;: &quot;module&quot;,
  &quot;dependencies&quot;: {
    &quot;@apollo/server&quot;: &quot;^4.9.5&quot;,
    &quot;dataloader&quot;: &quot;^2.2.2&quot;,
    &quot;graphql&quot;: &quot;^16.8.1&quot;
  }
}&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;h2&gt;📦 Setting Up DataLoaders&lt;/h2&gt;
        &lt;p&gt;
            DataLoader is a key tool for solving the N+1 query problem in GraphQL. It batches and caches database lookups:
        &lt;/p&gt;

        &lt;div class=&quot;tip&quot;&gt;
            &lt;strong&gt;What is the N+1 Problem?&lt;/strong&gt;&lt;br&gt;
            When fetching a list of items and their relations, you might end up making one query for the list and N additional queries for each item&#39;s relations.
        &lt;/div&gt;

        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;dataloaders/index.js&lt;/span&gt;
                &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;import DataLoader from &#39;dataloader&#39;;

export const createLoaders = () =&gt; ({
  userLoader: new DataLoader(async (userIds) =&gt; {
    console.log(&#39;Batch loading users:&#39;, userIds);
    return userIds.map(id =&gt; users.find(user =&gt; user.id === id));
  }),

  userPostsLoader: new DataLoader(async (userIds) =&gt; {
    console.log(&#39;Batch loading posts for users:&#39;, userIds);
    const postsByUser = groupBy(posts, post =&gt; post.userId);
    return userIds.map(userId =&gt; postsByUser[userId] || []);
  }),

  postCommentsLoader: new DataLoader(async (postIds) =&gt; {
    console.log(&#39;Batch loading comments for posts:&#39;, postIds);
    const commentsByPost = groupBy(comments, comment =&gt; comment.postId);
    return postIds.map(postId =&gt; commentsByPost[postId] || []);
  })
});&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;h2&gt;📝 Defining the Schema&lt;/h2&gt;
        &lt;p&gt;
            Our GraphQL schema defines the types and their relationships:
        &lt;/p&gt;

        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;schema.js&lt;/span&gt;
                &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-graphql&quot;&gt;type User {
  id: ID!
  name: String!
  email: String!
  posts: [Post!]!
}

type Post {
  id: ID!
  title: String!
  content: String!
  author: User!
  comments: [Comment!]!
}

type Comment {
  id: ID!
  text: String!
  post: Post!
  author: User!
}&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;h2&gt;🔧 Implementing Resolvers&lt;/h2&gt;
        &lt;p&gt;
            Resolvers define how to fetch the data for each field:
        &lt;/p&gt;

        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;resolvers.js&lt;/span&gt;
                &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-javascript&quot;&gt;export const resolvers = {
  Query: {
    user: (_, { id }, { loaders }) =&gt; {
      return loaders.userLoader.load(id);
    },
    posts: (_, __, { posts }) =&gt; posts,
  },

  User: {
    posts: (parent, _, { loaders }) =&gt; {
      return loaders.userPostsLoader.load(parent.id);
    },
  },

  Post: {
    author: (parent, _, { loaders }) =&gt; {
      return loaders.userLoader.load(parent.userId);
    },
    comments: (parent, _, { loaders }) =&gt; {
      return loaders.postCommentsLoader.load(parent.id);
    },
  }
};&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;h2&gt;🌟 Example Queries&lt;/h2&gt;
        &lt;p&gt;Here&#39;s how to query our API:&lt;/p&gt;

        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;Query Example&lt;/span&gt;
                &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-graphql&quot;&gt;query {
  user(id: &quot;1&quot;) {
    name
    email
    posts {
      title
      content
      comments {
        text
        author {
          name
        }
      }
    }
  }
}&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;h2&gt;🎉 Benefits of This Approach&lt;/h2&gt;
        &lt;ul&gt;
            &lt;li&gt;Efficient data loading with DataLoader&#39;s batching and caching&lt;/li&gt;
            &lt;li&gt;Clean separation of concerns between schema and resolvers&lt;/li&gt;
            &lt;li&gt;Type-safe API with GraphQL&#39;s type system&lt;/li&gt;
            &lt;li&gt;Flexible querying capabilities for clients&lt;/li&gt;
        &lt;/ul&gt;

        &lt;div class=&quot;warning&quot;&gt;
            &lt;strong&gt;Important Note:&lt;/strong&gt;&lt;br&gt;
            Remember to create new DataLoader instances for each request to prevent data leaks between different users&#39; requests.
        &lt;/div&gt;

        &lt;h2&gt;🔍 Performance Monitoring&lt;/h2&gt;
        &lt;p&gt;
            You can monitor DataLoader&#39;s effectiveness by looking at the console logs. You should see multiple IDs being loaded in single batches instead of individual queries.
        &lt;/p&gt;

        &lt;div class=&quot;tip&quot;&gt;
            &lt;strong&gt;Pro Tip:&lt;/strong&gt;&lt;br&gt;
            Use the Apollo Studio Explorer (available at http://localhost:4000) to test your queries and see the exact data being requested and returned.
        &lt;/div&gt;

      

    &lt;/div&gt;

    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/prism.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-javascript.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-json.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-graphql.min.js&quot;&gt;&lt;/script&gt;
    
    &lt;script&gt;
        function copyCode(button) {
            const codeBlock = button.parentElement.nextElementSibling.querySelector(&#39;code&#39;);
            const text = codeBlock.innerText;
            
            navigator.clipboard.writeText(text).then(() =&gt; {
                const successMessage = document.getElementById(&#39;copy-success&#39;);
                successMessage.style.display = &#39;block&#39;;
                setTimeout(() =&gt; {
                    successMessage.style.display = &#39;none&#39;;
                }, 2000);
            });
        }
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</content><link rel='replies' type='application/atom+xml' href='http://krishnapotluri.blogspot.com/feeds/5586755770691760863/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://krishnapotluri.blogspot.com/2020/12/graphql.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/5586755770691760863'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/5586755770691760863'/><link rel='alternate' type='text/html' href='http://krishnapotluri.blogspot.com/2020/12/graphql.html' title='graphql'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-162532840988979012.post-5490282626941944882</id><published>2020-10-05T16:06:00.000-07:00</published><updated>2024-12-31T16:14:16.112-08:00</updated><title type='text'></title><content type='html'>&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;title&gt;Spring Batch Tutorial: Processing Records with Scheduled Jobs&lt;/title&gt;
    &lt;link href=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/themes/prism-tomorrow.min.css&quot; rel=&quot;stylesheet&quot; /&gt;
    &lt;style&gt;
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #3498db;
            --accent-color: #e74c3c;
            --bg-color: #f5f5f5;
            --text-color: #333;
            --code-bg: #282c34;
        }

        body {
            font-family: &#39;Segoe UI&#39;, Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.8;
            color: var(--text-color);
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            background-color: var(--bg-color);
        }

        .container {
            background: white;
            padding: 40px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        h1, h2, h3 {
            color: var(--primary-color);
        }

        h1 {
            font-size: 2.5em;
            text-align: center;
            margin-bottom: 1em;
            padding-bottom: 0.5em;
            border-bottom: 3px solid var(--secondary-color);
        }

        .intro {
            font-size: 1.2em;
            color: #666;
            text-align: center;
            margin-bottom: 2em;
        }

        .code-container {
            position: relative;
            margin: 20px 0;
            background: var(--code-bg);
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .code-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 20px;
            background: var(--primary-color);
            color: white;
            border-radius: 8px 8px 0 0;
        }

        .copy-button {
            background: var(--secondary-color);
            color: white;
            border: none;
            padding: 5px 15px;
            border-radius: 4px;
            cursor: pointer;
            transition: background 0.3s;
        }

        pre {
            margin: 0;
            padding: 20px;
            overflow-x: auto;
        }

        code {
            font-family: &#39;Fira Code&#39;, monospace;
            font-size: 0.9em;
        }

        .note {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
            padding: 15px;
            margin: 20px 0;
            border-radius: 0 4px 4px 0;
        }

        .tip {
            background: #d4edda;
            border-left: 4px solid #28a745;
            padding: 15px;
            margin: 20px 0;
            border-radius: 0 4px 4px 0;
        }

        .success-message {
            position: fixed;
            top: 20px;
            right: 20px;
            background: #2ecc71;
            color: white;
            padding: 10px 20px;
            border-radius: 4px;
            display: none;
            z-index: 1000;
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div class=&quot;container&quot;&gt;
        &lt;h1&gt;Spring Batch Tutorial: Processing Records with Scheduled Jobs&lt;/h1&gt;
        
        &lt;p class=&quot;intro&quot;&gt;
            Learn how to implement a Spring Batch application that processes records every 5 minutes using an in-memory H2 database.
        &lt;/p&gt;

        &lt;div id=&quot;copy-success&quot; class=&quot;success-message&quot;&gt;Code copied!&lt;/div&gt;

        &lt;h2&gt;🎯 Project Overview&lt;/h2&gt;
        &lt;p&gt;
            In this tutorial, we&#39;ll build a Spring Batch application that:
        &lt;/p&gt;
        &lt;ul&gt;
            &lt;li&gt;Uses an in-memory H2 database for storing transactions&lt;/li&gt;
            &lt;li&gt;Processes pending transactions every 5 minutes&lt;/li&gt;
            &lt;li&gt;Implements a complete batch processing pipeline&lt;/li&gt;
            &lt;li&gt;Generates sample data for testing&lt;/li&gt;
        &lt;/ul&gt;

        &lt;h2&gt;🛠️ Project Setup&lt;/h2&gt;
        &lt;p&gt;First, let&#39;s set up our project with the required dependencies in &lt;code&gt;pom.xml&lt;/code&gt;:&lt;/p&gt;
        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;pom.xml&lt;/span&gt;
                &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-xml&quot;&gt;&amp;lt;dependencies&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;spring-boot-starter-batch&amp;lt;/artifactId&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;spring-boot-starter-data-jpa&amp;lt;/artifactId&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;com.h2database&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;h2&amp;lt;/artifactId&amp;gt;
        &amp;lt;scope&amp;gt;runtime&amp;lt;/scope&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.projectlombok&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;lombok&amp;lt;/artifactId&amp;gt;
        &amp;lt;optional&amp;gt;true&amp;lt;/optional&amp;gt;
    &amp;lt;/dependency&amp;gt;
&amp;lt;/dependencies&amp;gt;&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;h2&gt;📦 Domain Model&lt;/h2&gt;
        &lt;p&gt;We&#39;ll create a simple Transaction entity to represent our data:&lt;/p&gt;
        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;Transaction.java&lt;/span&gt;
                &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;@Entity
@Data
@NoArgsConstructor
public class Transaction {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String accountId;
    private BigDecimal amount;
    private String type;
    private LocalDateTime timestamp;
    private String status;
}&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;h2&gt;⚙️ Batch Configuration&lt;/h2&gt;
        &lt;p&gt;The batch job configuration is the heart of our application:&lt;/p&gt;
        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;BatchConfig.java&lt;/span&gt;
                &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;@Configuration
@EnableBatchProcessing
@RequiredArgsConstructor
public class BatchConfig {
    @Bean
    public ItemReader&lt;Transaction&gt; reader() {
        RepositoryItemReader&lt;Transaction&gt; reader = new RepositoryItemReader&lt;&gt;();
        reader.setRepository(transactionRepository);
        reader.setMethodName(&quot;findByStatus&quot;);
        reader.setArguments(java.util.Arrays.asList(&quot;PENDING&quot;));
        return reader;
    }

    @Bean
    public ItemProcessor&lt;Transaction, Transaction&gt; processor() {
        return transaction -&gt; {
            transaction.setStatus(&quot;PROCESSED&quot;);
            return transaction;
        };
    }

    @Bean
    public Job processTransactionsJob() {
        return jobBuilderFactory.get(&quot;processTransactionsJob&quot;)
                .incrementer(new RunIdIncrementer())
                .flow(processTransactionsStep())
                .end()
                .build();
    }
}&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;h2&gt;⏰ Job Scheduler&lt;/h2&gt;
        &lt;p&gt;The scheduler runs our batch job every 5 minutes:&lt;/p&gt;
        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;BatchJobScheduler.java&lt;/span&gt;
                &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;@Component
@EnableScheduling
@RequiredArgsConstructor
@Slf4j
public class BatchJobScheduler {
    @Scheduled(fixedRate = 300000) // Run every 5 minutes
    public void runBatchJob() {
        JobParameters jobParameters = new JobParametersBuilder()
                .addLong(&quot;time&quot;, System.currentTimeMillis())
                .toJobParameters();
        
        jobLauncher.run(processTransactionsJob, jobParameters);
    }
}&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;h2&gt;🔄 Sample Data Generation&lt;/h2&gt;
        &lt;p&gt;We generate sample transactions on application startup:&lt;/p&gt;
        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;TransactionService.java&lt;/span&gt;
                &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;@Service
@RequiredArgsConstructor
public class TransactionService {
    public void generateSampleTransactions() {
        for (int i = 0; i &lt; 50; i++) {
            Transaction transaction = new Transaction();
            transaction.setAccountId(UUID.randomUUID().toString());
            transaction.setAmount(BigDecimal.valueOf(Math.random() * 1000));
            transaction.setType(Math.random() &gt; 0.5 ? &quot;CREDIT&quot; : &quot;DEBIT&quot;);
            transaction.setTimestamp(LocalDateTime.now());
            transaction.setStatus(&quot;PENDING&quot;);
            
            transactionRepository.save(transaction);
        }
    }
}&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;h2&gt;💡 Key Features&lt;/h2&gt;
        &lt;div class=&quot;tip&quot;&gt;
            &lt;strong&gt;This implementation includes:&lt;/strong&gt;
            &lt;ul&gt;
                &lt;li&gt;Chunk-based processing (10 items per chunk)&lt;/li&gt;
                &lt;li&gt;Automatic job parameter incrementation&lt;/li&gt;
                &lt;li&gt;Error handling and logging&lt;/li&gt;
                &lt;li&gt;Scheduled execution every 5 minutes&lt;/li&gt;
                &lt;li&gt;In-memory H2 database for easy testing&lt;/li&gt;
            &lt;/ul&gt;
        &lt;/div&gt;

        &lt;h2&gt;🚀 Running the Application&lt;/h2&gt;
        &lt;ol&gt;
            &lt;li&gt;Clone the repository&lt;/li&gt;
            &lt;li&gt;Run &lt;code&gt;mvn clean install&lt;/code&gt;&lt;/li&gt;
            &lt;li&gt;Start the application&lt;/li&gt;
            &lt;li&gt;Access H2 console at &lt;code&gt;http://localhost:8080/h2-console&lt;/code&gt;&lt;/li&gt;
            &lt;li&gt;Watch the logs for batch job execution every 5 minutes&lt;/li&gt;
        &lt;/ol&gt;

        &lt;div class=&quot;note&quot;&gt;
            &lt;strong&gt;Note:&lt;/strong&gt; The H2 database is in-memory, so data will be reset when the application restarts.
        &lt;/div&gt;

        &lt;h2&gt;🔍 Monitoring&lt;/h2&gt;
        &lt;p&gt;You can monitor the batch jobs through:&lt;/p&gt;
        &lt;ul&gt;
            &lt;li&gt;Application logs&lt;/li&gt;
            &lt;li&gt;H2 console for database inspection&lt;/li&gt;
            &lt;li&gt;Spring Batch tables (BATCH_JOB_EXECUTION, BATCH_STEP_EXECUTION)&lt;/li&gt;
        &lt;/ul&gt;

       
    &lt;/div&gt;

    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/prism.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-java.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-xml.min.js&quot;&gt;&lt;/script&gt;
    
    &lt;script&gt;
        function copyCode(button) {
            const codeBlock = button.parentElement.nextElementSibling.querySelector(&#39;code&#39;);
            const text = codeBlock.innerText;
            
            navigator.clipboard.writeText(text).then(() =&gt; {
                const successMessage = document.getElementById(&#39;copy-success&#39;);
                successMessage.style.display = &#39;block&#39;;
                setTimeout(() =&gt; {
                    successMessage.style.display = &#39;none&#39;;
                }, 2000);
            });
        }
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</content><link rel='replies' type='application/atom+xml' href='http://krishnapotluri.blogspot.com/feeds/5490282626941944882/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://krishnapotluri.blogspot.com/2020/10/spring-batch-tutorial-processing.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/5490282626941944882'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/5490282626941944882'/><link rel='alternate' type='text/html' href='http://krishnapotluri.blogspot.com/2020/10/spring-batch-tutorial-processing.html' title=''/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-162532840988979012.post-497449295355520862</id><published>2018-12-31T15:48:00.000-08:00</published><updated>2024-12-31T15:49:15.452-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Kafka"/><title type='text'>Kafka</title><content type='html'>&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;title&gt;Apache Kafka Tutorial - Java and Spark Integration&lt;/title&gt;
    &lt;link href=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/themes/prism-tomorrow.min.css&quot; rel=&quot;stylesheet&quot; /&gt;
    &lt;style&gt;
        body {
            font-family: &#39;Segoe UI&#39;, Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        
        h1, h2, h3 {
            color: #2c3e50;
        }
        
        .code-container {
            position: relative;
            margin: 20px 0;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .code-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 20px;
            background: #2c3e50;
            color: white;
            border-radius: 8px 8px 0 0;
        }
        
        .copy-button {
            background: #3498db;
            color: white;
            border: none;
            padding: 5px 15px;
            border-radius: 4px;
            cursor: pointer;
            transition: background 0.3s;
        }
        
        .copy-button:hover {
            background: #2980b9;
        }
        
        pre {
            margin: 0;
            padding: 20px;
            border-radius: 0 0 8px 8px;
            overflow-x: auto;
        }
        
        code {
            font-family: &#39;Fira Code&#39;, monospace;
        }
        
        .success-message {
            position: fixed;
            top: 20px;
            right: 20px;
            background: #2ecc71;
            color: white;
            padding: 10px 20px;
            border-radius: 4px;
            display: none;
        }

        .note {
            background: #f1c40f;
            padding: 15px;
            border-radius: 4px;
            margin: 20px 0;
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1&gt;Apache Kafka Tutorial - Java and Spark Integration&lt;/h1&gt;
    &lt;p&gt;This tutorial demonstrates how to work with Apache Kafka using both Java and Apache Spark, including producer and consumer implementations with auto offset management.&lt;/p&gt;

    &lt;div id=&quot;copy-success&quot; class=&quot;success-message&quot;&gt;Code copied!&lt;/div&gt;

    &lt;h2&gt;1. Java Implementation&lt;/h2&gt;
    
    &lt;h3&gt;1.1 Kafka Producer in Java&lt;/h3&gt;
    &lt;div class=&quot;note&quot;&gt;
        This implementation includes idempotence and safe producer configurations for reliable message delivery.
    &lt;/div&gt;
    &lt;div class=&quot;code-container&quot;&gt;
        &lt;div class=&quot;code-header&quot;&gt;
            &lt;span&gt;KafkaProducerExample.java&lt;/span&gt;
            &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
        &lt;/div&gt;
        &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;
import java.util.Properties;
import java.util.concurrent.ExecutionException;

public class KafkaProducerExample {
    private static final String TOPIC_NAME = &quot;example-topic&quot;;
    private static final String BOOTSTRAP_SERVERS = &quot;localhost:9092&quot;;

    public static void main(String[] args) {
        // Create producer properties
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS);
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        
        // Create safe producer configs
        properties.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, &quot;true&quot;);
        properties.put(ProducerConfig.ACKS_CONFIG, &quot;all&quot;);
        properties.put(ProducerConfig.RETRIES_CONFIG, Integer.toString(Integer.MAX_VALUE));
        properties.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, &quot;5&quot;);

        // Create the producer
        try (KafkaProducer&lt;String, String&gt; producer = new KafkaProducer&lt;&gt;(properties)) {
            
            // Send messages with callbacks
            for (int i = 0; i &lt; 10; i++) {
                String key = &quot;key_&quot; + i;
                String value = &quot;message_&quot; + i;
                
                ProducerRecord&lt;String, String&gt; record = 
                    new ProducerRecord&lt;&gt;(TOPIC_NAME, key, value);

                producer.send(record, (metadata, exception) -&gt; {
                    if (exception == null) {
                        System.out.printf(&quot;Message sent successfully! Topic: %s, Partition: %d, Offset: %d%n&quot;,
                            metadata.topic(), metadata.partition(), metadata.offset());
                    } else {
                        System.err.println(&quot;Error sending message: &quot; + exception.getMessage());
                    }
                });
            }
            
            // Flush and close producer
            producer.flush();
        }
    }
}&lt;/code&gt;&lt;/pre&gt;
    &lt;/div&gt;

    &lt;h3&gt;1.2 Kafka Consumer in Java&lt;/h3&gt;
    &lt;div class=&quot;note&quot;&gt;
        This consumer implementation includes auto offset commit and earliest offset reset configuration.
    &lt;/div&gt;
    &lt;div class=&quot;code-container&quot;&gt;
        &lt;div class=&quot;code-header&quot;&gt;
            &lt;span&gt;KafkaConsumerExample.java&lt;/span&gt;
            &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
        &lt;/div&gt;
        &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.serialization.StringDeserializer;
import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

public class KafkaConsumerExample {
    private static final String TOPIC_NAME = &quot;example-topic&quot;;
    private static final String BOOTSTRAP_SERVERS = &quot;localhost:9092&quot;;
    private static final String GROUP_ID = &quot;my-consumer-group&quot;;

    public static void main(String[] args) {
        // Create consumer properties
        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS);
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, GROUP_ID);
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        
        // Auto offset reset config
        properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, &quot;earliest&quot;);
        
        // Enable auto commit
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, &quot;true&quot;);
        properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, &quot;1000&quot;);

        // Create the consumer
        try (KafkaConsumer&lt;String, String&gt; consumer = new KafkaConsumer&lt;&gt;(properties)) {
            // Subscribe to topic
            consumer.subscribe(Collections.singletonList(TOPIC_NAME));

            // Poll for messages
            while (true) {
                ConsumerRecords&lt;String, String&gt; records = consumer.poll(Duration.ofMillis(100));
                
                for (ConsumerRecord&lt;String, String&gt; record : records) {
                    System.out.printf(&quot;Received message: key = %s, value = %s, topic = %s, partition = %d, offset = %d%n&quot;,
                        record.key(), record.value(), record.topic(), record.partition(), record.offset());
                }
            }
        }
    }
}&lt;/code&gt;&lt;/pre&gt;
    &lt;/div&gt;

    &lt;h2&gt;2. Spark Implementation&lt;/h2&gt;
    
    &lt;h3&gt;2.1 Spark Kafka Producer&lt;/h3&gt;
    &lt;div class=&quot;note&quot;&gt;
        This Spark implementation demonstrates how to write data to Kafka using Spark&#39;s DataFrame API.
    &lt;/div&gt;
    &lt;div class=&quot;code-container&quot;&gt;
        &lt;div class=&quot;code-header&quot;&gt;
            &lt;span&gt;SparkKafkaProducer.scala&lt;/span&gt;
            &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
        &lt;/div&gt;
        &lt;pre&gt;&lt;code class=&quot;language-scala&quot;&gt;import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._

object SparkKafkaProducer {
  def main(args: Array[String]): Unit = {
    // Create Spark Session
    val spark = SparkSession.builder()
      .appName(&quot;Spark Kafka Producer&quot;)
      .master(&quot;local[*]&quot;)
      .getOrCreate()

    import spark.implicits._

    // Create sample data
    val data = (1 to 100).map(i =&gt; (s&quot;key_$i&quot;, s&quot;message_$i&quot;))
      .toDF(&quot;key&quot;, &quot;value&quot;)

    // Write to Kafka
    data.selectExpr(&quot;key&quot;, &quot;value&quot;)
      .write
      .format(&quot;kafka&quot;)
      .option(&quot;kafka.bootstrap.servers&quot;, &quot;localhost:9092&quot;)
      .option(&quot;topic&quot;, &quot;spark-topic&quot;)
      .save()

    spark.stop()
  }
}&lt;/code&gt;&lt;/pre&gt;
    &lt;/div&gt;

    &lt;h3&gt;2.2 Spark Kafka Consumer&lt;/h3&gt;
    &lt;div class=&quot;note&quot;&gt;
        This implementation uses Spark Structured Streaming to consume messages from Kafka with auto offset management.
    &lt;/div&gt;
    &lt;div class=&quot;code-container&quot;&gt;
        &lt;div class=&quot;code-header&quot;&gt;
            &lt;span&gt;SparkKafkaConsumer.scala&lt;/span&gt;
            &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
        &lt;/div&gt;
        &lt;pre&gt;&lt;code class=&quot;language-scala&quot;&gt;import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.streaming.Trigger
import org.apache.spark.sql.functions._

object SparkKafkaConsumer {
  def main(args: Array[String]): Unit = {
    // Create Spark Session
    val spark = SparkSession.builder()
      .appName(&quot;Spark Kafka Consumer&quot;)
      .master(&quot;local[*]&quot;)
      .getOrCreate()

    import spark.implicits._

    // Read from Kafka
    val df = spark.readStream
      .format(&quot;kafka&quot;)
      .option(&quot;kafka.bootstrap.servers&quot;, &quot;localhost:9092&quot;)
      .option(&quot;subscribe&quot;, &quot;spark-topic&quot;)
      .option(&quot;startingOffsets&quot;, &quot;earliest&quot;) // Auto offset reset config
      .load()

    // Process the stream
    val query = df.selectExpr(&quot;CAST(key AS STRING)&quot;, &quot;CAST(value AS STRING)&quot;)
      .writeStream
      .outputMode(&quot;append&quot;)
      .format(&quot;console&quot;)
      .option(&quot;truncate&quot;, &quot;false&quot;)
      .trigger(Trigger.ProcessingTime(&quot;1 second&quot;))
      .start()

    query.awaitTermination()
  }
}&lt;/code&gt;&lt;/pre&gt;
    &lt;/div&gt;

    &lt;h2&gt;Dependencies&lt;/h2&gt;
    &lt;div class=&quot;note&quot;&gt;
        &lt;h4&gt;For Java Implementation:&lt;/h4&gt;
        &lt;pre&gt;&lt;code class=&quot;language-xml&quot;&gt;&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;org.apache.kafka&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;kafka-clients&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;3.1.0&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;&lt;/code&gt;&lt;/pre&gt;

        &lt;h4&gt;For Spark Implementation:&lt;/h4&gt;
        &lt;pre&gt;&lt;code class=&quot;language-xml&quot;&gt;&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;org.apache.spark&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;spark-sql-kafka-0-10_2.12&amp;lt;/artifactId&amp;gt;
    &amp;lt;version&amp;gt;3.1.2&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;&lt;/code&gt;&lt;/pre&gt;
    &lt;/div&gt;

    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/prism.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-java.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-scala.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-xml.min.js&quot;&gt;&lt;/script&gt;
    
    &lt;script&gt;
        function copyCode(button) {
            const codeBlock = button.parentElement.nextElementSibling.querySelector(&#39;code&#39;);
            const text = codeBlock.innerText;
            
            navigator.clipboard.writeText(text).then(() =&gt; {
                const successMessage = document.getElementById(&#39;copy-success&#39;);
                successMessage.style.display = &#39;block&#39;;
                setTimeout(() =&gt; {
                    successMessage.style.display = &#39;none&#39;;
                }, 2000);
            });
        }
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</content><link rel='replies' type='application/atom+xml' href='http://krishnapotluri.blogspot.com/feeds/497449295355520862/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://krishnapotluri.blogspot.com/2024/12/kafka.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/497449295355520862'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/497449295355520862'/><link rel='alternate' type='text/html' href='http://krishnapotluri.blogspot.com/2024/12/kafka.html' title='Kafka'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-162532840988979012.post-2567286694263906404</id><published>2018-06-20T06:30:00.000-07:00</published><updated>2024-12-31T16:12:58.832-08:00</updated><title type='text'></title><content type='html'>&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;title&gt;Building a RESTful API with Spring Boot and H2 Database&lt;/title&gt;
    &lt;link href=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/themes/prism-tomorrow.min.css&quot; rel=&quot;stylesheet&quot; /&gt;
    &lt;style&gt;
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #3498db;
            --accent-color: #e74c3c;
            --bg-color: #f5f5f5;
            --text-color: #333;
            --code-bg: #282c34;
        }

        body {
            font-family: &#39;Segoe UI&#39;, Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.8;
            color: var(--text-color);
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            background-color: var(--bg-color);
        }

        .container {
            background: white;
            padding: 40px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        h1, h2, h3 {
            color: var(--primary-color);
        }

        h1 {
            font-size: 2.5em;
            text-align: center;
            margin-bottom: 1em;
            padding-bottom: 0.5em;
            border-bottom: 3px solid var(--secondary-color);
        }

        .intro {
            font-size: 1.2em;
            color: #666;
            text-align: center;
            margin-bottom: 2em;
        }

        .code-container {
            position: relative;
            margin: 20px 0;
            background: var(--code-bg);
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .code-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 20px;
            background: var(--primary-color);
            color: white;
            border-radius: 8px 8px 0 0;
        }

        pre {
            margin: 0;
            padding: 20px;
            overflow-x: auto;
        }

        code {
            font-family: &#39;Fira Code&#39;, monospace;
            font-size: 0.9em;
        }

        .note {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
            padding: 15px;
            margin: 20px 0;
            border-radius: 0 4px 4px 0;
        }

        .tip {
            background: #d4edda;
            border-left: 4px solid #28a745;
            padding: 15px;
            margin: 20px 0;
            border-radius: 0 4px 4px 0;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }

        th, td {
            padding: 12px;
            border: 1px solid #ddd;
            text-align: left;
        }

        th {
            background-color: var(--primary-color);
            color: white;
        }

        .endpoint {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 4px;
            font-family: monospace;
            color: var(--accent-color);
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div class=&quot;container&quot;&gt;
        &lt;h1&gt;Building a RESTful API with Spring Boot and H2 Database&lt;/h1&gt;
        
        &lt;p class=&quot;intro&quot;&gt;
            Learn how to create a production-ready REST API using Spring Boot, JPA, and H2 Database
            with complete CRUD operations and proper error handling.
        &lt;/p&gt;

        &lt;h2&gt;🎯 Project Overview&lt;/h2&gt;
        &lt;p&gt;
            We&#39;ll build a Customer Management API that includes:
        &lt;/p&gt;
        &lt;ul&gt;
            &lt;li&gt;CRUD operations for customer data&lt;/li&gt;
            &lt;li&gt;Input validation&lt;/li&gt;
            &lt;li&gt;Exception handling&lt;/li&gt;
            &lt;li&gt;Swagger/OpenAPI documentation&lt;/li&gt;
            &lt;li&gt;In-memory H2 database&lt;/li&gt;
            &lt;li&gt;Sample data generation&lt;/li&gt;
        &lt;/ul&gt;

        &lt;h2&gt;🛠️ Project Setup&lt;/h2&gt;
        &lt;p&gt;First, let&#39;s set up our project with the required dependencies in &lt;code&gt;pom.xml&lt;/code&gt;:&lt;/p&gt;
        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;pom.xml&lt;/span&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-xml&quot;&gt;&amp;lt;dependencies&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;spring-boot-starter-web&amp;lt;/artifactId&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;spring-boot-starter-data-jpa&amp;lt;/artifactId&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;com.h2database&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;h2&amp;lt;/artifactId&amp;gt;
        &amp;lt;scope&amp;gt;runtime&amp;lt;/scope&amp;gt;
    &amp;lt;/dependency&amp;gt;
&amp;lt;/dependencies&amp;gt;&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;h2&gt;📦 Domain Model&lt;/h2&gt;
        &lt;p&gt;Create the Customer entity with validation:&lt;/p&gt;
        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;Customer.java&lt;/span&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;@Entity
@Data
@NoArgsConstructor
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank(message = &quot;First name is required&quot;)
    private String firstName;

    @Email(message = &quot;Email should be valid&quot;)
    private String email;

    @Min(value = 18, message = &quot;Age should be at least 18&quot;)
    private Integer age;

    private Boolean active = true;
}&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;h2&gt;🔄 REST Endpoints&lt;/h2&gt;
        &lt;table&gt;
            &lt;tr&gt;
                &lt;th&gt;Method&lt;/th&gt;
                &lt;th&gt;Endpoint&lt;/th&gt;
                &lt;th&gt;Description&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td&gt;GET&lt;/td&gt;
                &lt;td class=&quot;endpoint&quot;&gt;/api/customers&lt;/td&gt;
                &lt;td&gt;Get all customers&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td&gt;GET&lt;/td&gt;
                &lt;td class=&quot;endpoint&quot;&gt;/api/customers/{id}&lt;/td&gt;
                &lt;td&gt;Get customer by ID&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td&gt;POST&lt;/td&gt;
                &lt;td class=&quot;endpoint&quot;&gt;/api/customers&lt;/td&gt;
                &lt;td&gt;Create new customer&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td&gt;PUT&lt;/td&gt;
                &lt;td class=&quot;endpoint&quot;&gt;/api/customers/{id}&lt;/td&gt;
                &lt;td&gt;Update customer&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td&gt;DELETE&lt;/td&gt;
                &lt;td class=&quot;endpoint&quot;&gt;/api/customers/{id}&lt;/td&gt;
                &lt;td&gt;Delete customer&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td&gt;PATCH&lt;/td&gt;
                &lt;td class=&quot;endpoint&quot;&gt;/api/customers/{id}/deactivate&lt;/td&gt;
                &lt;td&gt;Deactivate customer&lt;/td&gt;
            &lt;/tr&gt;
        &lt;/table&gt;

        &lt;h2&gt;🎯 Controller Implementation&lt;/h2&gt;
        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;CustomerController.java&lt;/span&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;@RestController
@RequestMapping(&quot;/api/customers&quot;)
@RequiredArgsConstructor
public class CustomerController {
    private final CustomerService customerService;

    @GetMapping
    public ResponseEntity&lt;List&lt;Customer&gt;&gt; getAllCustomers(
            @RequestParam(required = false) Boolean activeOnly) {
        List&lt;Customer&gt; customers = activeOnly != null &amp;&amp; activeOnly 
            ? customerService.getActiveCustomers()
            : customerService.getAllCustomers();
        return ResponseEntity.ok(customers);
    }

    @PostMapping
    public ResponseEntity&lt;Customer&gt; createCustomer(
            @Valid @RequestBody Customer customer) {
        return new ResponseEntity&lt;&gt;(
            customerService.createCustomer(customer), 
            HttpStatus.CREATED
        );
    }
}&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;h2&gt;⚡ Exception Handling&lt;/h2&gt;
        &lt;p&gt;Global exception handler for consistent error responses:&lt;/p&gt;
        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;GlobalExceptionHandler.java&lt;/span&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(CustomerNotFoundException.class)
    public ResponseEntity&lt;ErrorResponse&gt; handleCustomerNotFoundException(
            CustomerNotFoundException ex) {
        ErrorResponse error = new ErrorResponse(
            HttpStatus.NOT_FOUND.value(),
            ex.getMessage(),
            LocalDateTime.now()
        );
        return new ResponseEntity&lt;&gt;(error, HttpStatus.NOT_FOUND);
    }
}&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;h2&gt;📝 Sample Data&lt;/h2&gt;
        &lt;p&gt;
            The application automatically generates sample customer data on startup:
        &lt;/p&gt;
        &lt;div class=&quot;code-container&quot;&gt;
            &lt;div class=&quot;code-header&quot;&gt;
                &lt;span&gt;Sample Data&lt;/span&gt;
            &lt;/div&gt;
            &lt;pre&gt;&lt;code class=&quot;language-json&quot;&gt;{
    &quot;firstName&quot;: &quot;John&quot;,
    &quot;lastName&quot;: &quot;Doe&quot;,
    &quot;email&quot;: &quot;john.doe@example.com&quot;,
    &quot;phone&quot;: &quot;+1234567890&quot;,
    &quot;age&quot;: 30
}&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

        &lt;h2&gt;🚀 Running the Application&lt;/h2&gt;
        &lt;ol&gt;
            &lt;li&gt;Clone the repository&lt;/li&gt;
            &lt;li&gt;Run &lt;code&gt;mvn clean install&lt;/code&gt;&lt;/li&gt;
            &lt;li&gt;Start the application&lt;/li&gt;
            &lt;li&gt;Access Swagger UI at &lt;code&gt;http://localhost:8080/swagger-ui.html&lt;/code&gt;&lt;/li&gt;
            &lt;li&gt;Access H2 Console at &lt;code&gt;http://localhost:8080/h2-console&lt;/code&gt;&lt;/li&gt;
        &lt;/ol&gt;

        &lt;div class=&quot;tip&quot;&gt;
            &lt;strong&gt;Testing the API:&lt;/strong&gt;
            &lt;p&gt;You can use tools like Postman or curl to test the endpoints. For example:&lt;/p&gt;
            &lt;pre&gt;&lt;code&gt;curl http://localhost:8080/api/customers&lt;/code&gt;&lt;/pre&gt;
        &lt;/div&gt;

      
    &lt;/div&gt;

    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/prism.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-java.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-json.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-xml.min.js&quot;&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</content><link rel='replies' type='application/atom+xml' href='http://krishnapotluri.blogspot.com/feeds/2567286694263906404/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://krishnapotluri.blogspot.com/2018/06/building-restful-api-with-spring-boot.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/2567286694263906404'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/2567286694263906404'/><link rel='alternate' type='text/html' href='http://krishnapotluri.blogspot.com/2018/06/building-restful-api-with-spring-boot.html' title=''/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-162532840988979012.post-3757631186085438866</id><published>2017-03-28T15:33:00.000-07:00</published><updated>2024-12-31T15:45:04.760-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Hadoop"/><title type='text'>Hadoop</title><content type='html'>&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
    &lt;title&gt;Hadoop Ecosystem Tutorial - Word Count Examples&lt;/title&gt;
    &lt;link href=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/themes/prism-tomorrow.min.css&quot; rel=&quot;stylesheet&quot; /&gt;
    &lt;style&gt;
        body {
            font-family: &#39;Segoe UI&#39;, Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        
        h1, h2, h3 {
            color: #2c3e50;
        }
        
        .code-container {
            position: relative;
            margin: 20px 0;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .code-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 20px;
            background: #2c3e50;
            color: white;
            border-radius: 8px 8px 0 0;
        }
        
        .copy-button {
            background: #3498db;
            color: white;
            border: none;
            padding: 5px 15px;
            border-radius: 4px;
            cursor: pointer;
            transition: background 0.3s;
        }
        
        .copy-button:hover {
            background: #2980b9;
        }
        
        pre {
            margin: 0;
            padding: 20px;
            border-radius: 0 0 8px 8px;
        }
        
        code {
            font-family: &#39;Fira Code&#39;, monospace;
        }
        
        .success-message {
            position: fixed;
            top: 20px;
            right: 20px;
            background: #2ecc71;
            color: white;
            padding: 10px 20px;
            border-radius: 4px;
            display: none;
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1&gt;Hadoop Ecosystem Tutorial - Word Count Examples&lt;/h1&gt;
    &lt;p&gt;This tutorial demonstrates how to implement word count using different components of the Hadoop ecosystem.&lt;/p&gt;

    &lt;div id=&quot;copy-success&quot; class=&quot;success-message&quot;&gt;Code copied!&lt;/div&gt;

    &lt;h2&gt;1. HDFS Example&lt;/h2&gt;
    &lt;div class=&quot;code-container&quot;&gt;
        &lt;div class=&quot;code-header&quot;&gt;
            &lt;span&gt;HDFSWordCount.java&lt;/span&gt;
            &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
        &lt;/div&gt;
        &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IOUtils;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class HDFSWordCount {
    public static void main(String[] args) {
        try {
            // Initialize HDFS configuration
            Configuration conf = new Configuration();
            FileSystem fs = FileSystem.get(conf);

            // Path to input file in HDFS
            Path inputPath = new Path(&quot;/input/sample.txt&quot;);
            
            // Read file from HDFS
            FSDataInputStream in = fs.open(inputPath);
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            
            // Word count map
            Map&lt;String, Integer&gt; wordCount = new HashMap&lt;&gt;();
            
            String line;
            while ((line = reader.readLine()) != null) {
                String[] words = line.toLowerCase().split(&quot;\\W+&quot;);
                for (String word : words) {
                    if (word.length() &gt; 0) {
                        wordCount.merge(word, 1, Integer::sum);
                    }
                }
            }
            
            // Write results back to HDFS
            Path outputPath = new Path(&quot;/output/hdfs_wordcount.txt&quot;);
            FSDataOutputStream out = fs.create(outputPath);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
            
            for (Map.Entry&lt;String, Integer&gt; entry : wordCount.entrySet()) {
                writer.write(entry.getKey() + &quot;\t&quot; + entry.getValue() + &quot;\n&quot;);
            }
            
            // Cleanup
            writer.close();
            reader.close();
            System.out.println(&quot;Word count completed successfully!&quot;);
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}&lt;/code&gt;&lt;/pre&gt;
    &lt;/div&gt;

    &lt;h2&gt;2. MapReduce Example&lt;/h2&gt;
    &lt;div class=&quot;code-container&quot;&gt;
        &lt;div class=&quot;code-header&quot;&gt;
            &lt;span&gt;WordCountMR.java&lt;/span&gt;
            &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
        &lt;/div&gt;
        &lt;pre&gt;&lt;code class=&quot;language-java&quot;&gt;import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import java.io.IOException;
import java.util.StringTokenizer;

public class WordCountMR {
    
    public static class TokenizerMapper extends Mapper&lt;Object, Text, Text, IntWritable&gt; {
        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();
        
        public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            StringTokenizer itr = new StringTokenizer(value.toString());
            while (itr.hasMoreTokens()) {
                word.set(itr.nextToken().toLowerCase());
                context.write(word, one);
            }
        }
    }
    
    public static class IntSumReducer extends Reducer&lt;Text, IntWritable, Text, IntWritable&gt; {
        private IntWritable result = new IntWritable();
        
        public void reduce(Text key, Iterable&lt;IntWritable&gt; values, Context context)
                throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable val : values) {
                sum += val.get();
            }
            result.set(sum);
            context.write(key, result);
        }
    }
    
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, &quot;word count&quot;);
        
        job.setJarByClass(WordCountMR.class);
        job.setMapperClass(TokenizerMapper.class);
        job.setCombinerClass(IntSumReducer.class);
        job.setReducerClass(IntSumReducer.class);
        
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        
        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));
        
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}&lt;/code&gt;&lt;/pre&gt;
    &lt;/div&gt;

    &lt;h2&gt;3. PIG Example&lt;/h2&gt;
    &lt;div class=&quot;code-container&quot;&gt;
        &lt;div class=&quot;code-header&quot;&gt;
            &lt;span&gt;wordcount.pig&lt;/span&gt;
            &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
        &lt;/div&gt;
        &lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- Load the input file
raw_input = LOAD &#39;/input/sample.txt&#39; AS (line:chararray);

-- Tokenize the words
words = FOREACH raw_input GENERATE FLATTEN(TOKENIZE(LOWER(line))) AS word;

-- Group words and count occurrences
word_groups = GROUP words BY word;
word_count = FOREACH word_groups GENERATE group AS word, COUNT(words) AS count;

-- Sort results by count in descending order
ordered_word_count = ORDER word_count BY count DESC;

-- Store the results
STORE ordered_word_count INTO &#39;/output/pig_wordcount&#39;;&lt;/code&gt;&lt;/pre&gt;
    &lt;/div&gt;

    &lt;h2&gt;4. Hive Example&lt;/h2&gt;
    &lt;div class=&quot;code-container&quot;&gt;
        &lt;div class=&quot;code-header&quot;&gt;
            &lt;span&gt;wordcount.hql&lt;/span&gt;
            &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
        &lt;/div&gt;
        &lt;pre&gt;&lt;code class=&quot;language-sql&quot;&gt;-- Create a table for raw input text
CREATE TABLE IF NOT EXISTS raw_text (
    line STRING
);

-- Load data into the raw_text table
LOAD DATA INPATH &#39;/input/sample.txt&#39; INTO TABLE raw_text;

-- Create a table for word counts
CREATE TABLE IF NOT EXISTS word_counts (
    word STRING,
    count INT
);

-- Insert processed data into word_counts table
INSERT OVERWRITE TABLE word_counts
SELECT word, COUNT(*) as count
FROM (
    SELECT EXPLODE(SPLIT(LOWER(line), &#39;\\W+&#39;)) as word
    FROM raw_text
    WHERE TRIM(line) != &#39;&#39;
) w
WHERE LENGTH(word) &gt; 0
GROUP BY word
ORDER BY count DESC;&lt;/code&gt;&lt;/pre&gt;
    &lt;/div&gt;

    &lt;h2&gt;5. Spark Examples&lt;/h2&gt;
    &lt;h3&gt;Scala Implementation&lt;/h3&gt;
    &lt;div class=&quot;code-container&quot;&gt;
        &lt;div class=&quot;code-header&quot;&gt;
            &lt;span&gt;WordCountSpark.scala&lt;/span&gt;
            &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
        &lt;/div&gt;
        &lt;pre&gt;&lt;code class=&quot;language-scala&quot;&gt;import org.apache.spark.sql.SparkSession

object WordCountSpark {
  def main(args: Array[String]): Unit = {
    // Create Spark session
    val spark = SparkSession.builder()
      .appName(&quot;Spark Word Count&quot;)
      .master(&quot;local[*]&quot;)  // Use local mode for testing, remove for cluster deployment
      .getOrCreate()

    // Import spark implicits for DataFrame operations
    import spark.implicits._

    try {
      // Read input file
      val inputPath = &quot;/input/sample.txt&quot;
      val outputPath = &quot;/output/spark_wordcount&quot;

      // Read text file and split into words
      val words = spark.read.textFile(inputPath)
        .flatMap(line =&gt; line.toLowerCase.split(&quot;\\W+&quot;))
        .filter(_.nonEmpty)

      // Count words
      val wordCounts = words.groupBy(&quot;value&quot;)
        .count()
        .orderBy($&quot;count&quot;.desc)
        .withColumnRenamed(&quot;value&quot;, &quot;word&quot;)

      // Save results
      wordCounts.write
        .mode(&quot;overwrite&quot;)
        .format(&quot;csv&quot;)
        .option(&quot;header&quot;, &quot;true&quot;)
        .save(outputPath)

      // Show results
      println(&quot;Word Count Results:&quot;)
      wordCounts.show()

    } finally {
      // Clean up
      spark.stop()
    }
  }
}&lt;/code&gt;&lt;/pre&gt;
    &lt;/div&gt;

    &lt;h3&gt;Python Implementation&lt;/h3&gt;
    &lt;div class=&quot;code-container&quot;&gt;
        &lt;div class=&quot;code-header&quot;&gt;
            &lt;span&gt;word_count_spark.py&lt;/span&gt;
            &lt;button class=&quot;copy-button&quot; onclick=&quot;copyCode(this)&quot;&gt;Copy Code&lt;/button&gt;
        &lt;/div&gt;
        &lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;from pyspark.sql import SparkSession
from pyspark.sql.functions import explode, split, lower, count, desc

def word_count_spark():
    # Create Spark session
    spark = SparkSession.builder \
        .appName(&quot;PySpark Word Count&quot;) \
        .master(&quot;local[*]&quot;) \
        .getOrCreate()

    try:
        # Input and output paths
        input_path = &quot;/input/sample.txt&quot;
        output_path = &quot;/output/pyspark_wordcount&quot;

        # Read the input file
        df = spark.read.text(input_path)

        # Process the text and count words
        word_counts = df.select(explode(split(lower(df.value), &quot;\\W+&quot;)).alias(&quot;word&quot;)) \
            .filter(&quot;word != &#39;&#39;&quot;) \
            .groupBy(&quot;word&quot;) \
            .agg(count(&quot;*&quot;).alias(&quot;count&quot;)) \
            .orderBy(desc(&quot;count&quot;))

        # Save results
        word_counts.write \
            .mode(&quot;overwrite&quot;) \
            .format(&quot;csv&quot;) \
            .option(&quot;header&quot;, &quot;true&quot;) \
            .save(output_path)

        # Show results
        print(&quot;Word Count Results:&quot;)
        word_counts.show()

    finally:
        # Clean up
        spark.stop()

if __name__ == &quot;__main__&quot;:
    word_count_spark()&lt;/code&gt;&lt;/pre&gt;
    &lt;/div&gt;

    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/prism.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-java.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-scala.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-python.min.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-sql.min.js&quot;&gt;&lt;/script&gt;
    
    &lt;script&gt;
        function copyCode(button) {
            const codeBlock = button.parentElement.nextElementSibling.querySelector(&#39;code&#39;);
            const text = codeBlock.innerText;
            
            navigator.clipboard.writeText(text).then(() =&gt; {
                const successMessage = document.getElementById(&#39;copy-success&#39;);
                successMessage.style.display = &#39;block&#39;;
                setTimeout(() =&gt; {
                    successMessage.style.display = &#39;none&#39;;
                }, 2000);
            });
        }
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</content><link rel='replies' type='application/atom+xml' href='http://krishnapotluri.blogspot.com/feeds/3757631186085438866/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://krishnapotluri.blogspot.com/2017/03/hadoop-ecosystem-tutorial-word-count.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/3757631186085438866'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/3757631186085438866'/><link rel='alternate' type='text/html' href='http://krishnapotluri.blogspot.com/2017/03/hadoop-ecosystem-tutorial-word-count.html' title='Hadoop'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-162532840988979012.post-8466078216648892945</id><published>2011-09-14T20:25:00.000-07:00</published><updated>2011-09-14T20:26:54.530-07:00</updated><title type='text'>PayPal and MVC</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;Recently i had an opportunity to implement paypal. At first it was way too overwhelming to read about it and implement it in a day or two. However, this video &lt;a href=&quot;http://www.asp.net/mvc/videos/aspnet-mvc-storefront-part-22-restructuring-rerouting-and-paypal&quot;&gt;link&lt;/a&gt;&amp;nbsp; by Rob Conery cleared up lot of my confusion. I recommend seeing this video if you have any plans to implement paypal. So, &lt;a href=&quot;http://sandbox.paypal.com/&quot;&gt;PayPal SandBox&lt;/a&gt;&amp;nbsp; is the development site where you can test your code. All the code i have implemented is either in documentation or from the video.&lt;br /&gt;
&lt;br /&gt;
//Controller&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: csharp&quot;&gt;public class PayPalController : Controller
{
private const string Server_URL = &quot;https://www.sandbox.paypal.com/cgi-bin/webscr?&quot;;


public PayPalController()
{

}

public ActionResult Index()
{
MovieModel movieModel = new MovieModel();
movieModel.MovieDate = new List&lt;string&gt;() {
new DateTime(2011,9,15).ToLongDateString()
};
movieModel.MovieTime = new List&lt;string&gt;()
{
&quot;12:00 PM&quot;,&quot;3:00 PM&quot;,&quot;7:00 PM&quot;,&quot;10:00 PM&quot;
};
movieModel.NoOfTickets = new List&lt;int&gt;() {1,2,3,4,5,6};
movieModel.Price = 15;
return View(movieModel);
}

public RedirectResult PostToPayPal(MovieModel movieModel)
{
string custom = GetTransactionFromDB(movieModel);
string cmd = &quot;_xclick&quot;;
string business = &quot;SELLEREMAIL&quot;;
string notify_url = &quot;Localhost/PayPal/IPN&quot;;
int amount = movieModel.Price;
string item_name = &quot;Ticket&quot;;
string redirect = string.Format(&quot;{0}&amp;amp;cmd={1}¬ify_url={2}&amp;amp;amount={3}&amp;amp;item_name={4}&amp;amp;custom={5}&amp;amp;business={6}&quot;,Server_URL,cmd,notify_url,amount,item_name,custom,business);
return Redirect(redirect);  
}

private string GetTransactionFromDB(MovieModel movieModel)
{
//store from model in DB and return transactionID
//store amount also,need to verify later.
return &quot;123-234-5678&quot;;
}


public void IPN()
{
var formVals = new Dictionary&lt;string, string=&quot;&quot;&gt;();
formVals.Add(&quot;cmd&quot;, &quot;_notify-validate&quot;);
string response = GetPayPalResponse(formVals, true);
if (response == &quot;VERIFIED&quot;)
{
string sAmountPaid = Request[&quot;mc_gross&quot;];
string paymentStatus = Request[&quot;payment_status&quot;];
string customField = Request[&quot;custom&quot;];
if (sAmountPaid == GetPriceFromDatabase(id) &amp;amp;&amp;amp; paymentStatus == &quot;Completed&quot;)
{
string buyerEmail = Request[&quot;payer_email&quot;];
string transactionID = Request[&quot;txn_id&quot;];//PayPal Transaction ID(Store It)
string firstName = Request[&quot;first_name&quot;];
string lastName = Request[&quot;last_name&quot;];
//Call to SP saying Payment Processed
}
else
{
//Call to SP Saying Payment Corrupt or Invalid
}
}
else if (response == &quot;INVALID&quot;)
{
//Call to SP Saying Payment Failed;
}
else
{
//Send Email to Admin with response details
}
}

private string GetPriceFromDatabase(string id)
{
return &quot;15&quot;;
}



public string GetPayPalResponse(Dictionary&lt;string, string=&quot;&quot;&gt; formVals, bool useSandbox)
{

string paypalUrl = useSandbox ? &quot;https://www.sandbox.paypal.com/cgi-bin/webscr&quot;
: &quot;https://www.paypal.com/cgi-bin/webscr&quot;;


HttpWebRequest req = (HttpWebRequest)WebRequest.Create(paypalUrl);

// Set values for the request back

req.Method = &quot;POST&quot;;
req.ContentType = &quot;application/x-www-form-urlencoded&quot;;

byte[] param = Request.BinaryRead(Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);

StringBuilder sb = new StringBuilder();
sb.Append(strRequest);

foreach (string key in formVals.Keys)
{
sb.AppendFormat(&quot;&amp;amp;{0}={1}&quot;, key, formVals[key]);
}
strRequest += sb.ToString();
req.ContentLength = strRequest.Length;

string response = &quot;&quot;;
using (StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII))
{

streamOut.Write(strRequest);
streamOut.Close();
using (StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()))
{
response = streamIn.ReadToEnd();
}
}

return response;
}


}
}

&lt;/string,&gt;&lt;/string,&gt;&lt;/int&gt;&lt;/string&gt;&lt;/string&gt;&lt;/pre&gt;&lt;br /&gt;
//View&lt;br /&gt;
&lt;pre class=&quot;brush: html&quot;&gt;&amp;lt;% using (Html.BeginForm(&quot;PostToPayPal&quot;, &quot;PayPal&quot;, new { id= &quot;Form&quot; }))
   { %&amp;gt;
&lt;div class=&quot;Place&quot;&gt;&lt;div class=&quot;PlaceName&quot;&gt;(Theatre Name)&lt;/div&gt;&lt;div class=&quot;PlaceName&quot;&gt;Date: &amp;lt;%= Html.DropDownListFor(model =&amp;gt; model.MovieDate,new SelectList(Model.MovieDate,Model.MovieDate.First())) %&amp;gt; &lt;/div&gt;&amp;lt;%= Html.HiddenFor(model =&amp;gt; model.Price, new { id = &quot;Price&quot; })%&amp;gt;
&amp;lt;%= Html.HiddenFor(model =&amp;gt; model.TheatreName, new { id = &quot;TheatreName&quot;}) %&amp;gt;



&lt;table border=&quot;1&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; class=&quot;reference&quot;&gt;&lt;tbody&gt;
&lt;tr&gt;   &lt;td&gt;Time&lt;/td&gt;   &lt;td&gt;Tickets&lt;/td&gt;         &lt;td&gt;Price&lt;/td&gt;         &lt;td&gt;Buy With PayPal&lt;/td&gt;  &lt;/tr&gt;
&lt;tr&gt;   &lt;td&gt;&amp;lt;%= Html.DropDownListFor(model =&amp;gt; model.MovieTime, new SelectList(Model.MovieTime, &quot;3:00 PM&quot;))%&amp;gt;&lt;/td&gt;   &lt;td&gt;&lt;br /&gt;
&amp;lt;%= Html.DropDownListFor(model =&amp;gt; model.NoOfTickets, new SelectList(Model.NoOfTickets, 1), new { id = &quot;Tickets&quot; })%&amp;gt;&lt;/td&gt;         &lt;td id=&quot;sPrc&quot;&gt;&lt;br /&gt;
15$&lt;/td&gt; &lt;td&gt;&lt;br /&gt;
&lt;div class=&quot;PayPalButton&quot;&gt;&lt;br /&gt;
&lt;input alt=&quot;PayPal - The safer, easier way to pay online!&quot; border=&quot;0&quot; name=&quot;submit&quot; src=&quot;https://www.sandbox.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif&quot; type=&quot;image&quot; /&gt;&lt;br /&gt;
&lt;img alt=&quot;&quot; border=&quot;0&quot; height=&quot;1&quot; src=&quot;https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif&quot; width=&quot;1&quot; /&gt;&lt;/div&gt;&lt;/td&gt; &lt;/tr&gt;
&lt;/tbody&gt; &lt;/table&gt;&lt;/div&gt;&amp;lt;%} %&amp;gt;
&lt;/pre&gt;&lt;br /&gt;
Email me if you have questions. But like i said, the video has most of the explanation.&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://krishnapotluri.blogspot.com/feeds/8466078216648892945/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://krishnapotluri.blogspot.com/2011/09/paypal-and-mvc.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/8466078216648892945'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/8466078216648892945'/><link rel='alternate' type='text/html' href='http://krishnapotluri.blogspot.com/2011/09/paypal-and-mvc.html' title='PayPal and MVC'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-162532840988979012.post-1768276143191736697</id><published>2011-08-11T20:38:00.000-07:00</published><updated>2011-09-14T19:54:15.920-07:00</updated><title type='text'>Simple Chat Prototype using ASP.Net MVC</title><content type='html'>This chat application is a browser based chat.It uses ajax calls to get and send data.&lt;br /&gt;
On the server i have used two singletons which handle the messages and the list of online users&lt;br /&gt;
&lt;b&gt;&lt;br /&gt;
Controller and Models&lt;/b&gt;&lt;br /&gt;
&lt;pre class=&quot;brush: csharp&quot;&gt;//User Collection
namespace ChatClient.Models
{
    public sealed class UserCollection
    {

        private static UserCollection instance = null;
        private List&lt;user&gt; users = new List&lt;user&gt;();
        private static readonly object padlock = new object();

         UserCollection()
         {
         }

         public static UserCollection Instance
         {
                get
                {
                    lock (padlock)
                    {
                        if (instance == null)
                        {
                            instance = new UserCollection();
                        }
                        return instance;
                    }
                }
          }

         public void AddToUserCollection(User user)
         {
             users.Add(user);
         }

         public void RemoveFromUserCollection(User user)
         {
             users.Remove(user);
         }

         public bool IsUserPresent(User user)
         {
             return users.Exists(p =&gt; p.Name == user.Name);
         }
         
    }
}

public class User
    {
        public string Name { get; set; }
        public bool Online { get; set; }

    }

public class ChatMessage
    {
        public string Message { get; set; }
        public string MessageDateTime { get; set; }
        public User FromUser { get; set; }
        public User ToUser { get; set; }
    }

  public class MessageCollection
    {

         private static MessageCollection instance = null;
         private List&lt;chatmessage&gt; chatMessages = new List&lt;chatmessage&gt;();
        private static readonly object padlock = new object();

        MessageCollection()
         {
         }

        public static MessageCollection Instance
         {
                get
                {
                    lock (padlock)
                    {
                        if (instance == null)
                        {
                            instance = new MessageCollection();
                        }
                        return instance;
                    }
                }
          }

        public void AddToMessageCollection(ChatMessage chatMessage)
         {
             chatMessages.Add(chatMessage);
         }

        public void RemoveFromMessageCollection(User user)
         {
             chatMessages.RemoveAll(p =&gt; p.ToUser.Name == user.Name);
         }

         public List&lt;chatmessage&gt; GetMessages(User user)
         {
             return chatMessages.Where(p =&gt; p.ToUser.Name == user.Name).Select(p =&gt; p).ToList();
         }

    }


//Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ChatClient.Models;
using System.Runtime.Remoting.Messaging;

namespace ChatClient.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        UserCollection collection = UserCollection.Instance;
        MessageCollection messageCollection = MessageCollection.Instance;

        public ActionResult Index()
        {
            return View();
        }

        public string Register(string userName)
        {
            if (!collection.IsUserPresent(new User() { Name = userName, Online = true }))
            {
                collection.AddToUserCollection(new User()
                {
                    Name = userName,
                    Online = true,
                });
            }
            return &quot;Online&quot;;
        }

        public JsonResult SendMessage(string message, string toUser, string fromUser)
        {
            ChatMessage chatMessage = new ChatMessage()
            {
                FromUser = new User() {
                            Name = fromUser,
                            Online = true
                },
                ToUser = new User()
                {
                    Name = toUser,
                    Online = true
                },
                Message = message,
                MessageDateTime = DateTime.Now.ToString()
            };
            messageCollection.AddToMessageCollection(chatMessage);
            return Json(chatMessage);
        }

        public JsonResult GetMessages(string userName)
        {
            if (messageCollection.GetMessages(new User() { Name = userName, Online = true }).Count &gt; 0)
            {
                List&lt;chatmessage&gt; messages = messageCollection.GetMessages(new User() { Name = userName, Online = true }).Select(p =&gt; p).ToList();
                Action remove = delegate()
                {
                    RemoveMessages(userName);
                };
                IAsyncResult result = remove.BeginInvoke(RemoveMessagesEnd, null);
                return Json(messages.ToArray(),JsonRequestBehavior.AllowGet);
            }
            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }
        public void RemoveMessagesEnd(IAsyncResult result)
        {
            object state = (AsyncResult)result.AsyncState;
        }

        public void RemoveMessages(string userName)
        {
            messageCollection.RemoveFromMessageCollection(new User() { Name = userName, Online = true });
        }
        public ActionResult About()
        {
            return View();
        }
    }
}



&lt;/pre&gt;&lt;br /&gt;
&lt;b&gt;View&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: html&quot;&gt;&lt;asp:Content ID=&quot;Content2&quot; ContentPlaceHolderID=&quot;MainContent&quot; runat=&quot;server&quot;&gt;
  &lt;script type=&quot;text/javascript&quot;&gt;
      $(document).ready(function () {

          setInterval(GetMessages, 5000);

          function GetMessages() {
              $.ajax({
                  type: &quot;GET&quot;,
                  url: &quot;&lt;%= Url.Content(&quot;~/Home/GetMessages&quot;) %&gt;&quot;,
                  data: &quot;userName=&quot; + $(&quot;#userName&quot;).val(),
                  success: function (msg) {
                     $(&quot;#ChatHistory&quot;).append(msg[0].FromUser.Name + &quot;:&quot; + msg[0].Message + &quot;\n&quot;);
                  }
              });

          }

          $(&quot;#Register&quot;).click(function () {
              $.ajax({
                  type: &quot;POST&quot;,
                  url: &quot;&lt;%= Url.Content(&quot;~/Home/Register&quot;) %&gt;&quot;,
                  data: &quot;userName=&quot; + $(&quot;#userName&quot;).val(),
                  success: function (msg) {
                      alert(&quot;Data Saved: &quot; + msg);
                  }
              });
          });

          $(&quot;#ChatSubmit&quot;).click(function () {
              $.ajax({
                  type: &quot;POST&quot;,
                  url: &quot;&lt;%= Url.Content(&quot;~/Home/SendMessage&quot;) %&gt;&quot;,
                  data: &quot;message=&quot; + $(&quot;#ChatBox&quot;).val() + &quot;&amp;toUser=&quot; + $(&quot;#toUser&quot;).val() + &quot;&amp;fromUser=&quot; + $(&quot;#userName&quot;).val() ,
                  success: function (msg) {
                      $(&quot;#ChatHistory&quot;).append(msg.FromUser.Name + &quot;:&quot; + msg.Message + &quot;\n&quot;);
                  }
              });      
          });
      });
  &lt;/script&gt;
  &lt;div&gt;&lt;%= Html.Label(&quot;UserName&quot;) %&gt;
 &lt;%= Html.TextBox(&quot;userName&quot;)%&gt;
 &lt;%= Html.Label(&quot;ToUser&quot;) %&gt;
 &lt;%=Html.TextBox(&quot;toUser&quot;) %&gt;
 &lt;button type=&quot;button&quot; id=&quot;Register&quot;&gt;Go Online&lt;/button&gt;
 &lt;div&gt;&lt;%= Html.Label(&quot;ChatHistory&quot;) %&gt;
 &lt;%= Html.TextArea(&quot;ChatHistory&quot;)%&gt;
 &lt;%= Html.Label(&quot;ChatBox&quot;) %&gt;
 &lt;%= Html.TextBox(&quot;ChatBox&quot;) %&gt;
 &lt;button type=&quot;button&quot; id=&quot;ChatSubmit&quot;&gt;Send&lt;/button&gt;
 &lt;/div&gt;&lt;/div&gt;&lt;/asp:Content&gt;
&lt;/pre&gt;&lt;br /&gt;
&lt;iframe src=&quot;http://rcm.amazon.com/e/cm?t=potluscode-20&amp;o=1&amp;p=8&amp;l=as1&amp;asins=B004I49NJ8&amp;ref=tf_til&amp;fc1=000000&amp;IS2=1&amp;lt1=_blank&amp;m=amazon&amp;lc1=0000FF&amp;bc1=000000&amp;bg1=FFFFFF&amp;f=ifr&quot; style=&quot;width:120px;height:240px;&quot; scrolling=&quot;no&quot; marginwidth=&quot;0&quot; marginheight=&quot;0&quot; frameborder=&quot;0&quot;&gt;&lt;/iframe&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;iframe src=&quot;http://rcm.amazon.com/e/cm?t=widgetsamazon-20&amp;o=1&amp;p=8&amp;l=bpl&amp;asins=1430234040&amp;fc1=000000&amp;IS2=1&amp;lt1=_blank&amp;m=amazon&amp;lc1=0000FF&amp;bc1=000000&amp;bg1=FFFFFF&amp;f=ifr&quot; style=&quot;align:left;padding-top:5px;width:131px;height:245px;padding-right:10px;&quot;align=&quot;left&quot; scrolling=&quot;no&quot; marginwidth=&quot;0&quot; marginheight=&quot;0&quot; frameborder=&quot;0&quot;&gt;&lt;/iframe&gt;</content><link rel='replies' type='application/atom+xml' href='http://krishnapotluri.blogspot.com/feeds/1768276143191736697/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://krishnapotluri.blogspot.com/2011/08/simple-chat-prototype-using-aspnet-mvc.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/1768276143191736697'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/1768276143191736697'/><link rel='alternate' type='text/html' href='http://krishnapotluri.blogspot.com/2011/08/simple-chat-prototype-using-aspnet-mvc.html' title='Simple Chat Prototype using ASP.Net MVC'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-162532840988979012.post-1541917219242645605</id><published>2011-05-25T08:43:00.000-07:00</published><updated>2011-08-11T20:16:08.549-07:00</updated><title type='text'>Jqgrid for MVC 2</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;Here i will put in code to demonstrate Jqgrid.This is one of the coolest grids available.There are many ways to implement this grid.There is a lot of documentation available for Jqgrid on its wiki,so i am not going to explain the stuff.The way i have implemented the grid is to have a search form and have ajax call made to the search controller and then let it return us a array data and that we feed directly to the grid.This grid will also have a double click event hooked up for all the rows returned.I have also used Block UI to block the page when we construct a dialog with all the information about the record.One problem i faced with Json is,the default max for JSon Serialization is very small,so i found a class LargeJSon on google which basically increases the default limit to&lt;br /&gt;
&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;&amp;lt;jsonSerialization maxJsonLength=&quot;2147483644&quot;&quot;&amp;gt;&amp;lt;/jsonSerialization&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Here is the Main code&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: html&quot;&gt;&amp;lt;script type=&quot;text/javascript&quot; language=&quot;javascript&quot;&amp;gt;
$(document).ready(function() {


function Search() {
$(loading).show();
$.ajax({
type: &quot;POST&quot;,
url: &#39;&amp;lt;%=Url.Content(&quot;~/Search/Search&quot;)%&amp;gt;&#39;,
data: $(&quot;#SearchForm&quot;).serialize(),
datatype: &#39;json&#39;,
success: function(msg) {
if (msg != null) {
$(&quot;#Validation&quot;).hide();
var gridData = msg;
if (!loaded) {
loaded = LoadGridWithData(gridData);
}
else {
$(&quot;#list&quot;).GridUnload();
loaded = LoadGridWithData(gridData);
}
$(loading).hide();
}
},
error: function(xhr, status, error) {
var object = new Array();
object = xhr.responseText.split(&#39;;&#39;);
var response = &#39;&#39;;
for (var i = 0; i &amp;lt; object.length; i++) {
var p = &quot;&amp;lt;div&amp;gt;&quot; + object[i] + &quot;&amp;lt;/div&amp;gt;&quot;;
response += p;
}
$(&quot;#Validation&quot;).html(response);
$(&quot;#Validation&quot;).show();
$(loading).hide();
}
});

}

var dialogOpen = false;

function LoadGridWithData(gridData) {
jQuery(&quot;#list&quot;).jqGrid({
sortable: true,
data: gridData,
datatype: &#39;local&#39;,
mtype: &#39;GET&#39;,
colNames: [&#39;First Name&#39;, &#39;Middle Name&#39;, &#39;Last Name&#39;, &#39;Agent&#39;, &#39;State&#39;, &#39;Zip&#39;, &#39;Number&#39;, &#39;Type&#39;, &#39;Status&#39;, &#39;Date&#39;],
colModel: [
{ name: &#39;FirstName&#39;, index: &#39;FirstName&#39;, width: 30, sorttype: &#39;text&#39; },
{ name: &#39;MiddleName&#39;, index: &#39;MiddleName&#39;, width: 15, sorttype: &#39;text&#39;, align: &#39;left&#39; },
{ name: &#39;LastName&#39;, index: &#39;LastName&#39;, width: 40, sorttype: &#39;text&#39;, align: &#39;left&#39; },
{ name: &#39;Agent&#39;, index: &#39;Agent&#39;, width: 30, sorttype: &#39;int&#39;, align: &#39;left&#39; },
{ name: &#39;State&#39;, index: &#39;State&#39;, width: 15, sorttype: &#39;text&#39; },
{ name: &#39;Zip&#39;, index: &#39;Zip&#39;, width: 20, sorttype: &#39;int&#39;, align: &#39;left&#39; },
{ name: &#39;Number&#39;, index: &#39;Number&#39;, width: 50, sorttype: &#39;int&#39;, align: &#39;left&#39; },
{ name: &#39;Type&#39;, index: &#39;Type&#39;, width: 50, sorttype: &#39;text&#39;, align: &#39;left&#39; },
{ name: &#39;Status&#39;, index: &#39;Status&#39;, width: 50, sorttype: &#39;text&#39;, align: &#39;left&#39; },
{ name: &#39;Date&#39;, index: &#39;Date&#39;, width: 50, sorttype: &#39;date&#39;, resizable: false }
],
pager: &#39;#pager&#39;,
rowNum: 20,
rowList: [5, 10, 20, 50],
gridview: true,
sortname: &#39;Number&#39;,
sortorder: &quot;desc&quot;,
height: 400,
loadui: &quot;enable&quot;,
loadtext: &quot;Loading...&quot;,
autowidth: true,
rownumbers: true,
viewrecords: true,
caption: &#39;Quote Header Data&#39;,
ondblClickRow: function(id) {
$.blockUI({ message: &quot;&amp;lt;h1&amp;gt;Retrieving Information. Please Wait...&amp;lt;/h1&amp;gt;&quot;, timeout: 10000 });
var url = &#39;&amp;lt;%= Url.Content(&quot;~/&quot;) %&amp;gt;&#39; + &quot;Search/Modal&quot;;
$.post(url, { Id: id }, function(response, status, xhr) {
if (status != &quot;error&quot;) {
$.unblockUI();
$(&#39;#verificationedit-form&#39;).html(response).dialog(&quot;open&quot;);
}
else {
$.blockUI({ message: &quot;&amp;lt;h1&amp;gt;Retrieving Failed.Please Try Again...&amp;lt;/h1&amp;gt;&quot; });
$(&#39;.blockOverlay&#39;).attr(&#39;title&#39;, &#39;Click to unblock&#39;).click($.unblockUI);
}
});
}
});
jQuery(&quot;#list&quot;).jqGrid(&#39;navGrid&#39;, &#39;#pager&#39;, { del: false, add: false, edit: false, search: false });
return true;
}
}
&amp;lt;/script&amp;gt;



&amp;lt;table id=&quot;list&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot;&amp;gt;
&amp;lt;/table&amp;gt;
&amp;lt;div id=&quot;pager&quot; style=&quot;text-align: center;&quot;&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;div id=&quot;verificationedit-form&quot; title=&quot;Edit Verification Information&quot;&amp;gt;
&amp;lt;/div&amp;gt;


&lt;/pre&gt;//Controller&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: csharp&quot;&gt;[HttpPost]
[EnableCompression]
public JsonResult Search(SearchModel searchModel)
{
LargeJsonResult result = new LargeJsonResult();

if (ModelState.IsValid)
{
List&amp;lt;GridModel&amp;gt; model = repository.Search(searchModel);
var jsonData =
(from pp in model
select new
{
id = pp.Id,
pp.FirstName,
pp.MiddleName,
pp.LastName,
pp.Agent,
pp.State,
pp.Zip,
pp.Number,
pp.Type,
pp.Status,
pp.Date
}).ToArray();

result.Data = jsonData;
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return result;
}
else
{
StringBuilder errorString = Utilities.BuildErrorMessageFromModelStateWithDelimiter(ModelState, &quot;;&quot;);
Response.StatusCode = 500;
Response.Write(errorString.ToString());
return result;
}
}
&lt;/pre&gt;&lt;br /&gt;
Next time i will post the Jggrid code with inline editing.Happy Coding!!&lt;/div&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://krishnapotluri.blogspot.com/feeds/1541917219242645605/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://krishnapotluri.blogspot.com/2011/05/jqgrid-for-mvc-2.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/1541917219242645605'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/1541917219242645605'/><link rel='alternate' type='text/html' href='http://krishnapotluri.blogspot.com/2011/05/jqgrid-for-mvc-2.html' title='Jqgrid for MVC 2'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-162532840988979012.post-1729938897981866602</id><published>2011-01-26T15:26:00.000-08:00</published><updated>2011-08-11T20:18:57.064-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Jquery"/><category scheme="http://www.blogger.com/atom/ns#" term="MVC"/><title type='text'>autocomplete</title><content type='html'>autocomplete is one the coolest features for a UI to have.So i happened to get a chance to make it.I had some struggle initially as i am new to jquery but finally got it and it works like a charm.&lt;br /&gt;
&lt;br /&gt;
To do this you need to download Jquery autocomplete bundle.So,all we need to do is when the document loads we need to do a ajax call to your action to get your results(which is coming from your database or file,etc).For me it is the database,so you want to play around with it to find a sweet spot where your UI is not getting a performance hit because your query is taking too long.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: html&quot;&gt;jQuery(document).ready(function() {
$.ajax({
type: &quot;GET&quot;,
url: &quot;controller/AutoComplete&quot;,
data: &#39;{}&#39;,
success: function(msg) {
// Do something interesting here.
if (msg != null) {
data = msg.toString().split(&quot;,&quot;);
$(&quot;#Name&quot;).autocomplete(data);
}
},
error: function(xhr, status, error) {
// Boil the ASP.NET AJAX error down to JSON.
var err = eval(&quot;(&quot; + xhr.responseText + &quot;)&quot;);
// Display the specific error raised by the server
alert(err.Message);
}
});
}); 

&lt;/pre&gt;&lt;br /&gt;
&lt;br /&gt;
Now in your action,you need to call your repository to return back results,here i am returning a comma seperated array which i spit it and feed to the the autocomplete script.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: csharp&quot;&gt;[HttpGet]
public ActionResult AutoComplete()
{
string model = repository.GetDistinctNames();
return Content(model);
}
&lt;/pre&gt;&lt;br /&gt;
That&#39;s it you see autocomplete feature in your UI and your clients will be happy.</content><link rel='replies' type='application/atom+xml' href='http://krishnapotluri.blogspot.com/feeds/1729938897981866602/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://krishnapotluri.blogspot.com/2011/01/autocomplete.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/1729938897981866602'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/1729938897981866602'/><link rel='alternate' type='text/html' href='http://krishnapotluri.blogspot.com/2011/01/autocomplete.html' title='autocomplete'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-162532840988979012.post-3338980256116596014</id><published>2010-10-14T13:23:00.000-07:00</published><updated>2011-08-11T20:22:03.602-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="FileSystemWatcher"/><category scheme="http://www.blogger.com/atom/ns#" term="Rx"/><title type='text'>FileSystemWatcher Using Rx</title><content type='html'>&lt;div dir=&quot;ltr&quot; style=&quot;text-align: left;&quot; trbidi=&quot;on&quot;&gt;This is a simple program which checks and reports for error files produced by ETL jobs.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: csharp&quot;&gt;namespace ErrorFileWatcher
{
public class ErrFileWatcher
{
private readonly FileSystemWatcher _fileSystemWatcher;
public IObservable&lt;filesystemeventargs&gt; ChangedFiles { get; set; }
public IObservable&lt;filesystemeventargs&gt; CreatedFiles { get; set; }
public IObservable&lt;filesystemeventargs&gt; DeletedFiles { get; set; }
public IObservable&lt;renamedeventargs&gt; RenamedFiles { get; set; }
public IObservable&lt;erroreventargs&gt; Errors { get; set; }


public ErrFileWatcher(string directory, string filter, bool includeSubdirectories)
{
_fileSystemWatcher = new FileSystemWatcher(directory, filter)
{
EnableRaisingEvents = true,
IncludeSubdirectories = includeSubdirectories
};

ChangedFiles = Observable.FromEvent(
(EventHandler&lt;filesystemeventargs&gt; e) =&amp;gt; new FileSystemEventHandler(e),
e =&amp;gt; _fileSystemWatcher.Changed += e,
e =&amp;gt; _fileSystemWatcher.Changed -= e).Select(x =&amp;gt; x.EventArgs);

CreatedFiles = Observable.FromEvent(
(EventHandler&lt;filesystemeventargs&gt; e) =&amp;gt; new FileSystemEventHandler(e),
e =&amp;gt; _fileSystemWatcher.Created += e,
e =&amp;gt; _fileSystemWatcher.Created -= e).Select(x =&amp;gt; x.EventArgs);


DeletedFiles = Observable.FromEvent(
(EventHandler&lt;filesystemeventargs&gt; e) =&amp;gt; new FileSystemEventHandler(e),
e =&amp;gt; _fileSystemWatcher.Deleted += e,
e =&amp;gt; _fileSystemWatcher.Deleted -= e).Select(x =&amp;gt; x.EventArgs);


RenamedFiles = Observable.FromEvent(
(EventHandler&lt;renamedeventargs&gt; e) =&amp;gt; new RenamedEventHandler(e),
e =&amp;gt; _fileSystemWatcher.Renamed += e,
e =&amp;gt; _fileSystemWatcher.Renamed -= e).Select(x =&amp;gt; x.EventArgs);



Errors = Observable.FromEvent(
(EventHandler&lt;erroreventargs&gt; e) =&amp;gt; new ErrorEventHandler(e),
e =&amp;gt; _fileSystemWatcher.Error += e,
e =&amp;gt; _fileSystemWatcher.Error -= e).Select(x =&amp;gt; x.EventArgs);


}

}
}

&lt;/pre&gt;&lt;br /&gt;
Windows Service code which calls the above class and also calls the sendemail method&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: csharp&quot;&gt;try
{

while (true)
{
if (!RunToday)
{
if (IsItTimeToRun())
{
EventLog.WriteEntry(&quot;ErrorFileWactcher&quot;, &quot;Watcher Started For &quot; + DateTime.Now.Date, EventLogEntryType.Information);
SendEmails emails = new SendEmails();
Stopwatch sW = new Stopwatch();
sW.Start();
TextWriter writer = new StreamWriter(ConfigurationManager.AppSettings[&quot;FilePath&quot;].ToString());
ErrFileWatcher fileWatch = new ErrFileWatcher(ConfigurationManager.AppSettings[&quot;FILEPATHTOBEMONITORED&quot;], &quot;*.txt&quot;, false);
fileWatch.CreatedFiles.Where(p =&amp;gt; p.FullPath.Length &amp;gt; 0).Select(p =&amp;gt; p.Name).Subscribe(p =&amp;gt; writer.WriteLine(p.ToString() + &quot; Created&quot;));
fileWatch.ChangedFiles.Where(p =&amp;gt; p.FullPath.Length &amp;gt; 0).Select(p =&amp;gt; p.Name).Subscribe(p =&amp;gt; writer.WriteLine(p.ToString() + &quot; Changed&quot;));
fileWatch.DeletedFiles.Where(p =&amp;gt; p.FullPath.Length &amp;gt; 0).Select(p =&amp;gt; p.Name).Subscribe(p =&amp;gt; writer.WriteLine(p.ToString() + &quot; Deleted&quot;));
fileWatch.RenamedFiles.Where(p =&amp;gt; p.FullPath.Length &amp;gt; 0).Select(p =&amp;gt; p.Name).Subscribe(p =&amp;gt; writer.WriteLine(p.ToString() + &quot; Renamed&quot;));
while (true)
{
if (sW.Elapsed.Minutes &amp;gt; 10)
{
sW.Stop();
writer.Flush();
writer.Dispose();
emails.SendEmail(true, ConfigurationManager.AppSettings[&quot;FilePath&quot;].ToString(), &quot;ERRORREPORT&quot;);
break;
}
}
}
else
{
Thread.Sleep(int.Parse(ConfigurationManager.AppSettings[&quot;SleepTime&quot;]));
}
}
else
{
Thread.Sleep(int.Parse(ConfigurationManager.AppSettings[&quot;SleepTime&quot;]));
}
}
}
catch (Exception ex)
{
EventLog.WriteEntry(&quot;ErrorFileWactcher&quot;, ex.Message, EventLogEntryType.Error);
}
&lt;/pre&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://krishnapotluri.blogspot.com/feeds/3338980256116596014/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://krishnapotluri.blogspot.com/2010/10/filesystemwatcher-using-rx.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/3338980256116596014'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/3338980256116596014'/><link rel='alternate' type='text/html' href='http://krishnapotluri.blogspot.com/2010/10/filesystemwatcher-using-rx.html' title='FileSystemWatcher Using Rx'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-162532840988979012.post-6554492767124507447</id><published>2010-08-25T08:55:00.000-07:00</published><updated>2011-08-11T20:23:00.526-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Rx"/><title type='text'>Rx sample</title><content type='html'>&lt;div&gt;In this post i have implemented a simple program which writes all the information of a customer class to a file.I took this example as it can be functional in a very short period of time.The code in this blog is inspired from Rx wiki.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: csharp&quot;&gt;using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Threading;
using System.Concurrency;
using System.Diagnostics;

namespace ObservablePrototype
{
public class Prototype
{
string errorfile = ConfigurationManager.AppSettings[&quot;CustomerFile&quot;];

public void RunProto()
{
Stopwatch sw = new Stopwatch();
sw.Start();

//Making Customer as observableCollection 
var customers = new ObservableCollection&lt;customer&gt;();

// adding event handler 
var customerChanges = Observable.FromEvent(
(EventHandler&lt;notifycollectionchangedeventargs&gt; ev)
=&gt; new NotifyCollectionChangedEventHandler(ev),
ev =&gt; customers.CollectionChanged += ev,
ev =&gt; customers.CollectionChanged -= ev);

//ling query for notify collection changed

var line = (from c in customerChanges
where c.EventArgs.Action == NotifyCollectionChangedAction.Add
from cu in c.EventArgs.NewItems.Cast&lt;customer&gt;().ToObservable()
select cu).BufferWithCount(10);

//using scheduler or u can just subscribe directly
Scheduler.ThreadPool.Schedule(() =&gt;
{
line.Subscribe(cus =&gt;
{
WriteCustomers(cus.ToList());
}
);
});

//start adding customers  
AddCustomers(customers);
WriteTimings(sw.Elapsed.Seconds + &quot;Observable&quot;);
}

private void WriteTimings(string p)
{
TextWriter writer = new StreamWriter(errorfile, true);
writer.WriteLine(p);
writer.Close();
}



private void AddCustomers(ObservableCollection&lt;customer&gt; customers)
{
for (int i = 0; i &lt; 50; i++)
            {
                Thread.Sleep(500);
                customers.Add(new Customer() { firstName = &quot;K&quot;, lastName = &quot;P&quot; + i });
            }
            
        }



        public void StraightWrite()
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            List&lt;Customer&gt; customers = new List&lt;customer&gt;();
for (int i = 0; i &lt; 50; i++)
            {
                Thread.Sleep(500);
                customers.Add(new Customer() { firstName = &quot;K&quot;, lastName = &quot;P&quot; + i });
            }
            WriteCustomers(customers);
            WriteTimings(sw.Elapsed.Seconds + &quot;Normal&quot;);
        }



        private void WriteCustomers(List&lt;Customer&gt; customers)
{
foreach (var c in customers)
{
TextWriter writer = new StreamWriter(errorfile, true);
writer.WriteLine(&quot;FirstName : &quot; + c.firstName + &quot;  LastName : &quot; + c.lastName);
writer.Close();
}
}

}
}
&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div&gt;&lt;/div&gt;&lt;br /&gt;
&lt;div&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://krishnapotluri.blogspot.com/feeds/6554492767124507447/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://krishnapotluri.blogspot.com/2010/08/rx-sample.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/6554492767124507447'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/6554492767124507447'/><link rel='alternate' type='text/html' href='http://krishnapotluri.blogspot.com/2010/08/rx-sample.html' title='Rx sample'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-162532840988979012.post-3743473144926357285</id><published>2010-07-14T21:58:00.002-07:00</published><updated>2011-09-14T20:01:00.602-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="OTAClient"/><title type='text'>OTAClient + QC reporting with C#</title><content type='html'>When writing a Data Comparison tool, one of the requirements was to log the errors into Quality Center. Thats where OTAClient.dll comes into picture.&lt;br /&gt;
Open test Architecture is provided to access QC&#39;s database without using its GUI.&lt;br /&gt;
The code block below populates the bug object,posts it in QC&#39;s DB and also sends email to the concerned person.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;brush: csharp&quot;&gt;public void GetDistinctRowsForQC()
{
DataContext dataContext = new DataContext();

var qc = (from details in dataContext.TableName
where details.RunId == _testRunID
select details);

QCReporting.LogErrorInQualityCenter(qc.Take(2));
}


internal static void LogErrorInQualityCenter(IQueryable&lt;namespace.tablename&gt; qc)
{
TDConnectionClass QCConnection = new TDConnectionClass();
QCConnection.InitConnectionEx(&quot;http://qualitycenter/qcbin/&quot;);
QCConnection.Login(&quot;UserID&quot;, string.Empty);
QCConnection.Connect(&quot;C&quot;, &quot;C&quot;);

BugFactory BFactory = (BugFactory)QCConnection.BugFactory;
Customization field = (Customization)QCConnection.Customization;
CustomizationFields f = (CustomizationFields)field.Fields;

List list = f.get_Fields(&quot;Bug&quot;);
Dictionary&lt;string,string&gt; columnnames = new Dictionary&lt;string,string&gt;();
foreach (CustomizationField fieldd in list)
{
if(!columnnames.ContainsKey(fieldd.UserLabel))
columnnames.Add(fieldd.UserLabel,fieldd.ColumnName);
}
int i = 0;
foreach(var q in qc)
{
IBug bug = (IBug)BFactory.AddItem(i);
bug.AutoPost = false;
bug.AssignedTo = &quot;UserID&quot;;
bug.DetectedBy = Environment.UserName;
bug.Priority = &quot;1-Low&quot;;
bug.Status = &quot;New&quot;;
bug.Summary = q.ErrorMessage;
bug.Project = &quot;CCC&quot;;
bug[&quot;BG_Reproducible&quot;] = &quot;Y&quot;;
bug[&quot;BG_Severity&quot;] = &quot;2-Medium&quot;;
bug[columnnames.Where(P =&gt; P.Key == &quot;Issue Type&quot;).Select(p =&gt; p.Value).FirstOrDefault()] = &quot;Defect&quot;;
bug[columnnames.Where(P =&gt; P.Key == &quot;SDLC Phase&quot;).Select(p =&gt; p.Value).FirstOrDefault()] = &quot;2-Project Execution&quot;;
bug[columnnames.Where(P =&gt; P.Key == &quot;Detected on Date&quot;).Select(p =&gt; p.Value).FirstOrDefault()] = DateTime.Now;
bug[columnnames.Where(P =&gt; P.Key == &quot;Application Group&quot;).Select(p =&gt; p.Value).FirstOrDefault()] = &quot;Cu&quot;;
bug[columnnames.Where(P =&gt; P.Key == &quot;Application Sub Group&quot;).Select(p =&gt; p.Value).FirstOrDefault()] = &quot;CA&quot;;
bug[columnnames.Where(P =&gt; P.Key == &quot;Project Number&quot;).Select(p =&gt; p.Value).FirstOrDefault()] = &quot;C&quot;;
bug[columnnames.Where(P =&gt; P.Key == &quot;Environment&quot;).Select(p =&gt; p.Value).FirstOrDefault()] = &quot;QA&quot;;
bug[columnnames.Where(P =&gt; P.Key == &quot;Detector Name&quot;).Select(p =&gt; p.Value).FirstOrDefault()] = new DirectoryEntry(&quot;WinNT://p/&quot; + Environment.UserName + &quot;&quot;).Name;
bug[columnnames.Where(P =&gt; P.Key == &quot;Assigned Name&quot;).Select(p =&gt; p.Value).FirstOrDefault()] = new DirectoryEntry(&quot;WinNT://p/&quot; + Environment.UserName + &quot;&quot;).Name;
bug[columnnames.Where(P =&gt; P.Key == &quot;Verified By&quot;).Select(p =&gt; p.Value).FirstOrDefault()] = &quot;UserID&quot;;
bug[columnnames.Where(P =&gt; P.Key == &quot;Verifier Name&quot;).Select(p =&gt; p.Value).FirstOrDefault()] = new DirectoryEntry(&quot;WinNT://p/&quot; + Environment.UserName + &quot;&quot;).Name;
bug[columnnames.Where(P =&gt; P.Key == &quot;ReopenCountField&quot;).Select(p =&gt; p.Value).FirstOrDefault()] = &quot;0&quot;;
bug[columnnames.Where(P =&gt; P.Key == &quot;Source&quot;).Select(p =&gt; p.Value).FirstOrDefault()] = &quot;Test&quot;;
bug[columnnames.Where(P =&gt; P.Key == &quot;Reopen Count&quot;).Select(p =&gt; p.Value).FirstOrDefault()] = &quot;0&quot;;
bug.Post();

bug.Mail(&quot;UserID&quot;, &quot;UserID&quot;, 4, &quot;New Defect Notification&quot;, q.ErrorMessage);
i++;
}
QCConnection.DisconnectProject();
QCConnection.Logout();
}
&lt;/pre&gt;</content><link rel='replies' type='application/atom+xml' href='http://krishnapotluri.blogspot.com/feeds/3743473144926357285/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://krishnapotluri.blogspot.com/2010/07/otaclient-qc-reporting-with-c.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/3743473144926357285'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/162532840988979012/posts/default/3743473144926357285'/><link rel='alternate' type='text/html' href='http://krishnapotluri.blogspot.com/2010/07/otaclient-qc-reporting-with-c.html' title='OTAClient + QC reporting with C#'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry></feed>