<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rajeev Shukla on Medium]]></title>
        <description><![CDATA[Stories by Rajeev Shukla on Medium]]></description>
        <link>https://medium.com/@mail2rajeevshukla?source=rss-20dfb10b2322------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*0hJ2m5Ba3hnONI2v.</url>
            <title>Stories by Rajeev Shukla on Medium</title>
            <link>https://medium.com/@mail2rajeevshukla?source=rss-20dfb10b2322------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:41:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mail2rajeevshukla/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Mastering Synchronization in Goroutines: A Simple Guide to Concurrency Control in Go]]></title>
            <link>https://medium.com/swlh/mastering-synchronization-in-goroutines-a-simple-guide-to-concurrency-control-in-go-0e0ede1559fa?source=rss-20dfb10b2322------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e0ede1559fa</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Rajeev Shukla]]></dc:creator>
            <pubDate>Wed, 13 Nov 2024 17:12:06 GMT</pubDate>
            <atom:updated>2024-11-13T17:12:06.050Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*63IyAS2zEzelOVCv" /></figure><h3>Introduction</h3><p>In Go, goroutines let us run functions concurrently, making our code faster and more efficient. But with great concurrency comes great responsibility! When multiple goroutines try to access the same data simultaneously, we risk data races and unexpected bugs. That’s where synchronization comes in—it’s a way to control access and ensure only one goroutine changes shared data at a time.</p><p>In this guide, we’ll walk through some essential tools for synchronization in Go, using straightforward examples with minimal code. By the end, you’ll know how to use sync.Mutex, sync.WaitGroup, and channels to keep your goroutines safe and organized.</p><p>If you want to read about the internals of goroutines and how go scheduler schedules multiple goroutines to os threads please go through this blog</p><p><a href="https://medium.com/@mail2rajeevshukla/unlocking-the-power-of-goroutines-understanding-gos-lightweight-concurrency-model-3775f8e696b0">Unlocking the Power of Goroutines: Understanding Go’s Lightweight Concurrency Model</a></p><h4>1. Syncing Goroutines with sync.Mutex</h4><p>A mutex, short for “mutual exclusion,” is like a lock on a shared resource. When one goroutine locks it, no other goroutine can access it until it’s unlocked. This ensures only one goroutine changes data at any time.</p><p>Let’s look at an example where we protect a counter from concurrent updates:</p><pre>package main<br><br>import (<br> “fmt”<br> “sync”<br>)<br><br>func main() {<br>   var counter int<br>   var mu sync.Mutex<br>   var wg sync.WaitGroup<br><br>  for i := 0; i &lt; 5; i++ {<br>       wg.Add(1)<br>       go func() {<br>          defer wg.Done()<br>          mu.Lock() // Locking the counter<br>          counter++<br>          mu.Unlock() // Unlocking after update<br>       }()<br>  }<br><br>  wg.Wait() // wait for all goroutines to finish. <br>  fmt.Println(“Final Counter:”, counter)<br>}</pre><p>In this example:</p><ul><li>We create a sync.Mutex to protect the counter.</li><li>Each goroutine locks the counter, updates it, and then unlocks it.</li><li>The sync.WaitGroup ensures the main function waits for all goroutines to finish before printing the result.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*yWpXLoXhl6UAiMHDL_Myhg.png" /><figcaption>5 Gorutine waiting to enter in the critical section to update the counter.</figcaption></figure><h3>2. Coordinating Goroutines with sync.WaitGroup</h3><p>A sync.WaitGroup lets us wait for multiple goroutines to complete. It’s helpful when you have several tasks to run concurrently and must wait for them all before moving on.</p><p>Here’s a simple example:</p><pre>package main <br>import (<br> “fmt”<br> “sync”<br>) <br> <br> func main() {<br>     var wg sync.WaitGroup <br>     // Creating multiple goroutines<br>     for i := 1; i &lt;= 3; i++ {<br>         wg.Add(1)<br>         go func(id int) {<br>           defer wg.Done()<br>           fmt.Printf(&quot;Goroutine %d working…\n&quot;, id)<br>         }(i)<br>     } <br>     wg.Wait()<br>     fmt.Println(&quot;All goroutines finished!&quot;)<br>  }</pre><p>In this code:</p><ul><li>wg.Add(1) increases the wait count each time a new goroutine is launched.</li><li>Each goroutine calls wg.Done() when it finishes, reducing the count.</li><li>wg.Wait() makes the main function wait until the count reaches zero.</li></ul><h3>3. Communicating Between Goroutines with Channels</h3><p>Channels in Go let goroutines communicate by passing data without using shared variables. Channels provide a built-in way to synchronize and transfer data between goroutines.</p><p>Here’s an example of using a channel to update a counter safely:</p><pre>package main<br>import (<br> “fmt”<br>)<br>func main() {<br> counter := make(chan int)<br> done := make(chan bool)<br>// Goroutine to update counter<br> go func() {<br> count := 0<br> for i := 0; i &lt; 5; i++ {<br> count++<br> }<br> counter &lt;- count<br> done &lt;- true<br> }()<br>    &lt;-done // Wait for completion<br>   fmt.Println(“Final Counter:”, &lt;-counter)<br>}</pre><p>In this example:</p><ul><li>The goroutine counts up and sends the result to the counter channel.</li><li>The main goroutine waits for the done signal, ensuring that it doesn’t print the final count before the counting finishes.</li></ul><h3>4. Ensuring One-Time Execution with sync.Once</h3><p>Sometimes, you might have a piece of code that you only want to run once, no matter how many goroutines are involved. This is common with setup functions or tasks that should happen only once, like initializing a resource. Go’s sync.Once provides a simple way to ensure that a function is executed only once, even if multiple goroutines try to run it at the same time.</p><p>Here’s an example using sync.Once to initialize a configuration:</p><pre>package main<br>import (<br> “fmt”<br> “sync”<br>) <br>func main() {<br> var once sync.Once<br> var wg sync.WaitGroup<br>setup := func() {<br> fmt.Println(“Initializing configuration…”)<br> }  <br><br>for i := 0; i &lt; 3; i++ {<br> wg.Add(1)<br> go func(id int) {<br> defer wg.Done()<br> fmt.Printf(“Goroutine %d is calling setup.\n”, id)<br> once.Do(setup)<br> }(i)<br> }<br>  wg.Wait()<br> fmt.Println(“All goroutines finished.”)<br>}</pre><p>In this example:</p><ul><li>once.Do(setup) makes sure the setup the function runs only once, even though multiple goroutines are calling it.</li><li>sync.Once is ideal for initialization tasks or any code that should only run once, preventing race conditions and redundant executions.</li></ul><h3>Summary</h3><p>Synchronization in Go is essential for safe and effective concurrency. Using tools like sync.Mutex, sync.WaitGroup, channels and sync.Once help you control goroutines and avoid data races. Each of these has its strengths:</p><ul><li><strong>Mutex</strong> is perfect for protecting shared data.</li><li><strong>WaitGroup</strong> makes it easy to wait for multiple goroutines to complete.</li><li><strong>Channels</strong> provide safe communication between goroutines.</li><li><strong>sync.Once</strong> for one-time initialization</li></ul><p>With these basics in hand, you’re ready to handle concurrent tasks confidently in Go. Happy coding!</p><p>If you find this blog helpful, don’t forget to <strong>clap</strong> 👏 or <strong>follow</strong> on Medium. It’ll keep me motivated to write more such content in the future. Thanks for your support! 🙌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e0ede1559fa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/mastering-synchronization-in-goroutines-a-simple-guide-to-concurrency-control-in-go-0e0ede1559fa">Mastering Synchronization in Goroutines: A Simple Guide to Concurrency Control in Go</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Updating Lambda Configurations Without a Restart: A Guide to Dynamic Environment Refresh Using AWS…]]></title>
            <link>https://aws.plainenglish.io/updating-lambda-configurations-without-a-restart-a-guide-to-dynamic-environment-refresh-using-aws-23df341002a8?source=rss-20dfb10b2322------2</link>
            <guid isPermaLink="false">https://medium.com/p/23df341002a8</guid>
            <category><![CDATA[configuration-management]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[parameter-store]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[sns]]></category>
            <dc:creator><![CDATA[Rajeev Shukla]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 03:36:14 GMT</pubDate>
            <atom:updated>2024-11-06T09:44:48.470Z</atom:updated>
            <content:encoded><![CDATA[<h3>Updating Lambda Configurations Without a Restart: A Guide to Dynamic Environment Refresh Using AWS EventBridge and SNS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QJYxka9liOjSXNLO5ikusw.png" /></figure><h3>Problem Statement</h3><p>In serverless applications, Lambda functions are often deployed with environment configurations stored in AWS SSM Parameter Store. However, when configurations are updated, Lambda functions typically need a restart to load the new values. This creates a limitation, especially for live applications, where minimizing downtime is crucial. Manually restarting or redeploying Lambda functions to load new configurations can be both inefficient and operationally costly.</p><p>To address this, we’ll explore how to use AWS EventBridge, SNS, and a “fan-out” pattern to dynamically refresh Lambda configurations in real-time without requiring a restart. This method scales with concurrent Lambda instances, ensuring each “warm” copy receives updates automatically.</p><h3>Solution Summary</h3><p>Using EventBridge and SNS, we’ll build a solution that:</p><ol><li>Detects changes in SSM parameters for Lambda configuration.</li><li>Triggers an SNS notification that fans out to all running Lambda instances.</li><li>Each instance receives an SNS event, triggering a refreshConfig() function to reload configuration values directly from SSM or via the SNS payload.</li></ol><p>Let’s dive into the step-by-step process to set up this solution.</p><h3>Step 1: Define an EventBridge Rule to Monitor SSM Parameter Changes</h3><p>Start by creating an EventBridge rule that will detect changes in SSM parameters associated with Lambda configurations. You’ll configure it to listen for specific SSM paths, such as /mylambdaconfig/&lt;anychange&gt;, and then trigger a fan-out notification.</p><ol><li>In the AWS Console, navigate to <strong>EventBridge</strong>.</li><li>Go to <strong>Rules</strong> &gt; <strong>Create Rule</strong>.</li><li>Set the rule name, e.g., LambdaConfigChangeRule, and provide an appropriate description.</li><li>Define the <strong>Event Source</strong> to monitor changes in SSM parameters.</li><li>Specify the SSM path to watch, e.g., /mylamdaconfig/&lt;anychange&gt;. where mylambdaconfig is the root path that you would define under which you have all the key values created for your lambda.</li><li>For <strong>Target</strong>, choose <strong>SNS Topic</strong> and link it to the SNS topic created in Step 2.</li></ol><p>Now, EventBridge is configured to detect any configuration changes and automatically send events to SNS.</p><h3>Step 2: Create an SNS Topic for Fan-Out Notifications</h3><p>SNS will be used as the fan-out mechanism to ensure that each instance of the Lambda function receives the event when there’s a configuration change.</p><ol><li>Go to <strong>SNS</strong> in the AWS Console.</li><li>Create a new <strong>Topic</strong>.</li></ol><ul><li>Name the topic something descriptive, like LambdaConfigUpdateTopic.</li><li>Choose <strong>Standard</strong> as the topic type (since standard topics support fan-out).</li></ul><ol><li>Save the SNS topic and note its <strong>ARN</strong>; you’ll need it to configure EventBridge.</li></ol><h4>Subscribe Each Lambda Instance to the SNS Topic</h4><p>By subscribing each Lambda instance to the topic, SNS can send a copy of each configuration update event to all active Lambda instances.</p><ol><li>In the <strong>SNS Console</strong>, go to <strong>Subscriptions</strong> &gt; <strong>Create Subscription</strong>.</li><li>Choose the SNS topic you created (LambdaConfigUpdateTopic).</li><li>Select <strong>AWS Lambda</strong> as the protocol and select the Lambda function that should receive the updates.</li><li>Confirm the subscription.</li></ol><h3>Step 3: Configure the Lambda Function to Handle Configuration Refreshes</h3><p>To handle the event from SNS, each Lambda instance should include a function, e.g., refreshConfig(), to reload the configuration from SSM Parameter Store. The function can be triggered by the SNS event itself, prompting each instance to check for updated values.</p><p>Below is a Go-based handler example that demonstrates how each Lambda instance can listen for an SNS event, and then trigger a config refresh.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*DdFCz9D5fH9hvJzpdSfLBA.png" /></figure><h4>Below is the example code —</h4><pre>package main<br><br>import (<br> “context”<br> “encoding/json”<br> “log”<br>“github.com/aws/aws-lambda-go/events”<br> “github.com/aws/aws-lambda-go/lambda”<br>)<br><br>// EventBridgeEvent structure to handle incoming messages<br>type EventBridgeEvent struct {<br> Action string `json:”action”`<br>}<br><br>// refreshConfig function loads the latest configuration from SSM<br>func refreshConfig() {<br>   log.Println(“Reloading configuration from SSM…”)<br>   // Code to fetch and update the configuration from SSM Parameter Store<br> }<br><br>// Lambda handler that processes SNS events<br>func handler(ctx context.Context, snsEvent events.SNSEvent) error {<br>     for _, record := range snsEvent.Records {<br>     var event EventBridgeEvent<br>     if err := json.Unmarshal([]byte(record.SNS.Message), &amp;event); err != nil {<br>     log.Printf(“Failed to parse SNS message: %v”, err)<br>     continue<br>     }<br><br>// Check for configuration refresh action<br>     if event.Action == “refreshConfig” {<br>     refreshConfig()<br>     }<br>  }<br> return nil<br>}<br><br><br>func main() {<br> lambda.Start(handler)<br>}</pre><h3>Step 4: Optimize Config Retrieval (Optional)</h3><h4>Option 1: Retrieve Config Directly from SSM</h4><p>Each Lambda instance can call the SSM Parameter Store directly for updated values in the refreshConfig() function. This maintains security by keeping sensitive data out of the SNS payload.</p><h4>Option 2: Embed Config Changes in SNS Payload</h4><p>Alternatively, to reduce the load on SSM, the SNS message could contain configuration values directly. However, be cautious with this approach if sensitive data, like secrets, is involved. For better security, limit the information in the payload to non-sensitive values.</p><h3>Conclusion</h3><p>By using AWS EventBridge, SNS, and SSM, you can create a scalable, real-time solution to refresh Lambda configurations across all warm instances without redeployment. This approach is secure, and efficient, and helps ensure your Lambda functions always operate with the latest configurations.</p><p><strong>Key Takeaways:</strong></p><ul><li>EventBridge triggers changes automatically.</li><li>SNS fans out the event to each Lambda instance.</li><li>Lambda instances independently reload configurations with minimal downtime.</li></ul><p>This solution can be especially useful for serverless applications with high availability requirements. It minimizes operational overhead and improves responsiveness, keeping your Lambda functions up-to-date without manual intervention.</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23df341002a8" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/updating-lambda-configurations-without-a-restart-a-guide-to-dynamic-environment-refresh-using-aws-23df341002a8">Updating Lambda Configurations Without a Restart: A Guide to Dynamic Environment Refresh Using AWS…</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Power of Goroutines: Understanding Go’s Lightweight Concurrency Model]]></title>
            <link>https://medium.com/swlh/unlocking-the-power-of-goroutines-understanding-gos-lightweight-concurrency-model-3775f8e696b0?source=rss-20dfb10b2322------2</link>
            <guid isPermaLink="false">https://medium.com/p/3775f8e696b0</guid>
            <category><![CDATA[golang-development]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <dc:creator><![CDATA[Rajeev Shukla]]></dc:creator>
            <pubDate>Sun, 03 Nov 2024 22:27:13 GMT</pubDate>
            <atom:updated>2024-11-13T17:22:48.578Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Golang’s lightweight concurrency model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oqL6WvxkDNW5MbeDTMTIAg.png" /><figcaption>Goroutine internals</figcaption></figure><h3>Introduction</h3><p>Go routines are one of Go’s core features for handling concurrency like Java Threads. Unlike traditional, relatively heavy threads, goroutines are lightweight and managed by the Go runtime, allowing you to run hundreds or thousands of them simultaneously without significant overhead.</p><h3>What Are Goroutines?</h3><p>A goroutine is a function or method that runs concurrently with other goroutines in the same address space. When a goroutine is created, the Go runtime scheduler manages it independently, allocating resources and switching execution between goroutines as needed. They are incredibly efficient because:</p><ul><li>Goroutines have a small initial stack size (typically around 2 KB).</li><li>Go runtime manages stack growth as needed, unlike threads, which require a pre-allocated stack.</li><li>Goroutines are scheduled by the Go runtime rather than by the OS, which helps reduce the overhead of context switching.</li></ul><h4>Starting a Goroutines</h4><pre>package main<br><br>import (<br> “fmt”<br> “time”<br>) <br><br><br>func printMessage(msg string) {<br> fmt.Println(msg)<br>} <br><br>func main() { <br>// keyword go added in front of calling method will run the function in a sparate excution flow.<br> go printMessage(“Hello, Goroutine!”)<br>// Internally Above will be part of &#39;run queue&#39; which is managed by Go Scheduler<br> fmt.Println(“Main function message”)<br> time.Sleep(time.Second) // waiting for goroutine to finish. <br>}<br></pre><h3>How Goroutines Work Internally</h3><p>Goroutines are managed by the Go runtime scheduler, which maps multiple goroutines onto a small number of OS threads. This is achieved using a model called <em>M scheduling</em>, where M goroutines are <strong>multiplexed </strong>onto N OS threads.</p><h4>Key components involved:</h4><ol><li><strong>Goroutine (G)</strong>: These represent individual functions or tasks that run concurrently within a Go application.</li><li><strong>Machine (M)</strong>: This represents an OS thread that is capable of executing goroutines. Each thread has its associated CPU state, memory, and stack, as managed by the OS.</li><li><strong>Processor (P)</strong>: A logical resource that holds a “run queue” of goroutines that need execution. Processors are the bridge between goroutines and OS threads, with a one-to-one mapping to CPU cores by default (controlled by the GOMAXPROCS environment variable). The scheduler assigns each P to an OS thread (M), which then executes goroutines from P’s run queue.</li></ol><p>When you run a Go program, Go initializes a fixed number of processors (which defaults to the number of logical CPUs). Each processor is attached to a thread, which allows the Go scheduler to manage goroutines without needing OS intervention for context switching.</p><h3>How Go Scheduler Multiplexes M Goroutines onto N OS Threads</h3><ol><li><strong>Run Queue and Locality</strong>:</li></ol><ul><li>Each processor (P) maintains a local run queue of goroutines.</li><li>When a goroutine is created, it is placed in a P’s run queue.</li><li>The scheduler will select a goroutine from the queue of a P and assign it to an available OS thread (M) associated with that P for execution.</li><li>If the local run queue is empty, a P can &quot;steal&quot; goroutines from the run queues of other Ps to ensure that processors and OS threads are kept busy.</li></ul><p><strong>2. Lightweight Stack Management</strong>:</p><ul><li>Each goroutine starts with a small stack (about 2 KB), which the Go runtime dynamically grows and shrinks based on need, allowing hundreds of thousands of goroutines to run without exhausting system memory.</li><li>This stack resizing is managed by the Go runtime and avoids the fixed-size stacks typical of OS threads, making goroutines far more memory-efficient than threads.</li></ul><p><strong>3. Blocking and Non-Blocking Operations</strong>:</p><ul><li>When a goroutine performs a blocking operation (such as I/O or a sleep), it would normally block its OS thread as well.</li><li>The Go runtime, however, handles this by “parking” the blocked goroutine and then detaching the OS thread (M) from the processor (P).</li><li>The processor is then free to attach to another thread and pick up another goroutine from the run queue, allowing the system to maintain high concurrency without being blocked by individual goroutines.</li><li>Once the blocking operation completes, the parked goroutine is moved back into the run queue to be rescheduled.</li></ul><p><strong>4. Goroutine Preemption</strong>:</p><ul><li>Starting with Go 1.14, the Go scheduler introduced preemptive scheduling. This allows the scheduler to stop long-running goroutines at safe points to ensure that all goroutines get a fair share of CPU time, preventing one goroutine from monopolizing a thread.</li><li>The preemption points are added at regular intervals, usually at function calls or loop-back edges, which allows for more balanced scheduling without explicit control from the programmer.</li></ul><p><strong>5. Work Stealing</strong>:</p><ul><li>Each processor (P) operates with its local run queue for goroutines, but when it has no tasks to process, it can &quot;steal&quot; goroutines from the run queues of other processors.</li><li>This mechanism helps balance workload across all available processors, maximizing CPU usage and ensuring that all goroutines are actively progressing.</li></ul><p>In conclusion, Go’s innovative goroutine model, combined with its efficient M scheduling, enables developers to handle high levels of concurrency with ease and minimal resource overhead. By understanding and leveraging these features, you can build scalable applications that perform exceptionally well under load.</p><p>Check out my next blog how to Control Concurrency in Go</p><p><a href="https://medium.com/@mail2rajeevshukla/mastering-synchronization-in-goroutines-a-simple-guide-to-concurrency-control-in-go-0e0ede1559fa">Mastering Synchronization in Goroutines: A Simple Guide to Concurrency Control in Go</a></p><p>Happy Learning 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3775f8e696b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/unlocking-the-power-of-goroutines-understanding-gos-lightweight-concurrency-model-3775f8e696b0">Unlocking the Power of Goroutines: Understanding Go’s Lightweight Concurrency Model</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Spring Security tips before going into production]]></title>
            <link>https://medium.com/developervisits/basic-spring-security-tips-before-going-into-production-89d6bbca9eb3?source=rss-20dfb10b2322------2</link>
            <guid isPermaLink="false">https://medium.com/p/89d6bbca9eb3</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-security]]></category>
            <dc:creator><![CDATA[Rajeev Shukla]]></dc:creator>
            <pubDate>Thu, 17 Feb 2022 21:32:13 GMT</pubDate>
            <atom:updated>2022-02-19T20:46:15.453Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yc7OxJyx7VWruXIEdK__og.png" /></figure><h3><strong>Introduction</strong></h3><p>In general, web APIs are exposed to the Internet, so they need security mechanisms to prevent abuse, protect sensitive data, and ensure that only authenticated and authorized users can access them. Thus, web API security is crucial.</p><p>Below are some of the basic points that would help you to start the basic security checks —</p><h4>1. Url protection</h4><ul><li>Allow access to everyone to a given URL</li><li>Secure URL based on roles.</li><li>Secure URL based on multiple roles.</li></ul><p>.antMatchers(“/register”,”/login”,”/user”,”/admin”)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18629116a524c8cf66b1ab4ad127495d/href">https://medium.com/media/18629116a524c8cf66b1ab4ad127495d/href</a></iframe><p>access(“hasRole(‘ADMIN’) and hasIpAddress(‘123.123.123.123’)”)</p><p>Use the access method to use SPEL for more complicated security.</p><h4>2. CSRF Token</h4><p>A CSRF attack occurs when a website uses cookies for any reason and a malicious script is executed on the client/user side to perform any task such as fund transfer or password change without the user’s knowledge.</p><p>REST applications are immune to CSRF attacks if they do not use cookies. So, <strong>no cookies = no CSRF</strong>.</p><p>Usually, most of the people disable(in demo code) because they won’t be able to call /logout URL with the GET method as it requires you to submit it via POST with _csrf token. Check more details about CSRF <a href="https://owasp.org/www-community/attacks/csrf">here</a></p><h4><strong>3. Session Fixation Attack</strong></h4><p>This is the type of attack where one can steal your current session by offering their URL of the same website and append JSESSIONID it into the URL, with the URL rewrite approach. Spring Security Framework has taken care of this by default and it migrates the session once the user logs in. The corresponding configuration would be -</p><pre>http.sessionManagement()<br>  .sessionFixation().migrateSession()</pre><blockquote>You should use above only when you are using session based application. For REST based application this might not be needed.</blockquote><h4><strong>4. Securing session cookie</strong>:</h4><p>The malicious script can read your cookie information from the browser end so you need to make sure that your cookie is secured and accessible by server-side code by making them HttpOnly. For that, you can add the below config in your application.properties -</p><pre>server.servlet.session.cookie.http-only=true</pre><h4>5. <strong>Running your app on Https:</strong></h4><p>Make sure that you use HTTPS in production and in that case you can force your cookies to travel over HTTPS protocol only by adding the below config in your application.properties .</p><pre>server.servlet.session.cookie.secure=true</pre><p>and to force HTTPS connection add below lines in configure() method (this won’t be enough though because you have to get your public/private key setup also using the key tool)</p><pre>http.requiresChannel().requiresSecure();</pre><h4>6. <strong>Applying CSP:</strong></h4><p>User Content security policy to avoid any <a href="https://owasp.org/www-community/attacks/xss/">XSS attacks.</a> Spring security by default provides various security headers. But it does not add Content security policy headers you can add them in your security config file like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f9aca8dfafb239d4a6a5df70bae020f/href">https://medium.com/media/8f9aca8dfafb239d4a6a5df70bae020f/href</a></iframe><h4><strong>7. Password hashing</strong>:</h4><p>Password hashing is a one-way function that is impossible to decrypt. Keeping the password in open plain text is open for anyone to read. This can pose a great security threat as anyone in your organization or outside who can gain the access to DB can read the password. It is a must-have thing that everyone should follow.</p><p>Spring security provides various algorithms to support password hashing.</p><p>bcrypt password encoder by default.</p><pre>PasswordEncoderFactories.createDelegatingPasswordEncoder()</pre><p>Or use other also supported</p><pre>@Bean<br>public PasswordEncoder <strong>encoder</strong>() {<br>    return new BCryptPasswordEncoder();<br>}</pre><p><a href="https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/crypto/factory/PasswordEncoderFactories.html">Check here</a> for more sets of algorithms supported by this factory class.</p><h4>8. Enabling method level security</h4><p>Spring Security supports <strong>“Method Level Security”</strong> by using AOP. @PreAuthorized can be used to secure methods at the controller layer. This is similar to URL protection but the difference is that @PreAuthorized triggers when your controller code is about to execute. Also, you can use the SPEL expression to allow or deny requests based on security attributes such as, if the request is read_only and then update or delete operations should be rejected.</p><p>Also, it can help you to organize the security-related definitions within the code adjacent to the controller definitions.</p><h4><strong>9. Securing your application.properties</strong></h4><p>Security should be applied not only from outside but should also be protected from inside as well. Like encryption and decryption of database passwords or any other config passwords. Please check my other post on how you can secure the application.properties in spring boot.</p><p><a href="https://medium.com/@mail2rajeevshukla/hiding-encrypting-database-password-in-the-application-properties-34d59fe104eb">Hiding/Encrypting database password in the application.properties</a></p><h4>10. Prevent DDOS attack</h4><p>This should be addressed by adjusting several security parameters such as session timeouts, security header checks, memory leak handling, and POST request timeouts to ensure that no one posts a large request payload, among others. To counteract such security threats, you’ll need to put in some effort. There are cloud providers which prevent such type attacks such as AWS <a href="https://aws.amazon.com/shield/">Shield</a> or <a href="https://cloud.google.com/armor">Google Cloud armor</a></p><h4>11. What else we can do ??</h4><p>Security isn’t restricted to the topics we’ve discussed thus far. These considerations may not be sufficient when working with mission-critical systems, such as those in the finance industry, where security is paramount. However, these ideas might serve as a good starting point for addressing some of the more fundamental and sophisticated issues.</p><p>Occasionally, addressing a CVE (Common Vulnerability and Exposure) error may pose a security risk. You may need to upgrade the underlining library in this situation, as the library has security vulnerabilities that you may or may not be aware of. Do you remember the <a href="https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-45105">log4j </a>security crisis? 😊</p><p>Thank you for your time. Follow me for more such updates.😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89d6bbca9eb3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/developervisits/basic-spring-security-tips-before-going-into-production-89d6bbca9eb3">Basic Spring Security tips before going into production</a> was originally published in <a href="https://medium.com/developervisits">Developervisits</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Passwords Using HashiCorp Vault and Spring-Cloud]]></title>
            <link>https://medium.com/swlh/securing-passwords-using-hashicorp-vault-in-spring-6c18da62a42e?source=rss-20dfb10b2322------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c18da62a42e</guid>
            <category><![CDATA[vault]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-boot-cloud]]></category>
            <dc:creator><![CDATA[Rajeev Shukla]]></dc:creator>
            <pubDate>Sun, 26 Jul 2020 21:13:38 GMT</pubDate>
            <atom:updated>2020-07-28T20:55:16.324Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*MOT8w04-i5-kjGcliPx2PQ.png" /></figure><h3>Introduction</h3><p>An application should not be only secured from outsiders in this world, it should be secured from insiders as well. Recall those days when you hesitate to check-in secrete DB password into version control or email Id password which might be used for sending emails to end-user.</p><p>In my earlier post, I have written how to secure database properties using java simplified encryption.</p><p><a href="https://medium.com/@mail2rajeevshukla/hiding-encrypting-database-password-in-the-application-properties-34d59fe104eb">Hiding/Encrypting database password in the application.properties</a></p><p>In this post, we are going to learn how to secure properties using HashiCorp Value and spring which is the most secure way you can think of securing properties.</p><h3>HashiCorp Vault setup on local</h3><h4>1. Installation</h4><p>I am installing the HashiCorp vault on <strong>Ubuntu 20.20.</strong> Just in case if you are using different OS please follow <a href="https://learn.hashicorp.com/vault/getting-started/install">this link</a> to install and feel free to skip the installation section.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f14329bd2ec3c02c15c19a27d8cef173/href">https://medium.com/media/f14329bd2ec3c02c15c19a27d8cef173/href</a></iframe><p>After installing vault when you run $vault you should see below output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*2MBNwcZNWaCbm_HRbvraZg.png" /></figure><blockquote>Note: Knowledge of Vault internals is not required to use Vault. This installation usually done by system administrator in the orgnization. Though as a developer you can learn if you interested much about internals <a href="https://www.vaultproject.io/docs/internals/architecture">here</a>. We will only see basic things needed to get going.</blockquote><h4>2. Starting vault server on localhost</h4><p>To start the vault server you need to pass config information on the startup. For that copy below config and save it into a file say vaultConfig.hcl.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f93b5274eca56616750dd9dc047f75a/href">https://medium.com/media/7f93b5274eca56616750dd9dc047f75a/href</a></iframe><blockquote><strong><em>Note:</em></strong><em> Don’t use above configuration in production. Also, </em>during installation vault.hcl config file created on the path /etc/vault.d/vault.hcl (on ubuntu) but it has TL S/SSL configs automatically written in it to access Vault server over https which is out of the scope of this post. Also change path in above configuration according to your file system(Window/Mac).</blockquote><p>$ sudo vault server -config /etc/vault.d/vault.hcl</p><p>Now once the server is started one a new terminal and set an environment variable for the vault address so that the vault client could use it. (On windows set it using environment variable)</p><p># export VAULT_ADDR=<a href="http://127.0.0.1:8200/">http://127.0.0.1:8200</a></p><h4>3. Initialize Vault</h4><p>Once the vault server is started, for the very first time we need to initialize the vault and generate two different types of tokens one for login and one for <strong>Seal/Unseal</strong> the Vault. We have two ways to generate these tokens.</p><ul><li>Using the command line</li><li>Using UI (By accessing <a href="http://127.0.0.1:8200)">http://127.0.0.1:8200)</a></li></ul><p><strong>3.1 Command line approach</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87e18007c95ce844693ab2d4e2b6ebe4/href">https://medium.com/media/87e18007c95ce844693ab2d4e2b6ebe4/href</a></iframe><p>when you write vault operator init it creates two different tokens.</p><ol><li>The master key portion</li><li>Root Token(For authentication)</li></ol><p><strong>Key share and Key threshold</strong></p><p>When a Vault server is started, it starts in a <a href="https://www.vaultproject.io/docs/concepts/seal.html"><strong><em>sealed</em></strong></a> state and it does not know how to decrypt data. Before any operation can be performed on the Vault, it must be unsealed. Unsealing is the process of constructing the master key necessary to decrypt the data encryption key.</p><p>Once a Vault node is unsealed, it remains unsealed until —</p><ul><li>Server is restarted</li><li>any exception occurred</li><li>or manually resealed</li></ul><p><strong>Key shares: </strong>HashiCorp vault uses the master key to unseal vault and that master key can be split into any number of separate tokens. <strong>Key shares parameter </strong>ask you to enter<strong> </strong>a number and the master key will split into that many numbers of the token.</p><p><strong>Key threshold: </strong>Number of key shares required to construct the master key to unseal the vault.</p><p>We can pass these params during initialization though we didn’t as it uses default key shares 5 and threshold as 3. Below is how we can pass during initialization.</p><p># vault operator init -key-shares=5 -key-threshold=2</p><p>it generates 5 shared keys(-key-shares=5) out of which at least any of the two key combinations(-key-threshold=2) will be used to unseal the vault.</p><p><strong>3.2 UI approach</strong></p><p>We can also initialize vault through UI if it is enabled while starting up the vault server. (Check ui=true in vaultConfig.hcl)</p><p>You can access <a href="http://localhost:8200/">http://localhost:8200</a> below is the page you would see for the first time for the token generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*C1MSvnjlFVQTJMkv23qxKQ.png" /><figcaption>Vault UI for the first time</figcaption></figure><p>In UI, it asks for you to enter <strong>key shares</strong> and <strong>key threshold </strong>parameters. As these are mandatory (but not in the command line) once you enter key shares and key threshold it will generate all the needed token and will ask you to download it.</p><h4>Unseal vault</h4><p>Vault will decrypt the key and serve the request only when it is unsealed. So before using it we need to unseal it.</p><ol><li><strong>Command-line approach</strong></li></ol><p># vault operator unseal &lt;token 1&gt;<br> # vault operator unseal &lt;token 2&gt;<br> # vault operator unseal &lt;token 3&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*JTymvlnk7WcUHpnqVmqf_w.png" /><figcaption>Vault unsealing after entering all keys</figcaption></figure><p><strong>2. UI approach</strong></p><p>Access <a href="http://localhost:8200/">http://localhost:8200</a> in your browser</p><ol><li>You have to sign in to the vault server first by using to initial root token which was generated earlier.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*5HyF1_nqnZAT9mBBTguNvQ.png" /></figure><p>2. Then Unseal your vault by using key shares -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*epsqCtdJkID_NZ7YJX3I6A.png" /></figure><p>Now it is time to add a secret in the vault which we will access later in the spring application.</p><p>To do that we need to perform the below steps.</p><ol><li><strong>Login to vault</strong></li></ol><p># vault login &lt;Initial Root Token&gt;</p><p><strong>2. Enabling key-value secrets</strong></p><p>We will have to do this the very first time because by default vault’s secret engine won’t be enabled.</p><p># vault secrets enable -path=secret/ kv</p><ul><li>where the -path is where we are going to put all our key-value pair secrets.</li><li>kv is internal to the vault by which we are telling the vault server that this path will store key-value pairs.</li></ul><p><strong>3. Add your secrets to the vault</strong></p><p>Well, this is what we wanted to do, to put our secured key in the vault and access it directly from the spring application.</p><p>#vault kv put secret/spring-cloud-vault appSecurityKey=mysecretkey</p><p>#vault kv put secret/spring-cloud-vault/dev appSecurityKey=mysecretkey1</p><p>#vault kv put secret/spring-cloud-vault/prod appSecurityKey=mysecretkey2</p><p>where spring-cloud-vault is my spring boot application name and dev/prod is active profile</p><p>So the general syntax for multiple key-value pairs —</p><p>#vault kv put secret/&lt;application-name&gt;/&lt;profile&gt; key1=value1 key2=value2</p><h3>Spring Cloud Integration with Vault Server</h3><p>Now it is time to configure out spring boot application to fetch the secured key from the vault. For that, we need to add client jar dependency to connect to the vault</p><h4>Maven Dependency</h4><p>Adding spring cloud maven dependency into the project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d05c3ba59ddcc5943b0bf74f56022288/href">https://medium.com/media/d05c3ba59ddcc5943b0bf74f56022288/href</a></iframe><h4>Creating bootstrap.yml to connect with vault server</h4><p><strong>Why bootstrap.yml not application.yml?</strong></p><blockquote>A Spring Cloud application operates by creating a “bootstrap” context, which is a parent context for the main application. <strong><em>Out of the box it is responsible for loading configuration properties from the external sources</em></strong>, and also decrypting properties in the local external configuration files. — From the documentation.</blockquote><p>And hence we need to create bootstrap.yml to fetch external properties from vault server —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcce825be03530f24aa6adeae2915e5b/href">https://medium.com/media/fcce825be03530f24aa6adeae2915e5b/href</a></iframe><p>Spring Cloud Vault accesses different resources. By default, the secret backend is enabled which accesses secret config settings via JSON endpoints.</p><p>The HTTP service has resources in the form:</p><pre>/secret/{application-name}/{profile}<br>/secret/{application-name}<br>/secret/{default-context}/{profile}<br>/secret/{default-context}</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdcc30350c89667508e3fa9240d5b7c2/href">https://medium.com/media/cdcc30350c89667508e3fa9240d5b7c2/href</a></iframe><p>Now you can give it a try for adding more keys into vault serve with a different profile and access it in your spring cloud application by changing profile bypassing program argument like spring.profiles.active=dev/prod/test1 and see if value changes</p><h3>Conclusion</h3><p>We saw, how easy it is when it comes to access secrets from the vault server. The overall effort actually goes in the vault server setup which is actually a system administrator job done in your organization. You would only need your vault server IP and a token to authenticate with the vault server, and you would ask the admin to add key-value pairs in the vault server and access it directly in your spring application. There are various ways vault authentication can happen. Please<a href="https://cloud.spring.io/spring-cloud-vault/reference/html/"> see here</a> for more details.</p><p>Git hub code present here</p><p><a href="https://github.com/rajeevshukla/spring-cloud-vault">rajeevshukla/spring-cloud-vault</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c18da62a42e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/securing-passwords-using-hashicorp-vault-in-spring-6c18da62a42e">Securing Passwords Using HashiCorp Vault and Spring-Cloud</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Security 5.3 OAuth2 integration with Facebook along with Form-Based login]]></title>
            <link>https://medium.com/@mail2rajeevshukla/spring-security-5-3-oauth2-integration-with-facebook-along-with-form-based-login-767e10b02dbc?source=rss-20dfb10b2322------2</link>
            <guid isPermaLink="false">https://medium.com/p/767e10b02dbc</guid>
            <category><![CDATA[login]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[facebook]]></category>
            <category><![CDATA[spring-boot-2]]></category>
            <category><![CDATA[oauth2]]></category>
            <dc:creator><![CDATA[Rajeev Shukla]]></dc:creator>
            <pubDate>Fri, 01 May 2020 17:48:28 GMT</pubDate>
            <atom:updated>2020-10-08T17:17:28.810Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*vUs7bk4sQNFsTa9nQ-meLw.png" /></figure><h3><strong>Introduction</strong></h3><p>OAuth2 configurations are quite intimidating. You might have come across to see many people have tried to simplify by writing blogs, series about how to integrate OAuth2 facebook with Spring security in many different ways but when we start we get stuck as it does not work because of so many different configurations. Also, you don’t understand where to make changes to customize it according to your project.</p><p>In this post, we are going to see the simplest way of <strong>spring security 5 Facebook oauth2 integration along with form-based </strong>where users can either log in via Facebook or by entering username password in the login form.</p><blockquote>In this post implementation is going to in-memory only. The whole idea is to show the minimal configuration of spring security 5 for OAuth2 integration with Facebook along with form-based authentication. I have a plan to take it to the next level using DB and email integration and remember me blah blah. So stay tuned for the next post!!!</blockquote><h3><strong>Adding Dependency</strong></h3><p>With the assumption that you have knowledge on how to create spring boot project and have an understanding of the basics of maven, spring MVC following is the dependency, you need to add in your pom.xml.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e142073c5c2e87297e5c117fa49101e2/href">https://medium.com/media/e142073c5c2e87297e5c117fa49101e2/href</a></iframe><ul><li>The latest spring security project provides support for the OAuth2 server dependency but not the client. Since we need to connect to the Facebook OAuth server as a client so we need to add ‘oauth2-client’ dependency.</li></ul><blockquote>For experts who know the internals of spring security, OAuth2-client dependency is needed along with spring security because spring security needs <strong>OAuth2LoginAuthenticationFilter</strong> in its filter chain to be present on classpath in order to support OAuth client Integration. Which is present inside <strong>spring-boot-starter-oauth2-client. </strong>We will cover this later in upcoming posts.</blockquote><ul><li>Adding tomcat-embed-jasper dependency in order to support spring-MVC with JSP.</li></ul><h3><strong>Project Structure</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*5swy3vJY3uKWgJCjPiCIqQ.png" /></figure><p><strong>Hint:</strong> To support JSP you need to have <strong>webapp </strong>as a source folder and create WEB-INF/jsp/ under it. In eclipse you can <strong>Right-click on project&gt;new&gt;source folder</strong> and name it webapp. And then create two folders WEB-INF/jsp/.</p><h3><strong>Creating a Facebook App for Oauth 2 Login</strong></h3><ul><li>Go to <a href="https://developers.facebook.com/">https://developers.facebook.com/</a></li><li>Login and create a new app</li><li>Add details like application name, URL, and any required details.</li><li>After successful app creation, you would see something like below where you can navigate to <strong>settings&gt;basic</strong> and copy client-id and client-secret</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lU5nfGp3ryJhJfsbPFR-dQ.png" /></figure><blockquote>Note: The above steps may change on the Facebook developer page, depending on how long they keep the same UI.</blockquote><h4><strong>Application Properties</strong></h4><ul><li>Copy <strong>client-id</strong> and <strong>client-secret</strong> from the previous step, you need to add that in application.yml/properties file on given placeholders(&lt;&gt;) below which is self-explanatory. One thing you need to keep in mind that client-secret is something that you need to keep encrypted.<a href="https://medium.com/@mail2rajeevshukla/hiding-encrypting-database-password-in-the-application-properties-34d59fe104eb"> To know how to encrypt properties in spring boot property files see my other post.</a></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be04a1fe91bc0b66743587b67b5e62a0/href">https://medium.com/media/be04a1fe91bc0b66743587b67b5e62a0/href</a></iframe><ul><li>Technically <strong>scope</strong> is a <strong>grant_type </strong>that is specific to the provider. In our case, Facebook has these two default scope which will grant to the client(our app) to access public profile and email once the user is authenticated. There are various scopes (<a href="https://developers.facebook.com/docs/facebook-login/permissions">see here</a>) that you can define but that depends if your Facebook app is allowed to access or not.</li><li>Added Jsp view resolver mapping to look Jsp pages inside WEB-INF/jsp folder.</li></ul><h4><strong>Login Page</strong></h4><p>Before jumping to spring security configuration what our expectation is, we want to have one custom login page where we can add the <strong>Sign In with Facebook</strong> button along with <strong>form</strong> where we can enter username password. Something like below —</p><figure><img alt="Login page" src="https://cdn-images-1.medium.com/max/421/1*of0-d9td4Pk7uHzDv1NV3g.png" /></figure><h3>Security Configuration</h3><p>Keeping the login page in mind lets configure our security configuration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb6e6d0ecc9d365d494497ea3ddacbf1/href">https://medium.com/media/fb6e6d0ecc9d365d494497ea3ddacbf1/href</a></iframe><p><strong>Explanation: </strong>Okay so this is the main part that you need to understand that what we have done step by step.</p><blockquote>While reading the below points parallelly map it with the configuration we did in the above code snippet.</blockquote><p>Below is how you can read-</p><p>Hey spring-security (HttpSecurity technically)-</p><ul><li>authorize all the request and let everyone access /login page (permitAll()) see line:8</li><li>After that, any request should be authenticated see line:9</li><li>And enable form-based login see line:10</li><li>And add a custom login page /login for form-based and redirect to /formLoginSuccess after successful authentication seeline:11</li><li>And enable logout (default URL would be /logout ) see line:12</li><li>And enable OAuth2Login flow see line:13</li><li>And add a custom login page /login (same as form-based) and redirect to /oauth2LoginSuccess once the user is authenticated from Facebook see line:14</li><li>And disable CSRF token. By default, it is enabled and this will force you to call /logout using HTTP POST instead of GET Method. So let&#39;s disable it for now. see line 15</li></ul><h4>After that configure form-based credentials-</h4><p>Configure an in-memory username password so that we can use the login-form to submit a username password for authentication.see line:19 configure(AuthenticationManagerBuilder auth) methodfor more details in the above code snippet. Which is self-explanatory.</p><h4>Things to know —</h4><ul><li>spring-security by default provides oauth2 client implementation for common providers like Facebook, Google, GitHub, and Okta. That is why we didn’t do anything just added facebook details in application.properties and bang!</li><li>When you enable OAuth2Login flow see line 13, by default spring-security enables authorization endpoint as /oauth2/authorization/{registerationId}. In our case, registration id is facebook(see application props)hence URL to trigger Facebook authorization would be /oauth2/authorization/facebook and our app will talk to Facebook for OAuth2 flow.</li><li>Since our application has two different login flow Oauth and form-based hence spring security stores user details into 2 different objects <a href="https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/oauth2/core/user/OAuth2User.html">Oauth2User</a> for OAuth-flow and <a href="https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/core/userdetails/UserDetails.html">UserDetails</a> for form-based flow. We will see this in detail soon.</li></ul><h3><strong>Adding Controller</strong></h3><p>Now we need to configure all the custom URLs that we have mentioned in the security configuration which is</p><p><strong>1. </strong>/login <strong>page</strong></p><p>Since we need to show custom login page so this is going to be like —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/621db0dd41080f9d368ef89978c9fa80/href">https://medium.com/media/621db0dd41080f9d368ef89978c9fa80/href</a></iframe><p><strong>2.</strong> /oauth2LoginSuccess<strong>Request Mapping</strong></p><p>Once a user clicks on sign in with facebook , Oauth flow triggers our application will redirect the user to go on Facebook and enter the username password after successful authentication spring-security will redirect him to /oauth2LoginSuccess as we mention it in security config as default success URL.</p><blockquote>A lot of things happens behind the scene in OAuth2 flow. Intent of this post is to cover basic confiugration and integration. We will understand flow in upcoming posts as we will dive in. Stay tunned !</blockquote><p>Below is the request handler mapping code snippet —</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f08960d798b3eaf64b53cdb1e4fc9570/href">https://medium.com/media/f08960d798b3eaf64b53cdb1e4fc9570/href</a></iframe><h4>Things to know —</h4><p>When a user logs in in your application through OAuth2 Flow</p><ul><li>The very first time your application won’t have any user details present in DB. So in /oauth2LoginSuccess method you can look into DB and see if the user is not present the DB then insert into DB and send a welcome email else to load other profile related information. <em>[We will see this in an upcoming post when we will integrate this flow with DB]</em></li><li>Sometime you may need more user details from Facebook like first_name last_name which by default is not present inside OAuth2User object then here you have to make another call here to Facebook to get more details. So to do that you have to obtain facebook authenticated token first see line 17–20 in the above code snippet and pass that into rest call to facebook as Bearer &lt;token&gt;in header to fetch more details.<em> We will see this next post when we will store the first name last name in DB.</em></li><li>To obtain user info you need to get OAuth2User object from OAuth2AuthenticationToken.getPricipal() and OAuth2User.getAttributes() will return you a map of user info.</li><li>@AuthenticationPricipal is a new annotation in spring security which extracts the authentication object. This is exactly similar to —</li></ul><p>Authentication authentication = SecurityContextHolder.getContext().getAuthentication();</p><blockquote>In OAuth2 login flow OAuth2User object is encapsulated inside authentication object which we can obtain via Authentication object or OAuth2AuthenticationToken.</blockquote><p><strong>3.</strong> /formLoginSuccess<strong>Request Mapping</strong></p><p>Once the user will enter a valid username password which is admin/admin in our case as we have defined in memory. After successful authentication user will be redirected to /formLoginSuccess</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1910c3764fa4aec932f315985cf6a5ee/href">https://medium.com/media/1910c3764fa4aec932f315985cf6a5ee/href</a></iframe><blockquote>In form login flow <a href="https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/core/userdetails/UserDetails.html">UserDetails</a> object encapsulated in authentication which we can obtain using authentication.getPrincipal()</blockquote><h4>Login Page HTML</h4><p>I will leave it on you to understand below HTML :).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/494145168af2e5be07307d452170357e/href">https://medium.com/media/494145168af2e5be07307d452170357e/href</a></iframe><h4>Home Page HTML</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc97ee65a8ee68ce8bb9945a43150a36/href">https://medium.com/media/cc97ee65a8ee68ce8bb9945a43150a36/href</a></iframe><p><strong>Home page after Facebook login</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*aNFzarkPdaLcTY0xQE7YtQ.png" /></figure><p><strong>Home page username password flow</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*B7JI9CwFKdF14ywAJVU7IQ.png" /></figure><p>In both cases, we land on the same screen after successful authentication.</p><h3>Summary</h3><p>So far we have seen one of the simplest ways to integrate with Facebook along with form-based. Which most of us need in our application to support. But this is not enough. We need to customize it more and more and integrate it with DB. Add Forget-Password flow, Remember me, Or you may be looking for REST-based flow where you send Bearer &lt;Token&gt; in the response to the client (like angular) as many of us might be working in the microservices world. We will cover all the topics one by one in my upcoming posts. They are all in draft mode :).</p><p>👉🏽Check out the complete working code on my GitHub account.</p><p><a href="https://github.com/rajeevshukla/spring-security-oauth2-facebook">rajeevshukla/spring-security-oauth2-facebook</a></p><p><strong>PS: </strong>Your comments/claps keep me motivated to write more stuff like this. Please keep me motivated 😜.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=767e10b02dbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating ORC table in SparkR and Dynamic Partitioning]]></title>
            <link>https://medium.com/@mail2rajeevshukla/creating-orc-table-in-sparkr-and-dynamic-partitioning-8b11aa9b6118?source=rss-20dfb10b2322------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b11aa9b6118</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[sparkr]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Rajeev Shukla]]></dc:creator>
            <pubDate>Sat, 14 Sep 2019 18:14:19 GMT</pubDate>
            <atom:updated>2019-09-14T18:41:46.076Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*SKtF-kkBOu2VZJwq.png" /></figure><p><strong>Introduction</strong></p><p>Assuming that you are using sparkR with Hive to process huge set of data. In this blog post, I am going to tell you how to create an ORC table using SparkR with dynamic partitioning on columns. In sparkR, there is no direct method available which can create ORC table and do the partitioning while creating the table.</p><p>Though there is a sparkR function saveAsTable() which can serve the purpose it can’t do the partition on the fly while saving the data frame.</p><p><strong>What is an ORC format?</strong></p><p>ORC stands for <strong>Optimized Row Columnar</strong>. It is an intelligent big data file format which provides a highly efficient way to store hive data. In simple terms, it works on column-based which means whatever columns you are working on, only those columns will be processed rest of them will be intact.</p><p>For more details about ORC please refer <a href="https://cwiki.apache.org/confluence/display/Hive/LanguageManual+ORC#LanguageManualORC-ORCFileFormat">here</a>.</p><p>Below is the file size comparison between different file format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/0*O27OXBfoXZrQBgNy.png" /><figcaption>File Size comparison (<a href="https://www.slideshare.net/oom65/optimize-hivequeriespptx">source</a>)</figcaption></figure><p><strong>Creating SparkR function to save the data frame in a partitioned table</strong></p><p>In sparkR there is a saveAsTable() function which saves the Data Frame into a table but that is by default in text format which is not efficient. Also, when you want to partition also this function, can’t help you. So let&#39;s create a function name <a href="https://spark.apache.org/docs/latest/api/R/saveAsTable.html">saveAsORCTable</a>()which accepts 4 arguments -</p><ol><li>DataFrame: Actual data frame which you want to store as ORC table</li><li>Table Name: Name of the ORC table</li><li>ParitionBy: A vector by which you want to partition the table</li><li>Mode: Append/Overwrite</li></ol><p><strong>Function in SparkR:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15148f7682735b47bd7c52eccedaa04d/href">https://medium.com/media/15148f7682735b47bd7c52eccedaa04d/href</a></iframe><blockquote>Note: Above fuction is only compatible if you are using Spark Version 2.2+</blockquote><p>Assuming you have a data frame having account statement details with so many columns including month, year and you want to partition table based on month and year column below would be the function call.</p><p><strong><em>Function Call:</em></strong><em> </em><em>saveAsORCTable(df,&#39;account_statement_master&#39;,c(&#39;month&#39;,&#39;year&#39;),&#39;append&#39;)</em></p><blockquote>Just in case you want to overwrite mode only then don’t pass last argument as overwrite mode is by default as you can see in function signature.</blockquote><p>Few things to note down related to the above function, in Spark SQL when you insert data on a partitioned table, the partitioned columns must appear in the last of the select statement. So whatever column you pass in partitionByshould be the last argument in select statement in insert into select &lt;here&gt; from`. see line#9. So to achieve this you have to do some manipulation on a column name to make it appear in the last which is done in line #6,7 &amp; 8.</p><p>Rest of the code is self-explanatory. Though If you have any query related to this, write in the comment section. I would be happy to help you.</p><p>Stay tuned for more updates like this. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b11aa9b6118" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hiding/Encrypting database password in the application.properties]]></title>
            <link>https://medium.com/developervisits/hiding-encrypting-database-password-in-the-application-properties-34d59fe104eb?source=rss-20dfb10b2322------2</link>
            <guid isPermaLink="false">https://medium.com/p/34d59fe104eb</guid>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[secure]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[jasypt]]></category>
            <dc:creator><![CDATA[Rajeev Shukla]]></dc:creator>
            <pubDate>Sun, 28 Apr 2019 03:27:17 GMT</pubDate>
            <atom:updated>2020-07-26T21:27:44.529Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hiding/Encrypting database password in the application.properties file in a simple and secure way using spring-boot-jasypt</h3><figure><img alt="Image result for spring boot image" src="https://cdn-images-1.medium.com/proxy/1*jMQ9lkY5SBnbcOlJB4aizg.png" /></figure><h3><strong>1.Introduction</strong></h3><p>Java Simplified Encryption also knows as J<a href="http://www.jasypt.org/">asypt</a> is a java library which allows the developer to add basic encryption capabilities to his/her projects with minimum effort, and without the need of having deep knowledge on how cryptography works.</p><p>It provides integration into <strong>Spring</strong>-based applications and also transparently integrable with <strong>Spring Security </strong>and many other frameworks.</p><p><strong>2. Adding Jasypt dependency</strong></p><p>Now when it comes to adding Jasypt dependency there are multiple ways to do. It is totally up to you which way you want to go.</p><p><strong>2.1</strong> Remove Spring boot’s core dependency and add Jasypt enabled spring boot core dependency.</p><p>Remove below from your project which is only deal with spring boot core</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfde9c73cab62909c3fb01c33a3be34c/href">https://medium.com/media/cfde9c73cab62909c3fb01c33a3be34c/href</a></iframe><blockquote>Add below Jasypt enabled spring core which includes spring boot + jayspt enabled with this you don’t need to do anything in your project. @EnableAutoConfiguration annotation is enough to get going.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9881088cf2fc773f0d0573f5b97b863/href">https://medium.com/media/c9881088cf2fc773f0d0573f5b97b863/href</a></iframe><p><strong>2.2</strong> if you don’t use jasypt spring starter dependency then you can go with alternate just add below dependency</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5288a8b7049fec7cef02b23727b32045/href">https://medium.com/media/5288a8b7049fec7cef02b23727b32045/href</a></iframe><p>And annotation your main configuration class with <strong>@EnableEncryptableProperties</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8870658fd4e1c9e5f991027042b7eb0/href">https://medium.com/media/a8870658fd4e1c9e5f991027042b7eb0/href</a></iframe><p>That is it. Now spring boot will enable encryptable properties across the entire Spring Environment.</p><h3><strong>3. Creating an encrypted key-</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8fb5bb790c717b698958f60752a2230/href">https://medium.com/media/e8fb5bb790c717b698958f60752a2230/href</a></iframe><p><strong>input:</strong> It is the actual password that you want to hide.</p><p><strong>password:</strong> A secret key that is used to encrypt the actual input which will later be used to decrypt the password. So you need to note down this key for future decryption.</p><p><strong>PBEWithMD5AndDES: </strong>A password-based version of the DES algorithm which uses an MD5 hash of the specified password as the encryption key</p><p><strong>Update-</strong></p><blockquote>In version 3.0.0+ jasypt started using PBEWITHHMACSHA512ANDAES_256 algorithm as default encryption algo so you may face error if you see use same algorithm what we are using here PBEWithMD5AndDES<strong> </strong>So either use <em>PBEWITHHMACSHA512ANDAES_256 algo as default or add below properties to fix the issue.</em></blockquote><p>The error would be something like —</p><pre>Unable to decrypt: ENC(MyEncryptedPass). The decryption of Properties failed, make sure encryption/decryption passwords match</pre><p>To fix this problem you will have to add two properties in your application.properties file.</p><pre>jasypt.encryptor.algorithm=PBEWithMD5AndDES<br>jasypt.encryptor.iv-generator-classname=org.jasypt.iv.NoIvGenerator</pre><p>For more details <a href="https://github.com/ulisesbocchio/jasypt-spring-boot#update-11242019-version-300-release-includes">see here</a></p><p><strong>4. Adding encrypted key into application.properties</strong></p><p>Now whatever output you get in step #3 in the output section, is your actual property value which is going to be used in application.poperties.</p><p>Now before adding that encrypted value, Firstly, you need to know how would Jasypt know that it should be decrypted or not? To distinguish that Jasypt uses a default convention to add that encrypted key inside ENC(&lt;encrypted keys here&gt;)</p><p><strong>Example:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8eacb65ae285b56c2058e0d97aa57c0/href">https://medium.com/media/a8eacb65ae285b56c2058e0d97aa57c0/href</a></iframe><p>Jasypt reads all the properties from application.properties or any classpath properties that you passed. It is not necessary you can only secure only the DB password. In fact, you can secure anything you want You just need to use the prefix ENC( and suffix ) and pass the encrypted key.</p><p>We can change the prefix ENC() to a custom name like SEC() or anything that you want but that would lead to the separate topic of discussion.</p><p><strong>5. Passing Jasypt secret key in command line argument</strong></p><p>Now we need to tell the program to decrypt the encrypted key at run time when needed. To do that we need to pass that secret key into our application. There as various way we can do that —</p><p><strong>5.1</strong> $mvn -Djasypt.encryptor.password=secretkey spring-boot:run</p><p><strong>5.2</strong> export JASYPT_ENCRYPTOR_PASSWORD=secretkey and then run your application a simple java application.</p><p><strong>5.3</strong> <strong><em>(Using STS/Eclipse)Right click on main class &gt; Run as &gt; Run configuration </em></strong>and pass secret key in VM argument like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZg-1osZo2fPWj7X4FXjEQ.png" /></figure><p><strong><em>5.4 Using spring cloud vault: </em></strong>This is the most secure way to do that. Please follow given the link to read how to secure it using spring cloud vault.</p><p><a href="https://medium.com/@mail2rajeevshukla/securing-passwords-using-hashicorp-vault-in-spring-6c18da62a42e">Securing passwords using HashiCorp Vault and Spring-cloud</a></p><p><strong>6. Summary</strong></p><p>So far we have seen how easy it is to encrypt passwords or any text that we want to hide. But this is the most simple form of implementation which is enough to get going. But sometimes we come across a situation where we need to customize some of its functionality as per the application needs. So, In that case, I would like to refer you to go through the document and you will get so much information which I have not mentioned <a href="https://github.com/ulisesbocchio/jasypt-spring-boot">here</a>.</p><p>Likes/comments are appreciated.</p><p>👉🏼 <strong>Check out my next post on how to Integrate Spring Security OAuth2 with Facebook along with Form-based login</strong></p><p><a href="https://medium.com/@mail2rajeevshukla/spring-security-5-3-oauth2-integration-with-facebook-along-with-form-based-login-767e10b02dbc">Spring Security 5.3 OAuth2 integration with Facebook along with Form-Based login</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34d59fe104eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/developervisits/hiding-encrypting-database-password-in-the-application-properties-34d59fe104eb">Hiding/Encrypting database password in the application.properties</a> was originally published in <a href="https://medium.com/developervisits">Developervisits</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating and loading 1000 mock datasets from a JSON file using guava & Gson]]></title>
            <link>https://medium.com/@mail2rajeevshukla/creating-and-loading-1000-mock-datasets-from-a-json-file-using-guava-gson-869666fc00a6?source=rss-20dfb10b2322------2</link>
            <guid isPermaLink="false">https://medium.com/p/869666fc00a6</guid>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Rajeev Shukla]]></dc:creator>
            <pubDate>Mon, 15 Oct 2018 12:32:51 GMT</pubDate>
            <atom:updated>2018-10-15T12:32:51.929Z</atom:updated>
            <content:encoded><![CDATA[<ol><li><strong>Introduction</strong></li></ol><p>Sometimes we come across a situation where we need a lot of mock data to perform certain operations. For example, During my learning java 8 stream, I faced a situation where I need multiple sets of data to perform certain stream operation. During those time, I had hard-coded some mock data into ArrayList and performed operations. But that was not enough for me as I had to perform a verity of operations.</p><p>In this post, I am going to tell you how to load thousands set of mock data programmatically which can help you during your learning.</p><p><strong>2. Java POJO Classes</strong></p><p>We are going to load Employee object who can have multiple Cars.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dc79e25a5ff7bfb5096f18ffcd092c8/href">https://medium.com/media/4dc79e25a5ff7bfb5096f18ffcd092c8/href</a></iframe><p>List of fields that a Car can have :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62b64387b0b5b90a74c62d3918e454e4/href">https://medium.com/media/62b64387b0b5b90a74c62d3918e454e4/href</a></iframe><p><strong>3. Download JSON data from Mockaroo</strong></p><p>Here is a website called <a href="https://www.mockaroo.com/">mockaroo</a> you can take help of this website to generate data in JSON format and download a JSON file. You have a choice what kind of field you want [<a href="https://www.youtube.com/watch?v=YIm3Xx1jk3g">YouTube</a>].</p><p>For above employee.java and Car.java class fields, you need to set below columns on <a href="https://www.mockaroo.com/">mockaroo</a> website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7m-8O85Ajn0Qp-SIEHjs8Q.png" /></figure><p>From above screenshot a few things to note down :</p><ul><li>Field name data should be matching with Employee class instance variable.</li><li>Type column is what type of data you want. To explore more just click on any type you will get to know.</li><li>Options column is just in case you want to apply any condition or formula to generate data.</li><li>By default, Mockaroo provides 1000 free rows only which is more than enough for us.</li><li>Select format type as JSON. There are many formats available like CSV, SQL, XML.</li><li>Click on Download button and save file with name employees.json.</li></ul><p>Now paste employees.json (that we downloaded in previous steps) on the classpath (directly inside ‘src’ folder).</p><p><strong>4. Maven</strong></p><p>Create a simple maven project having Java 8 support in eclipse or any IDE that you use and add following dependencies in pom.xml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59275729010b8a20c9390052261e4892/href">https://medium.com/media/59275729010b8a20c9390052261e4892/href</a></iframe><p><strong>5. Load JSON data (employees.json) to create Java Objects</strong></p><p>Create a util class name <strong>MockDataUtil</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd338eea6cf21e4feadbd5bfbb9bed7f/href">https://medium.com/media/bd338eea6cf21e4feadbd5bfbb9bed7f/href</a></iframe><p>Now you can access MockDataUtil.getEmployees() anywhere and you can get 1000 records at a time and perform any certain operations like calculating average salary, finding employees having gender male and blah blah blah….</p><p><strong>Why did we do this?</strong></p><p>In upcoming blog posts, I am going to write about Java 8 stream’s different operations with the help of these datasets which will be very useful for us.</p><p>If you have any question feel free to ask in the comment section.</p><p>Stay tuned for more posts :).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=869666fc00a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Axis logging of SOAP Request/Response programmatically]]></title>
            <link>https://medium.com/@mail2rajeevshukla/apache-axis-logging-of-soap-request-response-programmatically-c9f75eca7c45?source=rss-20dfb10b2322------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9f75eca7c45</guid>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[soap]]></category>
            <category><![CDATA[apache-axis]]></category>
            <category><![CDATA[java-webservices]]></category>
            <dc:creator><![CDATA[Rajeev Shukla]]></dc:creator>
            <pubDate>Sun, 14 Oct 2018 23:35:01 GMT</pubDate>
            <atom:updated>2018-10-15T01:01:20.280Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>There are many ways to log the Apache Axis SOAP request/response.</strong></p><ol><li>Using client-config.wsdd.</li><li>Using log4j.properties and adding axis logger related configurations.</li><li>Registering Axis logger programmatically.</li></ol><p>Choosing <strong>option#3</strong> which is the simplest and easiest way to do.</p><p><strong>Registering Axis logger programmatically –</strong></p><p>1: Create a java file and extend BasicHandler class provided by Apache Axis framework.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a69a062551b5f30f743e3844ef90dd3/href">https://medium.com/media/5a69a062551b5f30f743e3844ef90dd3/href</a></iframe><p>Place below code snippet in your main file (or ApplicationUtils.java in my case) where you are creating the object of locator instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe5dcb7686b864fce5f4ed161932be10/href">https://medium.com/media/fe5dcb7686b864fce5f4ed161932be10/href</a></iframe><p>Make sure that all above imported classes are part of <em>org.apache.axis.*</em> package.</p><p>Now call above method and set into Locator instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fda321abb676bb3066bff35a83c03d0/href">https://medium.com/media/9fda321abb676bb3066bff35a83c03d0/href</a></iframe><p>That’s it. Now when you execute the API, SOAP request/response would be logged on to the console.</p><p>Hope this helps to you. Stay tuned for more like this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9f75eca7c45" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>