<?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"><channel><title><![CDATA[Suraj Gautam Blog]]></title><description><![CDATA[Never stop learning.]]></description><link>https://blog.gautamsuraj.com.np</link><generator>RSS for Node</generator><lastBuildDate>Wed, 16 Sep 2026 16:23:17 GMT</lastBuildDate><atom:link href="https://blog.gautamsuraj.com.np/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[K8s Cheat sheet]]></title><description><![CDATA[Pods, Deployments and Services
kubectl run nginx --image=nginx --port=80
kubectl run nginx --image=nginx --port=80 --expose=true
kubectl run nginx --image=nginx --labels="app=web,tier=frontend"

kubectl create deployment nginx --image=nginx
kubectl c...]]></description><link>https://blog.gautamsuraj.com.np/k8s-cheat-sheet</link><guid isPermaLink="true">https://blog.gautamsuraj.com.np/k8s-cheat-sheet</guid><category><![CDATA[Kubernetes]]></category><category><![CDATA[ckad]]></category><category><![CDATA[k8s]]></category><dc:creator><![CDATA[Suraj gautam]]></dc:creator><pubDate>Sat, 13 Dec 2025 04:08:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1765600079612/57aaa535-5da9-43fb-9d4c-c08d163281cc.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-pods-deployments-and-services">Pods, Deployments and Services</h2>
<pre><code class="lang-bash">kubectl run nginx --image=nginx --port=80
kubectl run nginx --image=nginx --port=80 --expose=<span class="hljs-literal">true</span>
kubectl run nginx --image=nginx --labels=<span class="hljs-string">"app=web,tier=frontend"</span>

kubectl create deployment nginx --image=nginx
kubectl create deployment nginx --image=nginx --replicas=3
kubectl create deployment nginx --image=nginx --dry-run=client -o yaml &gt; nginx-deploy.yaml

kubectl expose pod redis --port=6379 --name=redis-service
kubectl expose pod redis --port=6379 --name=redis-service --selector=<span class="hljs-string">"app=redis"</span>
kubectl expose deployment nginx --port=80 --<span class="hljs-built_in">type</span>=ClusterIP
kubectl expose pod nginx --port=80 --<span class="hljs-built_in">type</span>=NodePort

kubectl get pods -l tier=frontend
kubectl get deploy -o wide
kubectl get endpoints redis-service

kubectl label pod nginx app=web
</code></pre>
<h2 id="heading-scaling-and-editing">Scaling and Editing</h2>
<pre><code class="lang-bash">kubectl scale deployment nginx --replicas=5
kubectl edit deployment nginx
kubectl delete pod nginx-xxxx
</code></pre>
<h2 id="heading-rolling-updates">Rolling Updates</h2>
<pre><code class="lang-bash">kubectl <span class="hljs-built_in">set</span> image deployment/myapp-deployment nginx=nginx:1.25
kubectl rollout status deployment/myapp-deployment
kubectl rollout <span class="hljs-built_in">history</span> deployment/myapp-deployment
kubectl rollout <span class="hljs-built_in">history</span> deployment/myapp-deployment --revision=3
kubectl rollout undo deployment/myapp-deployment
kubectl rollout pause deployment/myapp-deployment
kubectl rollout resume deployment/myapp-deployment
</code></pre>
<h2 id="heading-configmaps-and-secrets">ConfigMaps and Secrets</h2>
<pre><code class="lang-bash">kubectl create configmap app-config \
  --from-literal=APP_COLOR=blue \
  --from-literal=APP_MODE=prod

kubectl create configmap app-config --from-file=application.properties
kubectl create configmap app-config --from-env-file=app.env

kubectl create secret generic app-secret --from-literal=DB_HOST=mysql
kubectl create secret generic app-secret --from-file=application.properties
</code></pre>
<h2 id="heading-authorization-amp-rbac">Authorization &amp; RBAC</h2>
<pre><code class="lang-bash">kubectl auth can-i create deployment
kubectl auth can-i delete nodes
kubectl auth can-i create deployments --as dev-user
kubectl auth can-i create pods -n dev
kubectl auth can-i get pods --as system:serviceaccount:dev:my-sa
</code></pre>
<h2 id="heading-others">Others</h2>
<pre><code class="lang-bash">kubectl get clusterrole --no-headers | wc -l
<span class="hljs-comment"># Ingress</span>
kubectl create ingress ingress-test --rule=<span class="hljs-string">"payment.xyz.com/pay*=pay-service:80"</span> --annotation nginx.ingress.kubernetes.io/rewrite-target=/
<span class="hljs-comment"># ApiGroups</span>
kubectl api-resources
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Add a custom domain to the elastic beanstalk and enable SSL]]></title><description><![CDATA[Elastic Beanstalk is one of the most powerful services powered by AWS for quick deployment and monitoring of your application. It provides a better and easiest way to auto-scale your application and balance workloads. In this article, I am not going ...]]></description><link>https://blog.gautamsuraj.com.np/add-a-custom-domain-to-the-elastic-beanstalk-and-enable-ssl</link><guid isPermaLink="true">https://blog.gautamsuraj.com.np/add-a-custom-domain-to-the-elastic-beanstalk-and-enable-ssl</guid><category><![CDATA[AWS]]></category><category><![CDATA[software development]]></category><category><![CDATA[Security]]></category><category><![CDATA[SSL]]></category><category><![CDATA[dns]]></category><dc:creator><![CDATA[Suraj gautam]]></dc:creator><pubDate>Fri, 04 Jun 2021 13:23:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1622650996941/iMuVzdFqm.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Elastic Beanstalk is one of the most powerful services powered by AWS for quick deployment and monitoring of your application. It provides a better and easiest way to auto-scale your application and balance workloads. In this article, I am not going to cover how to deploy your application to AWS Elastic Beanstalk, how to add a custom domain, and enable SSL for it.</p>
<p><strong>Prerequisites</strong>:</p>
<ol>
<li>Application deployed in AWS Elastic Beanstalk using Application Load Balancer</li>
<li>A Custom Domain and access to DNS settings</li>
</ol>
<h1 id="adding-custom-domain">Adding custom domain</h1>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622376334372/lmIE4PbvF.png" alt="application.png" /></p>
<p>As you can see, <strong>demo-application</strong> is the name of the application currently deployed. It's a simple Spring Boot application with <strong>/api/v1/test</strong> endpoint that returns Hello world as a response. Let's see it.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622376732660/kieaNIP4I.png" alt="image.png" /></p>
<p>Cool, the application is working. Now, let's try to add a custom domain first to this application. We need to use the Route53 service from AWS to create a hosted zone.</p>
<p>Steps:</p>
<ul>
<li>Search the Route53 service and go to the dashboard.</li>
<li>Click on create hosted zone. Enter the domain you want to link to this ELB. The type would be Public hosted zone.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622377078577/6YLOqlTDt.png" alt="image.png" /></p>
<ul>
<li>Click on Create hosted zone. </li>
<li>After it is created, click on Create record button.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622377437328/6Z8TZOkHg.png" alt="image.png" /></p>
<ul>
<li>Toggle the Alias button and in the Choose endpoint select option, choose <strong>Alias to Elastic Bean Stalk Environment</strong>. After that, choose your region and environment. It looks something like this.  </li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622377627605/81xV6Vc1k.png" alt="image.png" /></p>
<ul>
<li>Click create a record.</li>
</ul>
<p>Now you need to update your nameservers in your domain provider. In my case, it's Google Domain. Head to the DNS settings page and choose custom name servers.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622377924261/SowgDIvQQ.png" alt="image.png" /></p>
<p>If you're wondering where did I get those values from, do not worry, it's from the hosted zone dashboard from AWS.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622378423162/7SRe-3V2f.png" alt="untitled.png" /></p>
<p>It might take few hours to days depending on your domain provider. Now, when I go to <strong>startpeeq.com/api/v1/test</strong> I can see a hello world response.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622563430969/N3CPln-Xa.png" alt="image.png" /></p>
<h1 id="adding-ssl">Adding SSL</h1>
<p>If I try to curl the API with HTTPS, it responds time out because it is not enabled. Let's add the certificate now.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622649834160/9J5vnRibe.png" alt="curl.png" /></p>
<ul>
<li>Go to AWS Certificate Manager service and click on Request a public certificate. </li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622564131437/910RiQt0t.png" alt="request-a-certificate.png" /></p>
<ul>
<li>Enter the domain name (startpeeq.com in my case) and click on Next. </li>
<li>Now comes a validation step where we need to validate that we own this domain. We have two methods of doing it i.e DNS Validation and Email Validation. I chose DNS Validation. I have to create a CNAME Record by clicking on <strong>Create Record in Route 53</strong>. We are using custom DNS nameservers from the hosted zone. So, it will create a cname record in the hosted zone recordset.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622649348876/3Gxa1UVqn.png" alt="image.png" /></p>
<p>If you choose Email Validation instead, you will receive an email with a link in emails from your domain provider and you have to click on that link.</p>
<p>After few minutes, you will see the status issued in AWS Certificate Manager. Something like this</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622649444730/VyKeV-Uv2.png" alt="image.png" /></p>
<ul>
<li>Go to your Elastic Beanstic Beanstalk application and click on configuration on the left and edit the load balancer configuration. On the <strong>Listeners</strong> section, add a new listener.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622649975072/jHbxXosS2.png" alt="image.png" /></p>
<p>In the SSL Certificate, you will see the one we newly created. Apply the configuration and wait until the environment updates.</p>
<h1 id="testing-time">Testing time</h1>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622650260141/1Ghzps0hr.png" alt="image.png" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622650287986/iUY3wlBxg.png" alt="image.png" /></p>
<p><strong>Yay</strong>, we're done. Thanks a lot for bearing with me for so long. If you need any help or have any suggestions, feel free to reach out. Peace!</p>
]]></content:encoded></item><item><title><![CDATA[Avoiding Security Risks for Developers]]></title><description><![CDATA[Software developers are not only responsible for writing codes, building, and testing applications. They must be responsible for avoiding security risks for the project and the company as a whole. Due to the growing use of the internet, applications,...]]></description><link>https://blog.gautamsuraj.com.np/avoiding-security-risks-for-developers</link><guid isPermaLink="true">https://blog.gautamsuraj.com.np/avoiding-security-risks-for-developers</guid><category><![CDATA[Security]]></category><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Suraj gautam]]></dc:creator><pubDate>Tue, 19 Jan 2021 09:59:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1611050748380/Z2UHY0vdh.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Software developers are not only responsible for writing codes, building, and testing applications. They must be responsible for avoiding security risks for the project and the company as a whole. Due to the growing use of the internet, applications, tools, and technology, security risks have skyrocketed. It’s a major challenge for any software developer to try to avoid the common threats that have dominated the software development industry for so long.</p>
<p>Avoiding Security Risks must be a part of the development strategy. I mean, I’ve seen a lot of companies first trying to build software, and later after it's ready for UAT, they try to find vulnerabilities and threats by hiring part-time pen testers and security engineers. The developers cannot keep up with fixing bugs, adding features, and doing RND to fix security bugs at that point in time. That would create havoc and be a pain for the organization. Hence, it should be a part of a day to day development life cycle. For example, it can be a part of the CI/CD pipeline.</p>
<p>There are many things that a software developer can do from their end to avoid security risks. A few of them are:</p>
<h3 id="keep-up-with-dependencies">Keep Up With Dependencies</h3>
<p>Dependencies are an indispensable part of any system. It is not possible to write everything from scratch and would not be better to re-invent the wheel when there are already a bunch of trusted dependencies/libraries being used by top-notch companies. Always while choosing a dependency/library, a software developer must check the community whether it is supported hitherto, the number of downloads, or companies that use it. In short, a developer must meticulously look into the details. Choosing dependency is one thing but keeping up with it is another. There can be a major bug in the previous versions that you are using and an exploiter can use it to exploit your system. It’s always advisable to check the release notes and keep up to date your dependencies and libraries.</p>
<h3 id="manage-secrets">Manage Secrets</h3>
<p>We, software developers, and programmers are human beings though we don’t have a life. We, as human beings, find it so hard to manage secrets in our daily life. So is true in software development. There are many secrets that we use like passwords, tokens, keys etcetera. Usually, we, developers have to work under pressure and do everything in a rush. It can abstain us from managing secrets. The examples can be:</p>
<ul>
<li><p>Posting a stack overflow question with code to resolve immediate bug which contains credentials</p>
</li>
<li><p>Committing and pushing official projects with credentials, keys, tokens in a public Github/Gitlab repo</p>
</li>
<li><p>Posting things online which contains sensitive information</p>
</li>
</ul>
<p>It must be taken into consideration for maintaining the secrecy and avoiding the apocalypse.</p>
<h3 id="avoid-sharing-accounts">Avoid Sharing Accounts</h3>
<p>There is a common trend in a company to share the credentials of an account. Sharing a password is fine until it’s not. The more the credentials of an account are shared with individuals, the more the track of it is lost. Let’s say if the root account of AWS is shared among 20 developers and one of them deleted the EC2 instance then who is responsible for the havoc? How can we know what action is performed by which account because the account is shared?</p>
<p>The account can be created individually, if not possible, team-wise. It will minimize the risk because the account shared by 50 developers if hacked will impact more than the account shared by 4–5 developers. Also, if the account is used by more users, the more vulnerable it is and the tougher it is to manage secrecy.</p>
<h3 id="manage-permissions">Manage Permissions</h3>
<p>The permissions to the systems, databases, tools, and technologies should be managed properly. It should be only provided to the ones that are accountable. The needed permissions should be granted not more than that. For instance, the client executive should not be provided access to the development environment. The application that needs to upload files to AWS S3 should only be provided access to that operation nothing more than that.</p>
<p> <a target="_blank" href="https://about.gitlab.com/blog/2017/02/10/postmortem-of-database-outage-of-january-31/">Remember database outrage in Gitlab? </a> One engineer in Gitlab mistakenly deleted the primary production database instead of the secondary which resulted in the loss of 5000 projects, 5000 comments, and 700 new user accounts. One small mistake can result in a loss of reputation and a million dollars. If it can happen to a big company like Gitlab then is it inevitable for you?</p>
<h3 id="avoid-risky-behaviour">Avoid Risky Behaviour</h3>
<p>A skilled pilot with decades of experience can crash a plane when things go wrong. Similarly, skilled and trained developers can also create problems when their mental state is not good. Risky behaviors include:</p>
<ul>
<li><p>Setting unrealistic deadlines</p>
</li>
<li><p>Working through fatigue</p>
</li>
<li><p>Taking shortcuts and cutting corners</p>
</li>
<li><p>Rushing through tasks to meet the deadlines and ignoring crucial aspects of the development</p>
</li>
</ul>
<p>A short break or procrastination sometimes can be a good approach to avoiding risks.</p>
<p>Thanks a lot for reading this article. If you have anything in mind, then please feel free to comment or reach out to me. :) </p>
]]></content:encoded></item><item><title><![CDATA[Cool Intellij IDEA Shortcuts]]></title><description><![CDATA[I have used Netbeans, Eclipse, STS, and Intellij IDEA but Intellij has been my first choice since my first use. It is one of the best IDE for developing applications. Compared to other IDEs, it provides strong support for autocomplete feature. The de...]]></description><link>https://blog.gautamsuraj.com.np/cool-intellij-idea-shortcuts</link><guid isPermaLink="true">https://blog.gautamsuraj.com.np/cool-intellij-idea-shortcuts</guid><category><![CDATA[IDEs]]></category><category><![CDATA[programming]]></category><category><![CDATA[Java]]></category><dc:creator><![CDATA[Suraj gautam]]></dc:creator><pubDate>Fri, 18 Sep 2020 09:02:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1600415150734/Pox6h8R13.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I have used Netbeans, Eclipse, STS, and Intellij IDEA but Intellij has been my first choice since my first use. It is one of the best IDE for developing applications. Compared to other IDEs, it provides strong support for autocomplete feature. The debugging feature in it is a lot easier and the User Interface is awesome. I just love it.</p>
<p>Using shortcuts helps us to do more in less time. I have my favorite IntelliJ IDEA shortcuts mentioned below.</p>
<p>Note: I have GNOME as a keymap setting in my IDE.</p>
<img alt="Image for post" src="https://miro.medium.com/max/1128/1*1o9_FfEsArFe8i74U7HGgQ.png" />

<h2 id="rename-shift-f6"><strong>Rename (Shift + F6)</strong></h2>
<p>This is the most frequently used shortcut for me. It helps to rename the variables or methods names. Let’s see an example.</p>
<pre><code><span class="hljs-keyword">public</span> <span class="hljs-keyword">List</span>&lt;<span class="hljs-keyword">String</span>&gt; getPaymentList(){
    <span class="hljs-comment">// logic</span>
<span class="hljs-keyword">return</span> Collections.emptyList();
}
</code></pre><p>Your senior developer didn’t like the name of your method or let’s say <strong>Uncle Bob </strong> would hate you for this method name which is why you would like to change it. It had been used in twenty different places and you have to replace the name manually. Can you feel the pain? Go to the method declaration part of your code or to the method calling part, place your cursor to the method name and hit <strong>Shift + F6</strong>, and rename your method. Voila, you can see the changes being reflected in all the files.</p>
<h2 id="multi-cursor-alt-j"><strong>Multi Cursor (Alt + J)</strong></h2>
<p>This is personally my favorite shortcut. It is also a shortcut to flex with junior developers. It helps us to multi-select the matching content. Consider the scenario, where you have this SQL file.</p>
<pre><code><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> <span class="hljs-keyword">users</span>(<span class="hljs-keyword">id</span>, <span class="hljs-keyword">name</span>, address, phone) <span class="hljs-keyword">VALUES</span> (<span class="hljs-number">1</span>, <span class="hljs-string">'John'</span>, <span class="hljs-string">'ktm'</span>, <span class="hljs-string">'122233'</span>);
<span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> <span class="hljs-keyword">users</span>(<span class="hljs-keyword">id</span>, <span class="hljs-keyword">name</span>, address, phone) <span class="hljs-keyword">VALUES</span> (<span class="hljs-number">2</span>, <span class="hljs-string">'Tim'</span>, <span class="hljs-string">'ktm'</span>, <span class="hljs-string">'122234'</span>);
<span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> <span class="hljs-keyword">users</span>(<span class="hljs-keyword">id</span>, <span class="hljs-keyword">name</span>, address, phone) <span class="hljs-keyword">VALUES</span> (<span class="hljs-number">3</span>, <span class="hljs-string">'Tom'</span>, <span class="hljs-string">'ktm'</span>, <span class="hljs-string">'122235'</span>);
<span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> <span class="hljs-keyword">users</span>(<span class="hljs-keyword">id</span>, <span class="hljs-keyword">name</span>, address, phone) <span class="hljs-keyword">VALUES</span> (<span class="hljs-number">4</span>, <span class="hljs-string">'Lindy'</span>, <span class="hljs-string">'ktm'</span>, <span class="hljs-string">'122236'</span>);
<span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> <span class="hljs-keyword">users</span>(<span class="hljs-keyword">id</span>, <span class="hljs-keyword">name</span>, address, phone) <span class="hljs-keyword">VALUES</span> (<span class="hljs-number">5</span>, <span class="hljs-string">'Catherina'</span>, <span class="hljs-string">'ktm'</span>, <span class="hljs-string">'122237'</span>);
<span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> <span class="hljs-keyword">users</span>(<span class="hljs-keyword">id</span>, <span class="hljs-keyword">name</span>, address, phone) <span class="hljs-keyword">VALUES</span> (<span class="hljs-number">6</span>, <span class="hljs-string">'Bill'</span>, <span class="hljs-string">'ktm'</span>, <span class="hljs-string">'122238'</span>);
// 1000 of lines
</code></pre><p>You have to add one more column in this SQL called <strong>user_type</strong> with static value <strong>USER,</strong> are you going to do it manually? Definitely, not. There might be other options for this use case as well, but I am going to demonstrate the power of <strong>Alt + J.</strong> In the first line, place your cursor before VALUES and select phone) and hit <strong>Alt+J multiple times</strong> and you can see the exact word phone) being selected. This is what it looks like:</p>
<img alt="Image for post" src="https://miro.medium.com/max/1728/1*r3_wzuEdx3isNo8O4loCzQ.png" />

<p>Move your cursor before ) and type , along with your column name i.e user_type. There you go, we unleashed the power of <strong>Alt + J.</strong> Also, we can unselect from the last by hitting <strong>Alt + Shift + J</strong>.</p>
<img alt="Image for post" src="https://miro.medium.com/max/1942/1*Cw4lFSLPdQF7hi_hYGT5Gg.png" />

<h2 id="bookmark-ctrlshiftanykey-and-ctrlanykey">Bookmark (Ctrl+Shift+AnyKey and Ctrl+AnyKey)</h2>
<p>If you are working with multiple files, you might have to navigate between methods across different files. It will be a pain to go back and forth. Let’s say you are trying to fix a bug written by somebody else, you are already tired searching codes and you forgot the method name or class name you recently visited, it will be so infuriating. Adding a bookmark will help you to be more productive in such cases.</p>
<p>You can hit <strong>Ctrl+Shift+AnyKey</strong> to set a bookmark. For eg: <strong>Ctrl+Shift+1</strong>. Intellij IDEA will show a bookmark icon.</p>
<img alt="Image for post" src="https://miro.medium.com/max/660/1*iDVMrxklqXnIYWv_P6Ap_w.png" />

<p>You can work with other files and if you feel like jumping into this code, you can hit <strong>Ctrl+AnyKey (Ctrl+1 in this case)</strong> and you will be returned to this method. It’s that easy. Similarly, you can remove the bookmark by hitting <strong>Ctrl+Shift+AnyKey</strong>.</p>
<h2 id="inline-ctrlaltn"><strong>Inline (Ctrl+Alt+N)</strong></h2>
<p>I prefer deleting codes to writing codes. I love to refactor the code. This shortcut is used to inline the variable or method call. It’s mostly used while refactoring the code.</p>
<pre><code>Customer customer = getCusomer();
createPaymentIntent(customer);
</code></pre><p>In the snippet like above, if it makes sense to you to inline <em>getCustomer()</em> method, then you can place your cursor to the customer object and hit <strong>Ctrl+Alt+N.</strong> It will inline the code and the result, then, looks like:</p>
<pre><code><span class="hljs-selector-tag">createPaymentIntent</span>(getCusomer());
</code></pre><h2 id="extract-variablemethodfieldconstantparameter"><strong>Extract Variable/Method/Field/Constant/Parameter</strong></h2>
<p>This shortcut also makes refactoring easy.</p>
<p>Snippet-1:</p>
<pre><code>getCustomer(); //<span class="hljs-keyword">returns</span> Customer <span class="hljs-keyword">Object</span>
</code></pre><p>Select <em>getCustomer()</em> method and hit <strong>Ctrl+Alt+V</strong> to get the variable returned by the object. The result will be:</p>
<pre><code><span class="hljs-attribute">Customer</span> customer = getCustomer();
</code></pre><p>Snippet-2:</p>
<pre><code>Customer customer = <span class="hljs-built_in">new</span> Customer();
customer.setName("Customer");
customer.setAddress("Ktm");
customer.setMobile("9779852365321");
</code></pre><p>Let’s say, you want to refactor this piece of code into a method. You can select these blocks of codes and enter <strong>Ctlr+Alt+M</strong> in order to extract to a method. Intellij IDEA will show a popup where you can enter the name of the method along with the visibility (access modifiers).</p>
<p>Likewise, <strong>Ctrl+Alt+P</strong> is for extracting the method parameter. <strong>Ctrl+Alt+C</strong> is for extracting a constant variable and <strong>Ctrl+Alt+F</strong> is for extracting a field variable.</p>
<h2 id="live-templates"><strong>Live Templates</strong></h2>
<p>You can save time by using live templates for the code blocks you use repeatedly. Intellij Idea itself provides some live templates.  Let's check it out.</p>
<ul>
<li><strong>psf</strong>: Type psf and hit Tab,  <code>public static final</code> snippet will be generated.</li>
<li><strong>psfs</strong>: Type psfs and hit Tab, <code>public static final String</code> snippet will be generated.</li>
<li><strong>thr</strong>:  Type thr and hit Tab, <code>throw new</code> snippet will be generated.</li>
<li><strong>fori</strong>: Type fori and hit Tab, a for loop will be generated.</li>
<li><strong>iter</strong>: Type iter and hit Tab, a forEach loop will be generated.</li>
</ul>
<p>You can also define your custom live templates.</p>
<p>Thanks a lot for reading my article. If you know other cool shortcuts, then feel free to add in the comments :)</p>
]]></content:encoded></item><item><title><![CDATA[Stripe Payment Integration]]></title><description><![CDATA[At the time of writing this article, there is no official support of Stripe for React-Native. I, having knowledge of backend, was trying to create RESTful endpoints to integrate Stripe payment using Spring boot. Although the documentation of Stripe i...]]></description><link>https://blog.gautamsuraj.com.np/stripe-payment-integration</link><guid isPermaLink="true">https://blog.gautamsuraj.com.np/stripe-payment-integration</guid><dc:creator><![CDATA[Suraj gautam]]></dc:creator><pubDate>Thu, 10 Sep 2020 03:49:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1600414271288/UkdPg8cgY.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>At the time of writing this article, there is no official support of Stripe for React-Native. I, having knowledge of backend, was trying to create RESTful endpoints to integrate Stripe payment using Spring boot. Although the documentation of Stripe is aesthetically designed, I really had a tough time doing it. I find nothing useful for React-Native in the docs.</p>
<p>There are three ways by which we can initiate a payment using Stripe payment.</p>
<ol>
<li>Stripe Checkout</li>
<li>Charges API</li>
<li>PaymentIntent API</li>
</ol>
<p><strong>Stripe Checkout</strong> redirects customers to the prebuilt page and accepts payment. This is not what I wanted for my mobile application. <strong>Charges API</strong> was ok for me but it is recommended for the businesses in the USA and Canada. More importantly, it’s not SCA ready (Strong Customer Authentication) and only works for card payments. The only option left was to use <strong>PaymentIntent API.</strong></p>
<p>In this article, I am going to explain the backend and frontend (React-Native <a target="_blank" href="https://github.com/tipsi/tipsi-stripe">tipsi-stripe library)</a> flow for payment using Stripe.</p>
<ol>
<li>The user inputs the card details.</li>
<li>The frontend (React-Native) will call the Stripe API to create <a target="_blank" href="https://stripe.com/docs/api/payment_methods"><strong>PaymentMethod</strong></a> object using the card details (Card-number, Expiry date, CVC).</li>
<li>The frontend will send the Payment Method Id created from the response of Step-2 along with currency and amount to the backend.</li>
<li>The backend will create the Payment Intent Object using the payment method Id.</li>
<li>If the status of the PaymentIntent is <strong>requires_action</strong>, there is secure 3D authentication enabled for the payment and needs further processing. Hence, the backend will send payment intent <strong>client_secret</strong> to the frontend.</li>
<li>The frontend will use this <strong>client_secret</strong> and proceed for further authentication and payment from the frontend per se.</li>
<li>If the status of the PaymentIntent is other than <strong>requires_action,</strong> the backend will complete the transaction.</li>
<li>The backend will receive the subscribed events from the Stripe server using Webhooks. The backend then sends the Push Notification using <a target="_blank" href="https://expo.io/">Expo</a> to the frontend notifying the success and failure of the payment.</li>
</ol>
<p>Let’s see the code snippets. I used <a target="_blank" href="https://github.com/stripe/stripe-java"><strong>stripe-java</strong></a> library to communicate with the Stripe server.</p>
<p>The dependency in <strong>pom.xml</strong> looks like:</p>
<pre><code><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.stripe<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>stripe-java<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>${stripe.version}<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre><p>The  createPayment method looks like this:</p>
<pre><code>Stripe.apiKey = <span class="hljs-keyword">this</span>.secretKey;
    PaymentIntentCreateParams <span class="hljs-keyword">params</span> = PaymentIntentCreateParams.builder()
            .setCurrency(currency)
            .setAmount(getConvertedAmount(amount))
            .setPaymentMethod(paymentMethodId)
            .setConfirm(<span class="hljs-literal">true</span>)              
            .setReceiptEmail(SecurityContext.getUser().getUsername())         
.setConfirmationMethod(PaymentIntentCreateParams.ConfirmationMethod.AUTOMATIC)
.build();

PaymentIntent paymentIntent = createPaymentIntent(<span class="hljs-keyword">params</span>);
<span class="hljs-keyword">if</span> (REQUIRES_ACTION.<span class="hljs-keyword">equals</span>(paymentIntent.getStatus())) {
        <span class="hljs-comment">//requires 3D secure authentication in frontend</span>
 <span class="hljs-keyword">return</span> paymentIntent.getClientSecret();
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">return</span> EMPTY;
    }
}

<span class="hljs-function"><span class="hljs-keyword">private</span> PaymentIntent <span class="hljs-title">createPaymentIntent</span>(<span class="hljs-params">PaymentIntentCreateParams <span class="hljs-keyword">params</span></span>)</span> {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">return</span> PaymentIntent.create(<span class="hljs-keyword">params</span>);
    } <span class="hljs-keyword">catch</span> (StripeException e) {
        <span class="hljs-comment">//log</span>
    }
}
</code></pre><p>The webhooks API will be called by Stripe and it can be configured from the Stripe Dashboard. You can choose the event types that you would like to receive in your webhook endpoint. For payment success and failure, I am listening to <strong>payment_intent.succeeded</strong> and <strong>payment_intent.payment_failed</strong> events respectively.</p>
<p>The webhooks API looks like:</p>
<pre><code><span class="hljs-meta">@PostMapping(value = <span class="hljs-meta-string">"/your-webhook-endpoing"</span>)</span>
<span class="hljs-keyword">public</span> ResponseEntity&lt;<span class="hljs-built_in">Void</span>&gt; webhooks(<span class="hljs-meta">@RequestBody</span> String json, HttpServletRequest httpRequest) {

    Event event = validateStripeHeadersAndReturnEvent(json, httpRequest.getHeader(<span class="hljs-string">"Stripe-Signature"</span>));
    StripeObject stripeObject = getStripeObject(event);
    PaymentIntent paymentIntent = (PaymentIntent) stripeObject;
    <span class="hljs-keyword">this</span>.stripePaymentService.handlePaymentSuccess(event.getType(), paymentIntent);
    <span class="hljs-keyword">this</span>.stripePaymentService.handlePaymentFailure(event.getType(), paymentIntent);
    <span class="hljs-keyword">return</span> ResponseEntity.status(HttpStatus.OK).build();
}
</code></pre><p>As you can see, I am getting <strong>Stripe-Signature</strong> header from the request because I want to validate if the request is being sent by the Stripe server or not. The <em>validateStripeHeadersAndReturnEvent</em> method looks like:</p>
<pre><code><span class="hljs-keyword">private</span> Event validateStripeHeadersAndReturnEvent(<span class="hljs-built_in">String</span> payload, <span class="hljs-built_in">String</span> headers) {
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">return</span> Webhook._constructEvent_(
                payload, headers, <span class="hljs-built_in">this</span>.webhookSecret
        );
    } <span class="hljs-keyword">catch</span> (JsonSyntaxException e) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> UnAuthorizedException(<span class="hljs-string">"Invalid payload"</span>);
    } <span class="hljs-keyword">catch</span> (SignatureVerificationException e) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> UnAuthorizedException(<span class="hljs-string">"Invalid Signature"</span>);
    }
}
</code></pre><p>You can write your own logic after you receive webhooks. I am sending the success and failure push notifications.</p>
<p>Thanks a lot for reading this article :)</p>
]]></content:encoded></item><item><title><![CDATA[Haversine Formula for Spring Data JPA]]></title><description><![CDATA[I was working on a project where I have to find the nearest stores from the current location within X kilometer distance. I was skeptical if I can deliver the story within the promised timeframe. I googled and found out this cool thing called Haversi...]]></description><link>https://blog.gautamsuraj.com.np/haversine-formula-for-spring-data-jpa</link><guid isPermaLink="true">https://blog.gautamsuraj.com.np/haversine-formula-for-spring-data-jpa</guid><dc:creator><![CDATA[Suraj gautam]]></dc:creator><pubDate>Fri, 04 Sep 2020 08:41:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1600414364153/k514FeE44.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I was working on a project where I have to find the nearest stores from the current location within <strong>X</strong> kilometer distance. I was skeptical if I can deliver the story within the promised timeframe. I googled and found out this cool thing called Haversive Formula. I was able to deliver it way before the expected time. The <strong>Haversine</strong> formula calculates the shortest distance between two points on a sphere using their latitudes and longitudes measured along the surface. It is important for use in navigation.</p>
<p>I have latitude and longitude stored in the table. The Entity <strong>Store</strong> looks like:</p>
<pre><code><span class="hljs-variable">@Entity</span>
<span class="hljs-variable">@Table</span>(name = <span class="hljs-string">"STORE"</span>)
<span class="hljs-variable">@Getter</span>
<span class="hljs-variable">@Setter</span>
public class Store {
    <span class="hljs-variable">@Id</span>
    <span class="hljs-variable">@GeneratedValue</span>(strategy = GenerationType._IDENTITY_)
    private long id;
    <span class="hljs-selector-tag">private</span> <span class="hljs-selector-tag">double</span> <span class="hljs-selector-tag">latitude</span>;
    <span class="hljs-selector-tag">private</span> <span class="hljs-selector-tag">double</span> <span class="hljs-selector-tag">longitude</span>;
}
</code></pre><p>Let’s say now we want to find all the stores within a 10-kilometer distance from our current location then using Spring Data JPA repository we can do it as:</p>
<pre><code>public <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">StoreRepository</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">JpaRepository</span>&lt;<span class="hljs-title">Store</span>, <span class="hljs-title">Long</span>&gt;</span>{

<span class="hljs-built_in">String</span> HAVERSINE_FORMULA = <span class="hljs-string">"(6371 * acos(cos(radians(:latitude)) * cos(radians(s.latitude)) *"</span> +
        <span class="hljs-string">" cos(radians(s.longitude) - radians(:longitude)) + sin(radians(:latitude)) * sin(radians(s.latitude))))"</span>;

<span class="hljs-meta">@Query</span>(<span class="hljs-string">"SELECT s FROM Store s WHERE "</span> + HAVERSINE_FORMULA + <span class="hljs-string">" &lt; :distance ORDER BY "</span>+ HAVERSINE_FORMULA + <span class="hljs-string">" DESC"</span>)
<span class="hljs-built_in">List</span>&lt;Store&gt; findStoresWithInDistance(
<span class="hljs-meta">@Param</span>(<span class="hljs-string">"latitude"</span>) <span class="hljs-built_in">double</span> latitude,
 <span class="hljs-meta">@Param</span>(<span class="hljs-string">"longitude"</span>) <span class="hljs-built_in">double</span> longitude,
 <span class="hljs-meta">@Param</span>(<span class="hljs-string">"distance"</span>) <span class="hljs-built_in">double</span> distanceWithInKM );
</code></pre><p>The parameters latitude and longitude are your current location values whereas distance represents the distance you want to search within. (10KM in our case).</p>
<p>As you can see, in the Haversine Formula, we have used 6371. This is the value for the radius of the earth in KM. If you want to search using miles then you need to change it to <strong>3961</strong> from <strong>6371.</strong></p>
<p>Thanks a lot for reading my article :)</p>
]]></content:encoded></item><item><title><![CDATA[Object-Oriented Design Principles]]></title><description><![CDATA[Programming is fun until you have to incorporate a new requirement that changes the whole design of your code. Everyone writes code but it’s too difficult to write a code that your colleagues can understand. It’s difficult to write a code that sucks ...]]></description><link>https://blog.gautamsuraj.com.np/object-oriented-design-principles</link><guid isPermaLink="true">https://blog.gautamsuraj.com.np/object-oriented-design-principles</guid><category><![CDATA[Java]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[software development]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Object Oriented Programming]]></category><dc:creator><![CDATA[Suraj gautam]]></dc:creator><pubDate>Fri, 28 Aug 2020 08:45:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1600414593279/3JcnfLsnt.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><span class="r"></span>
Programming is fun until you have to incorporate a new requirement that changes the whole design of your code. Everyone writes code but it’s too difficult to write a code that your colleagues can understand. It’s difficult to write a code that sucks less and doesn’t succumb to changes. However, there are a few design principles that can be learned, practiced, and absorbed so that it will make us suck less.</p>
<p>Design principles are basic guidelines that help us to avoid bad object-oriented design. Nobody is going to point a gun towards you and make you adhere to it strictly. It’s not a rule of thumb but it will definitely help you. We are now going to see <strong>three</strong> principles.</p>
<ol>
<li>Encapsulate what varies.</li>
<li>Favor composition over inheritance.</li>
<li>Program to interface.</li>
</ol>
<h1 id="encapsulate-what-varies">Encapsulate what varies.</h1>
<p>The principle is so simple. Identify the aspects of the code that varies and isolate it with what stays the same. You gotta ask yourself</p>
<h2 id="does-this-code-change-every-time-i-get-the-new-requirement">“Does this code change every time I get the new requirement?”</h2>
<p>If the answer is yes then you now know what to do. Encapsulate. Let’s see an example.</p>
<pre><code><span class="hljs-built_in">public</span> <span class="hljs-type">void</span> connectToDatabase(String connectionType) {
    DBConnection <span class="hljs-keyword">connection</span> = <span class="hljs-keyword">null</span>;
    <span class="hljs-keyword">if</span> ("mysql".equals(connectionType)) {
        <span class="hljs-keyword">connection</span> = <span class="hljs-built_in">new</span> MySqlConnection();
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>("mongodb".equals(connectionType)){
        <span class="hljs-keyword">connection</span> = <span class="hljs-built_in">new</span> MongoConnection();
    }<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>("postgres".equals(connectionType)){
        <span class="hljs-keyword">connection</span> = <span class="hljs-built_in">new</span> PostgresConnection();
    }
    <span class="hljs-keyword">connection</span>.createConnection();
}
</code></pre><p>I bet every one of us has seen code like this and who knows we may still have such code running in production. So, let’s say we need to add an Oracle database in our code. How are we going to add it? Another else if condition, isn’t it? But let’s say there are a bunch of other important codes in the same file and while adding a new Oracle database you mistakenly touched other production codes in the same file which introduced many newer bugs. Had it been encapsulated, then there would have been a single place to change. By encapsulating it, our design will be much more flexible.</p>
<p>The part that will change with every new requirement is if-else conditions. So, we can create a factory class that will be solely responsible for creating database connections. I will not show how to create a factory class but I will show how the code looks once we encapsulated all the logics inside the factory class.</p>
<pre><code><span class="hljs-built_in">public</span> <span class="hljs-type">void</span> connectToDatabase(String connectionType) {
    DBConnectionFactory dbConnectionFactory = <span class="hljs-built_in">new</span> DBConnectionFactory();
    DBConnection <span class="hljs-keyword">connection</span> = dbConnectionFactory.getConnection(connectionType);
    <span class="hljs-keyword">connection</span>.createConnection();
}
</code></pre><p>With this approach, let’s say if you want to add an H2 database connection then you have to change only in DBConnectionFactory class.</p>
<h1 id="favor-composition-over-inheritance">Favor composition over inheritance</h1>
<p>In object-oriented programming (OOP), inheritance is <strong>IS-A</strong> relationship (A car is a vehicle) whereas composition is <strong>HAS-A</strong> relationship (A car has an engine).</p>
<p>Inheritance provides a great way to reuse the code but it becomes less effective once the hierarchy grows on. Classes and objects created through inheritance are <a target="_blank" href="https://en.wikipedia.org/wiki/Coupling_(computer_programming"><strong><em>tightly coupled</em></strong></a>) because if something is changed in the base class then it will affect its subclasses. But it’s not true for composition. The classes and objects created through composition are <a target="_blank" href="https://en.wikipedia.org/wiki/Coupling_(computer_programming"><strong><em>loosely coupled</em></strong></a>)<strong><em>.</em></strong> There is another great benefit of using Composition over Inheritance. Inheritance is not easily testable because to test derived class you also need superclass but the composition is as we can use mock objects.</p>
<h1 id="program-to-interface">Program to interface</h1>
<p>The term interface here doesn’t merely mean the keyword we have in Java programming language. It is a kind of contract that has a bunch of rules that needs to be followed by concrete classes that implement it. It is often called as program to the supertype. If we program to an interface rather than the concrete implementations then it provides the flexibility to exploit polymorphism.</p>
<p>The interface provides rules and doesn’t care whoever implements it and how the implementation looks like. Let’s take a real-world simple example.</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">FileUpload</span> </span>{
    <span class="hljs-keyword">void</span> upload(<span class="hljs-keyword">Object</span> o);
}
</code></pre><p>We want to upload the file in our application. There may be many different ways to do so. We can use Cloudinary, AWS S3 bucket, upload care, etc. So the implementations of FileUpload would look like AmazonS3FileUpload, CloudinaryFileUpload, UploadCareFileUpload etcetera.</p>
<p>Let’s program to interface.</p>
<pre><code>FileUpload fileUpload = <span class="hljs-built_in">new</span> CloudinaryFileUpload();
// code related <span class="hljs-keyword">to</span> fileupload
</code></pre><p>Great, our file uploading feature is working correctly and after one year, we want to switch our file uploading from Cloudinary to AmazonS3. We just need to change the implementation like:</p>
<pre><code>FileUpload fileUpload = <span class="hljs-built_in">new</span> AmazonS3FileUpload();
</code></pre><p>It will not break other codes because we are relying on the interface and the methods provided by it. We can only use methods defined within the FileUpload interface. Had it been concrete implementation with a bunch of extra methods, then it would have created a havoc.</p>
<pre><code>//program <span class="hljs-keyword">to</span> concrete implementation
CloudinaryFileUpload fileUpload = <span class="hljs-built_in">new</span> CloudinaryFileUpload();
//code related <span class="hljs-keyword">to</span> fileUpload
</code></pre><p>So, it’s always a good idea to program to an interface. Besides, the flexibility it provides, it is also easy to test. We can easily mock FileUpload interface wherever necessary.</p>
<hr />
<p>Thanks a lot for reading my article. If you have any suggestions, then they are welcomed.</p>
]]></content:encoded></item></channel></rss>