<?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 Eranga Dulshan on Medium]]></title>
        <description><![CDATA[Stories by Eranga Dulshan on Medium]]></description>
        <link>https://medium.com/@erangad?source=rss-5ac1df2eb2f0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CwSou4tbD7CilW-6UdsBrw.jpeg</url>
            <title>Stories by Eranga Dulshan on Medium</title>
            <link>https://medium.com/@erangad?source=rss-5ac1df2eb2f0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 13:08:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@erangad/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[Shipping to Production in Under 10 Minutes: ECS Express Mode, ECR, GitHub Actions, and Custom…]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://erangad.medium.com/shipping-to-production-in-under-10-minutes-ecs-express-mode-ecr-github-actions-and-custom-1dd30a962dc7?source=rss-5ac1df2eb2f0------2"><img src="https://cdn-images-1.medium.com/max/1536/1*A-OBMuvNHI_Fi_lCxbcyYQ.png" width="1536"></a></p><p class="medium-feed-snippet">ECS Express Mode &#x2014; AWS&#x2019;s newer, opinionated on-ramp to Amazon ECS &#x2014; simplifies much of the usual infrastructure setup into a single guided&#x2026;</p><p class="medium-feed-link"><a href="https://erangad.medium.com/shipping-to-production-in-under-10-minutes-ecs-express-mode-ecr-github-actions-and-custom-1dd30a962dc7?source=rss-5ac1df2eb2f0------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://erangad.medium.com/shipping-to-production-in-under-10-minutes-ecs-express-mode-ecr-github-actions-and-custom-1dd30a962dc7?source=rss-5ac1df2eb2f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dd30a962dc7</guid>
            <category><![CDATA[ecs-express]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[production-deployment]]></category>
            <category><![CDATA[custom-domain]]></category>
            <category><![CDATA[aws-ecs]]></category>
            <dc:creator><![CDATA[Eranga Dulshan]]></dc:creator>
            <pubDate>Sat, 01 Aug 2026 16:10:45 GMT</pubDate>
            <atom:updated>2026-08-30T18:01:08.864Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Twitter / X OAuth 2.0 social login in react native]]></title>
            <link>https://erangad.medium.com/twitter-x-oauth-2-0-social-login-in-react-native-27d02df6f2bb?source=rss-5ac1df2eb2f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/27d02df6f2bb</guid>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[login]]></category>
            <category><![CDATA[twitter-x]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[social-login]]></category>
            <dc:creator><![CDATA[Eranga Dulshan]]></dc:creator>
            <pubDate>Mon, 24 Jun 2024 03:51:25 GMT</pubDate>
            <atom:updated>2024-06-24T03:51:25.982Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently wanted to have sign in with X integrated to one of my react native apps. There are libraries that can be used for google and Linkedin in react-native. But I could not find an existing working that works for Twitter. So here is how I implemented the Twitter login.</p><blockquote>If you know how OAuth works you can jump in to <strong>Setting up a Twitter App </strong>section<strong>. </strong>If you just want the code, you can check here.<strong> </strong><a href="https://github.com/ErangaD/TwitterOAuth">https://github.com/ErangaD/TwitterOAuth</a></blockquote><p>First of all, I think it is better to have an idea of how X’s OAuth 2.0 works. First, we have to create an app in X’s developer console, where we will get a client ID and a client secret for the app. When the user logs in, it means that we get access to the X user data through that app.</p><p>Then, we request X’s authorization URL with the client ID and relevant scopes that we need, along with a redirection URL. We also have to set the allowed redirection URLs in the X console (we will get back to that later).</p><p>What X, or any other OAuth provider, does is verify the client ID and redirect URL provided. If they match, it will call or request the provided redirect URL with a specific code parameter attached to it.</p><p>Then, with that code and the client secret (that we obtained for the app created in X’s console), we request X’s token URL to get a token. This token allows us to access user data.</p><p>Ideally, we should not store both the client ID and client secret on the mobile side due to security risks. We need the client secret to obtain the final access token using the code that comes with the redirect URI. Therefore, we can provide a server URL as a redirect URI and handle the token retrieval process on the backend.</p><p>In this blog, to demonstrate how this works, I have implemented the final access token retrieval process on the client side (mobile app).</p><p><strong>Setting up a Twitter App</strong></p><p>First go to the <a href="https://developer.twitter.com/en/portal/projects-and-apps">Twitter/X Apps</a>. You should see the default X project there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYubrGi30wpu0IGtyxBNVA.png" /></figure><p>In the app settings you can see the edit option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vLnOWOpUFzPP2RVbOhEdPw.png" /></figure><p>When you scroll down you will see the app section. Add a website url and the redirect/callback urls. You can directly use the redirect url that I have used <a href="https://erangad.github.io/TwitterOAuth">https://erangad.github.io/TwitterOAuth</a> if you do not have one already. What I have used is a github page (source -&gt; index.html file in the repo) that acts as a redirect url.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6df6fTrRS-P5EIUQ3WxgQ.png" /></figure><p>Then you can copy the clientID and client secret from the keys and tokens section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GX0himtsAgNgkIC2KUBJ6w.png" /></figure><p>Now you have completed the Twitter / X side of configurations required.</p><p>So let’s get to coding. Here is my demo repo link that I am going to explain <a href="https://github.com/ErangaD/TwitterOAuth">here</a>.</p><blockquote><a href="https://github.com/ErangaD/TwitterOAuth">https://github.com/ErangaD/TwitterOAuth</a></blockquote><p>If you are cloning the above repo make sure you replace the relevant <strong>clientID</strong> and <strong>clientSecret</strong> within the code (<strong>App.tsx</strong>).</p><p>I have installed following additional modules.</p><blockquote>react-native-inappbrowser-reborn</blockquote><blockquote>uuid</blockquote><blockquote>query-string</blockquote><blockquote>react-native-get-random-values</blockquote><blockquote>ramda</blockquote><p>Make sure that you have setup the deep links as well. In the above repo I have setup following as the deep link.</p><blockquote><strong>my-scheme://</strong></blockquote><p>You can find more on setting up deep links in</p><p><a href="https://github.com/proyecto26/react-native-inappbrowser/tree/1f7299782c57f849b2256277ef1c20f50c13db9a#authentication-flow-using-deep-linking">https://github.com/proyecto26/react-native-inappbrowser/tree/1f7299782c57f849b2256277ef1c20f50c13db9a#authentication-flow-using-deep-linking</a></p><p>When the login button is pressed, the first thing we do is opening the Twitter authorization url with additional url parameters using the InAppBrowser installed.</p><pre>const onLoginPressed = async () =&gt; {<br>    const deepLink = getDeepLink(&#39;callback&#39;);<br>    const authState = uuid();<br>    const inappBorwserAuthURL = `${AUTHORIZATION_URL}?${querystring.stringify({<br>      response_type: &#39;code&#39;,<br>      client_id: clientID,<br>      scope: permissions!.join(&#39; &#39;).trim(),<br>      state: authState,<br>      redirect_uri: `${redirectUri}?redirect_url=${encodeURIComponent(<br>        deepLink,<br>      )}`,<br>      code_challenge: authState,<br>      code_challenge_method: &#39;plain&#39;,<br>    })}`;<br><br>    try {<br>      if (await InAppBrowser.isAvailable()) {<br>        InAppBrowser.openAuth(inappBorwserAuthURL, deepLink, {<br>          ephemeralWebSession: false,<br>          enableUrlBarHiding: true,<br>          enableDefaultShare: false,<br>        }).then(async (response: any) =&gt; {<br>          const {code} = getCodeAndStateFromUrl(response.url);<br>          const token = await getAccessToken(code, authState);<br>          console.log(&#39;INFO::accessToken::response::&#39;, token); // this is the access token received<br>        });<br>      } else {<br>        Linking.openURL(inappBorwserAuthURL); // in case any error try to open the inbuilt browser<br>      }<br>    } catch (error) {<br>      Linking.openURL(inappBorwserAuthURL); // in case any error try to open the inbuilt browser<br>    }<br>  };</pre><p>Here note these.</p><p><strong>inappBorwserAuthURL</strong> has an additional authState which is a generated uuid string this needs to be passed later with the token request.</p><p><strong>redirect_uri</strong> consists of the provided redirect_url + a deep link schema that is going to be used to navigate back to the app later.</p><p>The provided redirect_uri is the github page that I have created <a href="https://erangad.github.io/TwitterOAuth">https://erangad.github.io/TwitterOAuth</a>. The source code can be found in <strong>index.html</strong> file of the repo.</p><p>Since we provided redirect_uri as the <a href="https://erangad.github.io/TwitterOAuth"><strong><em>https://erangad.github.io/TwitterOAuth</em></strong></a><strong><em>?redirect_url=my-scheme://callback</em></strong></p><p>Twitter is going to redirect our initial request to the above url with two additional parameters (code and state like below).</p><p><a href="https://erangad.github.io/TwitterOAuth"><strong><em>https://erangad.github.io/TwitterOAuth</em></strong></a><strong><em>?redirect_url=my-scheme://callback&amp;code=’**code**’&amp;state=’**state**’</em></strong></p><p>In the github page, what I do is extracting those code and state parameters and passing back via the deep link to the app when the “click to navigate back to the app” link is pressed.</p><p>So the response we get from InAppBrowser callback above will have those data and scheme as the response url.</p><pre>const {code} = getCodeAndStateFromUrl(response.url);</pre><p>So we then extract that code and state and use that to get the access token.</p><pre>const getAccessToken = async (code: string, currentAuthState: string) =&gt; {<br>    const deepLink = getDeepLink(&#39;callback&#39;);<br>    const redirectUriWithRedirectUrl = `${redirectUri}?redirect_url=${encodeURIComponent(<br>      deepLink,<br>    )}`;<br>    const payload: string = getPayloadForToken({<br>      clientID,<br>      clientSecret,<br>      code,<br>      redirectUriWithRedirectUrl,<br>      currentAuthState,<br>    });<br>    const token = await fetchToken(payload);<br>    if (token.error) {<br>      return {};<br>    }<br>    return token;<br>  };</pre><p>Note that we have to use the authState (uuid) that we originally passed with the autorization url when we requested the access token as well.</p><p>As I mentioned before, this access token retrieval should ideally be done in the backend. So instead of the custom github page that I created, you can do the code extraction and access token retrieval at the backend and show a success message in the browser and navigate back to the app after that. What I have done is kind of a simulation of that.</p><p>So after this is fully complete you will see the token in the console.</p><pre>const token = await getAccessToken(code, authState);<br>// this is the access token received<br>console.log(&#39;INFO::accessToken::response::&#39;, token); </pre><p>Happy coding 😃</p><h4><strong>References</strong></h4><ul><li><a href="https://github.com/GoldenOwlAsia/react-native-twitter-signin?tab=readme-ov-file">GitHub - GoldenOwlAsia/react-native-twitter-signin</a></li><li><a href="https://github.com/proyecto26/react-native-inappbrowser">GitHub - proyecto26/react-native-inappbrowser: 📱InAppBrowser for React Native (Android &amp; iOS) 🤘</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27d02df6f2bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using OpenAI semantic search with Neo4J]]></title>
            <link>https://erangad.medium.com/using-openai-semantic-search-with-neo4j-8cab050ee553?source=rss-5ac1df2eb2f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cab050ee553</guid>
            <category><![CDATA[search]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[text]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[neo4j]]></category>
            <dc:creator><![CDATA[Eranga Dulshan]]></dc:creator>
            <pubDate>Fri, 06 Jan 2023 17:58:09 GMT</pubDate>
            <atom:updated>2023-01-06T17:58:28.161Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BJ6pb7cmSC6JueLq" /><figcaption>Photo by <a href="https://unsplash.com/@evgenit?utm_source=medium&amp;utm_medium=referral">Evgeni Tcherkasski</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently, OpenAI has become the hot topic. I had a database of pdf files that needed to be searched. I was using Neo4J and its lucene search for searching. Every Neo4J node contained the file url and the extracted pdf text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5lrA1uCKzKbKCTzcT-neJw.png" /></figure><p>And wanted to try out the latest OpenAI semantic search. In this blog, I will be discussing the path that I followed and hope it would be helpful for someone who is interested in similar technologies. I have used python and py2neo package for this and I expect the reader has knowledge on python, Neo4j and py2neo (python driver library for Neo4J).</p><p>First, I will explain the way OpenAI search works. OpenAI has some pre trained models that returns something called embeddings when text is given as input. Embedding is nothing but a vector with numeric values in 1536 dimensions. If we calculate the cosine similarity of two embedding vectors, from the final value we can decide whether they are related or not. Cosine similarity score vary between -1 and 1. So higher the value better the relatedness. So if we have already have the items that should be text searchable, we have to get those embeddings for those text and save it in the database and when a search query comes we have to get the embedding for the specific search term and then calculate the cosine similarity and sort based on the score (descending order) to get the search results.</p><p>You can also check <a href="https://github.com/openai/openai-cookbook/blob/main/examples/Semantic_text_search_using_embeddings.ipynb">this</a> from OpenAI examples list to further get an idea on semantic search.</p><p>Let’s move on to code level.</p><p>So you have to first create an OpenAI account and get an API key. The moment you create an account you get free API requests that worth $18. You can access OpenAI<a href="https://beta.openai.com/account/usage"> here</a> and create an API key <a href="https://beta.openai.com/account/api-keys">here</a> after login. Then with the API key, we can request the embedding vectors for the text in the existing database and save them in the database as an array (In my scenario I saved them in the same Neo4J node).</p><p>OpenAI provides few models that we can use to get embeddings. I have used</p><blockquote>text-embedding-ada-002</blockquote><p>model which is the one OpenAI also <a href="https://openai.com/api/pricing/">recommends</a> to use. Here is the python code to request embedding from the OpenAI.</p><pre>import logging<br>import time<br>import openai<br><br>logger = logging.getLogger(__name__)<br><br>openai.api_key = OPEN_AI_KEY<br><br><br>def get_embeddings_from_open_ai(text):<br>    cur_time = time.time()<br>    logger.info(&quot;INFO::get_embeddings_from_open_ai::starting::&quot;)<br>    response = openai.Embedding.create(<br>        input=text,<br>        model=&quot;text-embedding-ada-002&quot;<br>    )<br>    logger.info(f&quot;INFO::get_embeddings_from_open_ai::ended::{ time.time() - cur_time }&quot;)<br>    embeddings = response[&#39;data&#39;][0][&#39;embedding&#39;]<br>    return embeddings</pre><p>When we get a search query, we first request the embedding from the OpenAI for the search query and then we have to calculate the cosine similarity with every stored embedding vector that we have already stored. We have to do this for any search query. One option is to load every embedding array and do the calculation in python application layer. But with Neo4J, we can calculate the cosine similarity at the database level. For that you have to use Neo4J Graph Data Science (GDS) package. Installation instruction can be found <a href="https://neo4j.com/docs/graph-data-science/current/installation/">here</a> and summary of the process is shown in below screenshot (this is for the Neo4J server and if you are on Neo4J desktop you can find them in the same link above).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GIHOFy1XYKl89V6p3XdCtA.png" /><figcaption>Enabling data science package in Neo4J</figcaption></figure><p>You can find further examples in <a href="https://medium.com/neo4j/cosine-similarity-in-neo4j-d617b0442439">here</a> as well for cosine similarity calculation in Neo4J.</p><p>Now you can run the query to fetch the results based on cosine similarity. Here is the query that I used.</p><pre>import time<br>from py2neo import Graph<br><br><br>def get_neo4j():<br>    global neo4j_instance, uri, secrets<br>    if neo4j_instance is None:<br>        neo4j_instance = Graph(uri, auth=(secrets[&#39;neo4j_username&#39;], secrets[&#39;neo4j_password&#39;]))<br>    return neo4j_instance<br><br><br>def search(search_query):<br>    graph = get_neo4j()<br>    search_query_embedding = get_embeddings_from_open_ai(search_query)<br>    query = &quot;&quot;&quot;match(a:pdf) with a, gds.alpha.similarity.cosine(a.embeddings, %s) as similarity return a as pdf <br>            order by similarity desc limit %s&quot;&quot;&quot;<br>    query = query % (search_query_embedding, 20)<br>    pdfs = graph.run(query).data()<br>    return pdfs</pre><p>here we simply get the embedding for search query first and the we use the</p><blockquote>gds.alpha.similarity.cosine</blockquote><p>function from GDS for cosine similarity calculation and sort based on the score.</p><p>So when you insert more items to the database (in this case the pdfs), you can simply request embedding for that item’s text and store the embedding vector as an array with it and then it would be searchable.</p><p>Please also note that there are limitations to OpenAI API requests, they have the concept of tokens and for one request token count should not be greater than 8191 tokens. You can get an idea about the tokens in this <a href="https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them">article</a>.</p><p>That’s it and happy coding 😃 .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cab050ee553" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add third party SSL to Azure App Service]]></title>
            <link>https://erangad.medium.com/add-third-party-ssl-to-azure-app-service-53900b732a3e?source=rss-5ac1df2eb2f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/53900b732a3e</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[ssl]]></category>
            <category><![CDATA[azure-app-service]]></category>
            <category><![CDATA[ssl-certificate]]></category>
            <category><![CDATA[globalsign]]></category>
            <dc:creator><![CDATA[Eranga Dulshan]]></dc:creator>
            <pubDate>Fri, 26 Aug 2022 17:57:18 GMT</pubDate>
            <atom:updated>2022-08-26T17:58:04.247Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I had to configure a third party ssl to an azure app service application (Obviously for cost reasons 😃). So I will walk you through the process of doing it (I wanted to use a ssl from <a href="https://www.ssl2buy.com/">ssl2buy</a>).</p><p>So the idea is, we will create a certificate from a certificate authority and add that to Azure App Service. For any certificate authority (CA) like DigiCert or GlobalSign, we need to provide a certificate signing request in order to generate the ssl certificate. A CSR normally includes information about the business (common name (CN), Organisation, City, Country etc), the public key (generated from the server) and information about key type and length.</p><p>In azure you can generate a CSR using key vault. Search for key vaults and select it. Then create a key vault (if you already do not have any). And select Generate/Import.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KBSLYByH9h0KzbtDAC0Z3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d5WVWfMAObODaQ4B0T-ORQ.png" /></figure><p>Then provide the following information and create the certificate. After creation, select the created certificate from the list and choose certificate operations. You will see the download CSR option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KX2k5MygrRi4wPay_W8zkw.png" /><figcaption>certificate generation screen</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w-QrgOXlBB5RyyRrOP2DBQ.png" /><figcaption>list of certificates screen</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4lhSkzDmLP6yY8Q08tIftg.png" /><figcaption>certificate info screen</figcaption></figure><p>Download the CSR file, open the file and copy the full key and submit that to certificate authority and get the certificate (usually CA emails the certificate). Upon receiving the certificate from CA, you can copy the text to a file and rename the file with extension “.crt”. In the same view (above certificate info screen), you can select the “<strong>Merge Signed Request”</strong> option and upload the created “.crt” file in order to complete the process. Then the certificate state will be turned to “<strong>Enabled</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*whRuK4D7laICFJCrp6r1gA.png" /><figcaption>adding certificate to app service screen</figcaption></figure><p>Up to now, we have created the certificate and store in the azure key vault. Now you can go to the app service that you need to add the certificate and select ssl. In the ssl settings, select Private Key Certificates and select import key vault certificate. And you can select the key vault and the generated certificate and submit. You will see that ssl has been applied (It could take few minutes 😉).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53900b732a3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Braintree Subscriptions Integration to Angular + Spring Boot app]]></title>
            <link>https://erangad.medium.com/braintree-subscriptions-integration-to-angular-spring-boot-app-5083331e05c5?source=rss-5ac1df2eb2f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5083331e05c5</guid>
            <category><![CDATA[braintree-payment-gateway]]></category>
            <category><![CDATA[braintree]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[paypal]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Eranga Dulshan]]></dc:creator>
            <pubDate>Sun, 15 Aug 2021 05:40:32 GMT</pubDate>
            <atom:updated>2021-08-15T05:40:32.266Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QSEXdFKyj7MRWVUNBFLLQw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jdent?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jason Dent</a> on <a href="https://unsplash.com/s/photos/gateway?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Recently I integrated the Braintree payment gateway to a project that I worked on and found it somewhat hard along the way. So I thought of writing this blog.</p><p>You can follow the <a href="https://developer.paypal.com/braintree/docs/start/overview">Braintree documentation</a> as well. It has lot of information and someone may find it hard to connect the pieces. So this blog focuses on quickly connecting the important pieces related to Braintree subscriptions and make it available to use.</p><p>First of all, you should have a Braintree sandbox account <a href="https://sandbox.braintreegateway.com/login">https://sandbox.braintreegateway.com/login</a>. After login into the account, you should create a plan first .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZLJM39VyK5HyiyN1yHHyVw.png" /></figure><p>These are my configurations for the yearly plan. You can create any plan as you like since this is a sandbox account. We will use this created plan later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*uGmgkeGUue0VulYVSxGk_w.png" /></figure><p>Then add the Braintree server side SDK dependencies using maven (to pom.xml) in the Spring Boot app (<a href="https://developer.paypal.com/braintree/docs/start/hello-server">link</a>).</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;com.braintreepayments.gateway&lt;/groupId&gt;<br>   &lt;artifactId&gt;braintree-java&lt;/artifactId&gt;<br>   &lt;version&gt;3.11.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>I used Braintree Drop-In UI which looks like this after integrating to the Angular side (<a href="https://developer.paypal.com/braintree/docs/guides/client-sdk/setup">drop-in documentation</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B54FY_hPWM2RZC6CvuUWTw.png" /></figure><p>The problem is how do you integrate the <a href="https://developer.paypal.com/braintree/docs/guides/client-sdk/setup">javascript SDK</a> in to Angular component. Here is what I did.</p><p>First you need to add javascript SDK to index.html file.</p><blockquote>&lt;script src=”https://js.braintreegateway.com/web/dropin/1.30.1/js/dropin.min.js&quot;&gt;&lt;/script&gt;</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6MPXtr9ADyETnKtFDVyzrw.png" /></figure><p>When you add the script tag, it creates a global <strong>Braintree</strong> object that we can access. Now we can initialise the Braintree drop in using that. You need to provide a place for the drop in ui to be initialised.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*-lGGLXoVfB-N7ljB1JZeuA.png" /></figure><p>I want the drop in ui to be placed inside &lt;div id=&quot;dropin-container&quot;&gt; inside the component. And also we need a submit button (id with “submit-button” in the screenshot) so that we can initiate the subscription process.</p><p>So the init process from the javascript side (Angular) inside the component looks like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47faa8a566d51f84b859d3be8ab77924/href">https://medium.com/media/47faa8a566d51f84b859d3be8ab77924/href</a></iframe><p>So the important things to be noted are,</p><ol><li>Declaring the <strong>braintree</strong> variable (line 4) in order to access it inside ngOnInit().</li><li>Usage of the token returned by the Spring Boot backend for <strong>authorization</strong> parameter (getClienToken() method in line 18 calls the <strong>client-token </strong>end point — You can find the merchantId, public and private keys in the <a href="https://sandbox.braintreegateway.com/merchants/2b54jxfnxzr7xtby/home">control panel of Braintree</a>).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*C6BG2KVZdSrI9PacQsFbkw.png" /></figure><p>3. ‘#dropin-container’ selector (line 21) which specifies the location to inject the drop in ui.</p><p>4. When someone clicks the activate button after adding a card (<a href="https://developer.paypal.com/braintree/docs/guides/credit-cards/testing-go-live/">test cards</a> in this case for sandbox) or with Paypal, we get the <a href="https://developer.paypal.com/braintree/docs/guides/payment-method-nonces">payment method nonce</a> inside payload which should be sent to the server to create the subscription (<strong>create-subscription</strong> endpoint in the server gets called by line 44 with the nonce inside user object).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*rhcxoz1zXwPZK3AjeHx0Lg.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85ea58a40be9b5777a4a645b4a9e722e/href">https://medium.com/media/85ea58a40be9b5777a4a645b4a9e722e/href</a></iframe><p>I have added the comments inside the code itself for clarity. So, yeah this is what you will need to just have the Braintree subscriptions working in your app. If you need more subscription options like free trials, there are options in <a href="https://developer.paypal.com/braintree/docs/reference/response/subscription">subscription</a> section of Braintree documentation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5083331e05c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upload a remote image to S3 without saving it first with python]]></title>
            <link>https://erangad.medium.com/upload-a-remote-image-to-s3-without-saving-it-first-with-python-def9c6ee1140?source=rss-5ac1df2eb2f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/def9c6ee1140</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[image]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[upload]]></category>
            <dc:creator><![CDATA[Eranga Dulshan]]></dc:creator>
            <pubDate>Sun, 14 Feb 2021 15:32:30 GMT</pubDate>
            <atom:updated>2021-07-03T07:45:36.328Z</atom:updated>
            <content:encoded><![CDATA[<h3>Upload an image to S3 without locally saving it in python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1X0-98EiQNkwBJj2vnTTqQ.jpeg" /><figcaption>Image by <a href="https://unsplash.com/@cdr6934">Chris Ried</a></figcaption></figure><p>In this I will be discussing about uploading a static file that is somewhere else to a S3 bucket without saving it first.</p><p>First of all you need an aws account. Let’s create a IAM user (it is not needed to create a user if you already have one other than the admin user). After logging in, go to the IAM dashboard (<a href="https://console.aws.amazon.com/iam/home">https://console.aws.amazon.com/iam/home)</a>. Then select users and add user. Name the user as you like. And also do not forget to set permissions for S3 (select attach existing policies -&gt; check amazon s3 full access check box).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*X9-o9kVEQAkXGX-b2WAlAg.png" /></figure><p>After user creation, you will be able to see the access key and secret access keys. Save it somewhere else for now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4XIKLa8eSpMigKwrBPMDEA.png" /></figure><p>Then create a S3 bucket. (<a href="https://s3.console.aws.amazon.com/s3/home">https://s3.console.aws.amazon.com/s3/home</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*PGBXZ50cdXiyxretaLwNQw.png" /></figure><p>keep the other settings as it is and create the bucket.</p><p>So let’s get to coding. We are going to use boto3 (amazon sdk for python).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c32c1993ee84535993ad69fa8b4a3b8/href">https://medium.com/media/2c32c1993ee84535993ad69fa8b4a3b8/href</a></iframe><p>Here I have used access and secret keys inside the code for simplicity. But usually those are stored as environment variable. So what is happening is that we request the remote file using requests and without saving the file we get the raw byte stream to put that into the <strong>upload_fileobj </strong>method.</p><p>So that is it. You will be able to see the uploaded file in the S3 bucket after executing the code.</p><p>Happy coding :).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=def9c6ee1140" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Spring Boot + Angular app using Docker on Ubuntu(on ec2)]]></title>
            <link>https://erangad.medium.com/deploy-spring-boot-angular-app-using-docker-on-ubuntu-on-ec2-1fb38b5c7533?source=rss-5ac1df2eb2f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fb38b5c7533</guid>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Eranga Dulshan]]></dc:creator>
            <pubDate>Fri, 25 Dec 2020 14:35:05 GMT</pubDate>
            <atom:updated>2020-12-25T14:35:05.906Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Lpb8wd5wMmXQUYte3JLxKA.jpeg" /><figcaption>Image by len_lov</figcaption></figure><p>This weekend I wanted to deploy a spring boot app + an angular app to an ec2 instance using docker. It is true that aws have their own ecs service to handle containers. But out of curiosity, I decided to do the deployment on an ec2. I have used a t2 micro instance (1GB ram). You can use any ubuntu server you like.</p><p>Here I am focusing only on deployment. That means I assume someone reads this has a working spring boot and angular app which are ready for deployment.</p><p>First connect to your ubuntu instance. Then install Docker. Use following commands to install docker on ubuntu.</p><pre>sudo apt update</pre><pre>sudo apt install apt-transport-https ca-certificates curl software-properties-common</pre><pre>curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -</pre><pre>sudo add-apt-repository &quot;deb [arch=amd64] <a href="https://download.docker.com/linux/ubuntu">https://download.docker.com/linux/ubuntu</a> focal stable&quot;</pre><pre>sudo apt update</pre><pre>apt-cache policy docker-ce</pre><pre>sudo apt install docker-ce</pre><p>check the docker status</p><pre>sudo systemctl status docker</pre><p>If you see an output similar to following, you are good to go.</p><pre>docker.service - Docker Application Container Engine</pre><pre>Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)</pre><pre>Active: <strong>active (running)</strong> since Fri 2020-12-25 08:21:03 UTC; 9s ago</pre><pre>TriggeredBy: <strong>●</strong> docker.socket</pre><pre>Docs: https://docs.docker.com</pre><pre>Main PID: 20814 (dockerd)</pre><p>If you would like to use docker without sudo. Use the following command and exit the tty and login again to the ubuntu instance.</p><pre>sudo usermod -aG docker ${USER}</pre><p>And I have used postgreSQL as the database in my spring boot application. So get a postgreSQL instance up using docker.</p><pre>docker run --name postgresql-container -p 5432:5432 -e POSTGRES_PASSWORD=2021WillBeFine! -d postgres</pre><p>Use any password you like. I have used 2021WillBeFine! :). After this you will have a database instance of postgreSQL (you can spin up any database you have used in spring application).</p><p>Connect to the postgreSQL running in docker with following command.</p><pre>docker exec -it 3f4e305f9956 bash</pre><p>You can find the container id (3f4e305f9956) using “docker ps”. And login to postgres database inside the container.</p><pre>psql -h localhost -p 5432 -U postgres -W</pre><p>It will ask for password and use the one you specified earlier. And create a database to be used by the application (spring boot).</p><p>And build a docker image with the spring boot application. Make sure that you are using a correct database url. Since I am running a local database server on docker, I have used localhost.</p><pre>datasource:<br>  url: jdbc:postgresql://localhost:5432/YourDatabaseName<br>  username: postgres<br>  password: 2021WillBeFine!</pre><p>And also specify a context path so that we can use that to connect to spring boot in <strong>Nginx</strong> configuration (I will describe that later). I am using “/api”.</p><pre>server:<br>  port: 8080<br>  servlet:<br>    context-path: /api</pre><p>This is the Dockerfile configuration.</p><pre>FROM openjdk:8-jdk-alpine<br>ARG <em>JAR_FILE</em>=target/*.jar<br>COPY ${<em>JAR_FILE</em>} app.jar<br>ENTRYPOINT [&quot;java&quot;,&quot;-jar&quot;,&quot;/app.jar&quot;]</pre><p>Before creating the image make sure you build the jar file (inside a folder name target from the Dockerfile). I am using maven.</p><pre>mvn clean install -DskipTests</pre><p>Let’s create the image. Use following on a terminal where Dockerfile is located.</p><pre>docker build -t username/repo-name .</pre><p>Here we have a username and a repo name. Username is the username of the docker hub (<a href="https://hub.docker.com/">https://hub.docker.com/</a>). So that I can push the image to the docker hub. If you do not have one, create one and login to the docker hub before trying to push the image. Following is the command to push a docker image.</p><pre>docker push username/repo-name</pre><p>Use your own username and repo name instead.</p><p>Now we have pushed the spring boot image to the docker hub. Let’s create a Nginx image with angular. First build the angular app.</p><pre>ng build --prod --aot</pre><p>You will have the dist folder and the project_name inside the dist.</p><p>So create a Dockerfile (where dist folder is) like this to build an image with Nginx as base image.</p><pre>FROM nginx:alpine</pre><pre>COPY /dist/projectname /usr/share/nginx/html</pre><p>And build the image.</p><pre>docker build -t yourusername/angular-app .</pre><p>Then push the image to the hub as before. And within the server (ubuntu), run the our containers using the built images. Let’s run our spring app. Since I am using the local postgreSQL database I run the application on the host network.</p><pre>docker run --net=host -d yourUserName/repo-name</pre><p>This will download the image and start a container. Make sure that your repositories are public in the docker hub.</p><p>We are going to use Nginx to serve our angular application as well as a reverse proxy to the spring application. So we have to use a Nginx configuration file. Create a “nginx.conf “ file on the ubuntu server and put the following instruction to the Nginx. I am using vim. (<strong>vi nginx.conf</strong>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8f98b18013c4d3baa9c6c8a794089b7/href">https://medium.com/media/c8f98b18013c4d3baa9c6c8a794089b7/href</a></iframe><p>Now run the nginx (angular-app) with the above configuration file as follows.</p><pre>docker run --net=host -d -p 80:80 -v /$PWD/nginx.conf://etc/nginx/nginx.conf:ro yourUserName/angular-app</pre><p>What does this do is, this get the image we uploaded (named angular-app), apply the config file we created as read only (:ro).</p><p>Now type the ip of the server on the browser and see the angular app (Make sure you have allowed the TCP traffic for port 80 in the attached security group if you are using ec2). And also send a request to the spring boot application and see whether it works or not (http://ip/api). That is where the context path (/api) comes in to the picture (We have configured Nginx to forward traffic that comes to the /api to spring boot application).</p><p>So that is it guys. Hope this would help someone to deep dive into deploying applications using docker.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fb38b5c7533" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create CI/CD pipeline for nodejs express with Gitlab]]></title>
            <link>https://erangad.medium.com/create-ci-cd-pipeline-for-nodejs-express-with-gitlab-6c420a956b10?source=rss-5ac1df2eb2f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c420a956b10</guid>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[gitlab-ci]]></category>
            <category><![CDATA[express]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[gitlab]]></category>
            <dc:creator><![CDATA[Eranga Dulshan]]></dc:creator>
            <pubDate>Sun, 06 Sep 2020 10:37:47 GMT</pubDate>
            <atom:updated>2020-09-06T10:37:47.997Z</atom:updated>
            <content:encoded><![CDATA[<p>CI/CD allows the developers to deliver the code more frequently and reliably. Implementation of CI/CD is known as the pipeline. Here we are going to build a simple pipeline for a nodejs express app with Gitlab to deploy to an ec2.</p><p>If you do not have an express app already, first create one. I am not going to describe creating an express app here. If you do not have any experience, <a href="https://expressjs.com/en/starter/installing.html">this</a> is a simple guide.</p><p>So now you have an express app. Then you need to add <strong>.gitlab-ci.yml</strong> file to your source folder. If we have this file, every time we push to gitlab upstream, the instructions within this file will be executed by a runner in gitlab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/145/1*baM-5htiSH8ujDUM9mGSWw.png" /><figcaption>.gitlab-ci.yml</figcaption></figure><p>Here is process of the simple pipeline that I am going to build in brief. When the code is pushed to a branch (called <strong>pre-prod</strong>), we will create a ssh connection with ec2 from the gitlab. Then we create a folder in the ec2 server and clone the project there. Then we use <a href="https://pm2.keymetrics.io/"><strong>pm2</strong></a> runner to run the express app. All these are executed using the created ssh connection.</p><p>Here is my .<strong>gitlab-ci.yml </strong>file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*QKc4-HO5IAqT3rNUb0jHeg.png" /></figure><p>Let’s see what are the options we have here. First we create a job (<strong>deployToAWS</strong>)(this is called a job). Then we define the stage. You can find more about stages <a href="https://docs.gitlab.com/ee/ci/yaml/#stages">here</a>. Then using <strong>only, </strong>we define the branch that this job needs to be applied to. Then we have the <strong>before_script</strong> option to specify commands that needs to be run before the job gets started. What happens here is that we set configurations to initiate the ssh connection with the ec2. It is not different than how we initiate ssh connection from our pc (<strong>ssh -i path-to-pem user@ip</strong>). I also have set <strong>StrictHostKeyChecking</strong> to <strong>no</strong>. Because when the initial ssh connection happens with a server, it asks to add the host to known hosts. Then you give an input <strong>yes/no </strong>from your terminal. But this ssh connection initiates from the gitlab, there is no one to enter that input and press enter right. So we have set that to “<strong>no”</strong> by default. Here you also see a <strong>$PRIVATE_KEY </strong>term which is an environment variable. It is the key string inside <strong>.pem</strong> file which is used to access the ec2.</p><p>How does that environment variable come to the action. I will explain. In gitlab we can set up variables. In the gitlab project you can go to <strong>Settings -&gt; CI/CD </strong>from the left panel. In that we have the environment variables section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yjUgXgSmm-ylWV0AyROOtQ.png" /></figure><p>Here I have set up two variables. DEPLOY_SERVERS and PRIVATE_KEY. Here is my PRIVATE_KEY variable (value is the private key string from the <strong>.pem</strong> file).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wMNpUuXo1ynsTVFSGGt3hA.png" /></figure><p>Here is my DEPLOY_SERVERS variable. I have set the ip of the server that I am going to deploy the code to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*beZpfsWiBSI4bGjnF5cOuw.png" /></figure><p>Okay, coming back to the <strong>.gitlab-ci.yml. </strong>Then we have the <strong>script </strong>section. There I have specified the path to a bash script which is on another file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*AyanCr7iDYwEbNAXLY0yvg.png" /></figure><p>In the DEPLOY_SERVER section, I have set only one server. If you want multiple, you can add comma separated ip values there. So here I am initiating a ssh connection with each server (in this case only one). And run the script in the restart.sh.</p><p>Here is my <strong>restart.sh</strong> file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*WUvFunXvVXpOGMz49Q2RaA.png" /></figure><p>This file contains the commands just to restart the server. That means we have to do some initial setup in the server. For that we have to login to the server by ourselves. There we clone the project initially, install npm modules and start the pm2 process (command - <strong>pm2 start app.js</strong>). If you run this for the first time, the pm2 process id will be <strong>0</strong>. Why are we doing this for the first time is, then we do not have to specify those things in the <strong>restart.sh </strong>file. We can just do the restarting the server using the gitlab runner.</p><p>So in the restarting.sh script, first we delete the existing directory. Then do the cloning, go to the cloned directory, install node modules and restart the pm2 process (<strong>pm2 restart 0</strong> - <strong>0</strong> means the process id which we took by running for the first time by logging to the server by ourselves earlier). And note that I have used a token before the <strong>@gitlab.com </strong>with the gitlab url<strong>. </strong>You can get such a token in <strong>Settings -&gt; Repository. </strong>There you can create deploy tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OMsi6_P0r442BPDA6pZzNw.png" /></figure><p>You will get a token upon creation and you can set the user name and token like following.</p><blockquote><a href="https://*********-repo-deply-token:pg33FMeH1qeVChF5UzZL@gitlab.com/******/*******.git">https://username:token@gitlab.com/******/*******.git</a></blockquote><p>Why we use this is because we need to avoid additional setup or prompts for password during the execution of the script.</p><p>Now if you push to the specified branch (in the <strong>only </strong>section), a job will be started. You can see the jobs in <strong>CI/CD -&gt; Jobs </strong>section.</p><p>That’s it. Now the server will be restarted in the ec2 with the updated changes every time you push to the specified branch only if the job was successful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hwtaAox7MUTeWQM47q5cBQ.png" /></figure><p>So folks, this is just a very simple CI/CD pipeline. You can add build, test and deployment stages in to the pipeline after this and see how we can benefit with the pipelines in different stages.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c420a956b10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Multiple React-Native Dev Servers.]]></title>
            <link>https://erangad.medium.com/running-multiple-react-native-dev-servers-7d35ea980a40?source=rss-5ac1df2eb2f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d35ea980a40</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[multiple]]></category>
            <category><![CDATA[dev]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[bundler]]></category>
            <dc:creator><![CDATA[Eranga Dulshan]]></dc:creator>
            <pubDate>Wed, 29 Apr 2020 18:12:28 GMT</pubDate>
            <atom:updated>2020-04-29T18:12:28.451Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h17UXPR3UQ_G6c6IptrzdQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@danielkorpai?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Daniel Korpai</a> on <a href="https://unsplash.com/s/photos/multiple-phone?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>When you run <strong>react-native run-android</strong> or <strong>react-native run-ios </strong>it starts the bundler on port 8081 and install the app on emulator or simulator or device. When one process is running on a port, we can not start another on the same port. So what if you want to develop two react-native apps at the same time. Here is the process.</p><p>You can run one metro bundler on default 8081 by running</p><blockquote>react-native run-android</blockquote><p>for android and</p><blockquote>react-native run-ios</blockquote><p>on ios. It will also install the app on emulator or device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*dYobltDXYijYk5_52K5FiA.png" /></figure><p>You can run a different metro bundler (other app that you want to build) on a different port (let’s say port 8082) using following command.</p><blockquote>react-native start — port 8082</blockquote><p>Spot the difference that this will only start the metro bundler without installing the app on an emulator or on a device. So, what you can do is running <strong>react-native run-android</strong> or <strong>react-native run-ios</strong> (depending on platform that you are developing) on the second project folder too. That will install the app on emulator/s or device/s (you can use multiple emulators or devices if you like).</p><p>Then find the last installed app on emulator/s or device/s and open it. Get the following screen by shaking the device or tapping the menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*wvfZEeLyntnySur3fJ1kYw.png" /></figure><p>Then in the Settings menu, you will have the <strong>debug server host and port </strong>option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*mEvFpcnQVXn5B0q-d0PYaA.png" /></figure><p>In that, you can set the ip and port of the metro bundler for the second app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*J79NNNDq-l3kwPQrzLY6tg.png" /></figure><blockquote>For example: 192.168.8.100:8082</blockquote><p>Do not use localhost or 127.0.0.1 since that is local to the device or emulator. Always use the ip of the machine that you are developing the apps. Now if you reload the app, the second app will request bundle from the 8082 metro bundler. And the first one will request from the 8081 by default. Like wise you can develop many apps in react-native at the same time.</p><p>Happy Coding 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d35ea980a40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load testing a REST api using POST requests]]></title>
            <link>https://erangad.medium.com/load-testing-a-rest-api-using-post-requests-6b0338196af0?source=rss-5ac1df2eb2f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b0338196af0</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[post]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Eranga Dulshan]]></dc:creator>
            <pubDate>Sun, 29 Mar 2020 09:47:32 GMT</pubDate>
            <atom:updated>2020-03-29T09:47:32.244Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s say you have built a REST api and you want to know how well it will perform when it is in use. In the development environment, mostly it is you that is using the REST api (you are the only user). But in the production environment there may be hundreds or thousands of users who will be using the REST api. We cannot wait until our api to go to the production to evaluate the performance with increased number of users.</p><p>There are many open source tools out there to load test a REST api. I will be discussing two tools (GUI and non-GUI) in a linux environment.</p><ol><li>Apache Benchmark (ab)</li><li>JMeter (Using GUI)</li></ol><h3><strong>Apache Benchmark</strong></h3><p>This is a simple tool (Non-GUI) for load testing by <a href="http://httpd.apache.org/docs/2.4/programs/ab.html">Apache</a>. You have to first install apache benchmark by (on linux).</p><blockquote>sudo apt install apache2-utils</blockquote><p>Since we want to send a JSON body, we have to create a JSON file with the keys and values that we want to send to the api.</p><p>I created a JSON file named test.json.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*8_t3AxA7fs4-fROIIiRmLg.png" /><figcaption>test.json</figcaption></figure><p>Then you can call your api as follows.</p><blockquote>ab -c 1-n 10 -p test.json -T application/json <a href="http://3.22.27.224:8000/api/v1/sites/trend/product/languages/en">http://127.0.0.1:8000/api/v1/sites/trend/product</a></blockquote><p>Let’s analyze the parameters we have set in the <strong>ab </strong>(apache benchmark). There are many more parameters that you can find <a href="http://httpd.apache.org/docs/2.4/programs/ab.html">here</a>.</p><p>-c: Number of multiple requests to perform at a time. Default is one request at a time.</p><p>-n: Number of requests to perform.</p><p>-T: To set content type header (we have set that to application/json since we are sending a JSON).</p><p>-p: To specify the file containing data to post.</p><p>Following is the response for the above request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*1FtUGq3A-iw5HgsAB0D0uA.png" /><figcaption>ab test results</figcaption></figure><p>Let’s analyze the results.</p><p>10.263 seconds have been taken to the test and the longest response time is 1316ms. Average response time is 1026ms. Something interesting to note is the complete and failed requests.</p><p><strong>Complete requests: </strong>Number of successful responses received</p><p><strong>Failed requests: </strong>Number of requests that were considered a failure.</p><p>We sent 10 requests. But two have been listed as failed even though all 10 are listed complete. There is another line below the <strong>Failed requests </strong>showing the number of requests that failed due to connecting, reading, incorrect content length, or exceptions. In our case, the two have been listed as incorrect content length. Which means the content lengths of two responses are different compared to the first response’s content length. In my case it is desirable.</p><p>Let’s change the parameters (concurrency to 2 and number of requests to 20) and see the results.</p><blockquote>ab -c 2 -n 20 -p test.json -T application/json <a href="http://3.22.27.224:8000/api/v1/sites/trend/product/languages/en">http://127.0.0.1:8000/api/v1/sites/trend/product</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*HCP94EUj24T7AYNihTMnyw.png" /><figcaption>ab test results 2</figcaption></figure><p>Now the mean response time is 1502ms. So the response time has been increased. Like that you can analyze your api with varying loads.</p><p>Specially ab comes in handy when you want to measure something you did is optimizing your api or not.</p><h3><strong>JMeter</strong></h3><p>First you have to download the JMeter binary from <a href="https://jmeter.apache.org/download_jmeter.cgi">here</a>. After downloading, you can extract the folder and go to the bin folder. You can open the JMeter GUI by executing <strong>./jmeter.sh </strong>on the terminal inside the<strong> bin </strong>folder. It will open up following UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YLux5HdnQPuknmTXxso6ow.png" /></figure><p>If you are to load test using JMeter, you have to first create a test plan. In order to add a test plan, you have to first add a thread group. For that, right click on the <strong>Test Plan. </strong>It will give a menu like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b-PVV6MtklbLqggaUKF52w.png" /></figure><p>And select the <strong>Add -&gt; Threads -&gt; Thread Group</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t6Oi3uzIFF-RnycdZpKX5g.png" /></figure><p>Thread group screen looks like following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wPeMoorm5CbkWQ-wbu4HSg.png" /><figcaption>Add Thread Group</figcaption></figure><p>There you can basically configure the <strong>number of threads, ramp-up period</strong> and the <strong>loop count</strong>. What is meant by those.</p><ul><li><strong>Number of Threads</strong>: Simulates the number of users connecting concurrently to the REST api.</li><li><strong>Loop Count</strong>: Number of times to execute the test</li><li><strong>Ramp-Up Period</strong>: The amount of time for creating the total number of threads (users). If set to zero, JMeter will create all the threads immediately. If set to 100 and number of users to 100, thread(user) will be created every second.</li></ul><p>I set those as following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8AwKkvijlG4sGVKwdIb7Ug.png" /><figcaption>Set Thread Group Parameters</figcaption></figure><p>Then in order to perform http requests, we have to add <strong>HTTP Request</strong> element to the thread group. For that right click on the thread group and select</p><p><strong>Add -&gt;Sampler -&gt; HTTP Request</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5mc1XlPw6hLznamNPqsmlA.png" /><figcaption>Add HTTP Request Element</figcaption></figure><p>This give you a screen as following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*faVvzzx9zTRC46sbqL3umg.png" /></figure><p>In this section you can specify the protocol (http), ip address or domain name, port number, method of the request (GET, POST, PUT …), the url path, parameters and request data etc. Here I will be testing a <strong>POST</strong> request with a <strong>JSON</strong> body. Here is the sample.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WrwmR2hpTuHbhwvtw5pg0A.png" /><figcaption>Configured Request</figcaption></figure><p>Since I am sending a request with JSON body, I have to instruct the server that I am sending JSON data. Therefore, I have to set the <strong>Content-Type </strong>header to <strong>application/json</strong> with our requests. Therefore we have to add <strong>HTTP Header Manager</strong> configuration element to the <strong>HTTP Request</strong> element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZa_ZK2zEgsYG22l78ct4w.png" /><figcaption>Add Header Manager</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QGO8BtPeYeB0M3dJgzUE1A.png" /><figcaption>Header Manager</figcaption></figure><p>Then using the add button at the bottom you can add headers. I added the Content-Type header as follows. You can other headers too if you want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6nsnWM8s6UHZTZV8vWvSA.png" /><figcaption>Add Content-Type header</figcaption></figure><p>Now you have to configure the way you want to get the results. It can be done by adding a listener. There are multiple listeners that you can use. I will use <strong>View Results In Table </strong>listener. In order to do that right click on the Thread group and select Add -&gt;Listener -&gt; View Results In Table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mLD2hsyt-gSi1i1iySF1Rw.png" /><figcaption>Add View Results in Table Listener</figcaption></figure><p>On the screen that you get, you can specify a file name to get results to a csv file (<strong>test_result.csv </strong>in my case). Also do not forget to save the test plan while you are doing the changes.</p><p>So I ran my test using the <strong>green play</strong> button. If you click the <strong>View Results In Table </strong>from the navigation panel, you can see the results. Here is the test results using the table view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYaLIDWRpM3AbkujWp4UnQ.png" /><figcaption>First Results set</figcaption></figure><p>As I have mentioned earlier, for this test I am using,</p><p>Number of Threads = 10</p><p>Ramp-up time period = 10s</p><p>Loop Count = 1</p><p>In the test results, there are two columns that we should be focusing on.</p><ol><li>Sample Time (Response Time)</li><li>Latency</li></ol><p>here is the difference between two</p><p><strong>Latency</strong> is the time between request was sent and response has started to be received. <strong>Sample Time</strong> is the time between request was sent and response has been fully received. So <strong>Sample Time</strong> always &gt;= L<strong>atency.</strong></p><p>You can see the latency and sample time of each request. You can also see the average sample time with deviation on the bottom. In this test, average time was 1384ms. Let’s increase the number of users to 20 with the same Ramp-up time period.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BkJtVhWQS9ANUpFu2k6dqw.png" /><figcaption>Second Result</figcaption></figure><p>Now the average time has been increased to 8394ms. You can see that with the increased number of users the latency has been increased.</p><p>Similarly, we can test any API to see the behavior with the varying loads and identify issues with the api while processing heavy loads.</p><p>By Load testing, you can change the parameters as you like and see the results, identify issues with the api and fix them (query optimizations, caching, load balancing etc).</p><p>There are many other open source tools as well.</p><ol><li><a href="https://www.joedog.org/siege-home/">Siege</a></li><li><a href="https://github.com/giltene/wrk2">Wrk2</a></li><li><a href="https://locust.io/">Locust</a></li></ol><p>Hope I have provided a head start to the load testing. Happy Coding 😃 😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b0338196af0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>