<?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[BATC — BFI Agile Thought Community - Medium]]></title>
        <description><![CDATA[Official technology blog of BFI Agile Thought Community (BATC) - Medium]]></description>
        <link>https://medium.com/batc?source=rss----90163a577ddd---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>BATC — BFI Agile Thought Community - Medium</title>
            <link>https://medium.com/batc?source=rss----90163a577ddd---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 21:11:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/batc" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Combining RSA + AES Encryption to secure REST Endpoint With Sensitive Data]]></title>
            <link>https://medium.com/batc/combining-rsa-aes-encryption-to-secure-rest-endpoint-with-sensitive-data-eb3235b0c0cc?source=rss----90163a577ddd---4</link>
            <guid isPermaLink="false">https://medium.com/p/eb3235b0c0cc</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[data-security]]></category>
            <dc:creator><![CDATA[Timotius Pamungkas]]></dc:creator>
            <pubDate>Tue, 26 Apr 2022 14:13:13 GMT</pubDate>
            <atom:updated>2022-04-26T23:11:06.281Z</atom:updated>
            <content:encoded><![CDATA[<p>There are so many links out there who explains about encryption, particularly symmetric encryption using AES, and asymmetric encryption using RSA. For the sake of coding implementation, I will re-write them here, as simple (and short) as possible.</p><p>There are basically some important terms:</p><p><strong><em># Encryption</em></strong></p><p>you want to provide data to your partner, but don’t want anybody else know what the data is -only you and your partner can know the data-. So you encrypt the data. Instead of sending plain data (e.g. <strong><em>I Love You</em></strong>), you and your partner have a secret key to mask the plain data. Suppose the secret key is XXX (only you and your partner know it). You encrypt the plain data using the secret key, so it masked and became <strong><em>MFf$2jr0akb3302Amr02+53mZa9rYsA2j9f</em></strong>. You send this masked string (encrypted data) to your partner.</p><p><strong><em># Decryption</em></strong></p><p>The other side of coin. Your partner receive string <strong><em>MFf$2jr0akb3302Amr02+53mZa9rYsA2j9f </em></strong>(encrypted data)<strong><em>. </em></strong>Using secret key (XXX), your partner decrypt the encrypted data, so it became plain string <strong><em>I Love You</em></strong>. Encrypted data can only decrypted back using matching key. A wrong key will not show the plain data.</p><p><strong><em># Symmetric Encryption</em></strong></p><p>You and your partner has same one key (XXX) for encryption / decryption.</p><p><strong><em># Asymmetric Encryption</em></strong></p><p>You are not not really good at keeping secret, and the key (XXX) might be leaked. Your partner worry that someone will have the key (XXX), steal encrypted message you sent, then use the leaked key and decrypt the message. So your partner decide to keep the key (she is really good at keeping secret!).</p><p>Problem is, you still need to encrypt the data then send encrypted data. But you cannot has the key (XXX). Your partner then provide asymmetric key. Your partner has pair of key :</p><ul><li>public key PP1 (which she said: Just share it to everyone, it is public anyway, anybody can know).</li><li>she also has private key QQ1 (which she keeps by herself, thus called as private key)</li><li>This PP1 and QQ1 key pair is irreplacable each other. So if “someone” has PP1 (it is public anyway), but does not has QQ1, this “someone” cannot decrypt the message. The way asymmetric encryption works, the pair must be exact (PP1-QQ1, but not PP2-QQ1 or PP1-QQ2)</li></ul><p>You use public key PP1 to encrypt the plain message (<strong><em>I Love You</em></strong>), resulting <strong><em>590–2nnZas+21v0j5LAia90AmKf\jil2b4sG90.sa9F95z </em></strong>which you send yo your partner.</p><p>Your partner use the matching private key (QQ1) to decrypt <strong><em>590–2nnZas+21v0j5LAia90AmKf\jil2b4sG90.sa9F95z</em></strong><em> </em>and she gets <strong><em>I Love You</em></strong></p><p>“Someone” intercept the message, gets <strong><em>590–2nnZas+21v0j5LAia90AmKf\jil2b4sG90.sa9F95z. </em></strong>This “someone” has PP1 key (it is public, remember), but he does not has QQ1 private key. This “someone” cannot use PP1 to decrypt it. The only person can decrypt the message is your partner (she is the only one who has QQ1 private key).</p><p>Problem solved!</p><p><strong><em># AES Encryption</em></strong></p><p>Popular symmetric encryption. Can encrypt large data.</p><p><strong><em># RSA Encryption</em></strong></p><p>Popular asymmetric encryption. Can only encrypt limited amount of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/0*I9f0bG3xRYtDhrjK.jpg" /></figure><p><strong><em># Use Case on Data Interchange using REST API</em></strong></p><p>You are a company, and you have partner company. Your job : provide customer data (email, phone, and 50 more fields) in form of json. You have partner company. The customer data is considered sensitive, and only partner company can know. So when your partner access <em>https://you.com/api/{customerId}</em> you need to provide encrypted customer data. Somebody intercept the traffic and get the data, they will get only encrypted data.</p><p>You and partner company cannot trust anyone for encrypting such sensitive data. Only your partner can decrypt the data. So symmetric encryption cannot be used. To resolve this, in a way, asymmetric encryption must take place. Problem : asymmetric RSA encryption an only encrypt limited amount of data, not the whole 50+ fields. So you need to encrypt the full data using symmetric encryption (AES), AND put a way to utilise asymmetric encryption (RSA). Your company partner will owns the RSA public-private key, and send only the public key to you to encrypt data.</p><p>This is how it should works.</p><ol><li>Your partner owns public key PP9 and private key QQ9</li><li>Your partner hit GET <em>https://you.com/api/{customerId} </em>providing RSA-public key on request header. Kind of</li></ol><pre>curl --location --request GET &#39;https://you.com/cust099&#39; --header &#39;rsa-public-key: PP9&#39;</pre><p>2. For each request, you generate random AES key (XX9), then encrypt the customer data using AES (symmetric). The customer data became <strong><em>NgqUCBFoLq7qn1RhOKNy/yDuy1pFsLYd1k7mR6913+oXfLMtDK#5MPtFBpcNkyb</em></strong></p><p>This AES key XX9 is <strong>always </strong>randomly generated for each request.</p><p>3. You encrypt <strong>the AES key </strong>(XX9) using provided RSA public key. So XX9 became <strong><em>klf0Ak4Nz9</em></strong></p><p>4 You give the encrypted customer data (<strong><em>NgqUCBFoLq7qn1RhOKNy/yDuy1pFsLYd1k7mR6913+oXfLMtDK#5MPtFBpcNkyb</em></strong>) as API response, along with encrypted AES key <strong><em>klf0Ak4Nz9</em></strong> (from step 3). So the response is basically:</p><p>Response header &gt; encrypted-AES-key : <strong><em>klf0Ak4Nz9</em></strong></p><p>Response body &gt; <strong><em>NgqUCBFoLq7qn1RhOKNy/yDuy1pFsLYd1k7mR6913+oXfLMtDK#5MPtFBpcNkyb</em></strong></p><p>So there are two encrypted data here:</p><ul><li>Response header provides encrypted AES (symmetric) key. This AES key is randomly generated for each response, and encrypted using RSA (asymmetric). Means only your partner can decrypt the AES key.</li><li>Response body provided customer data, encrypted using AES.</li></ul><p>Note that the AES key is sent as part of response (to be precise : at response header). But instead of sending plain AES key, the key itself is asymmetrically encrypted using RSA. Since for each request-response, an AES key is randomly generated, a response body can only decrypted using key that is sent along, on it’s own response header.</p><p>5. Your partner company decrypt the AES key <strong><em>klf0Ak4Nz9 </em></strong>using their matching private key (QQ9, which only they know the key). So they get plain AES key XX9</p><p>6. Your partner company uses decrypted AES key XX9 to decrypt <strong><em>NgqUCBFoLq7qn1RhOKNy/yDuy1pFsLYd1k7mR6913+oXfLMtDK#5MPtFBpcNkyb </em></strong>so they get the plain customer data (email, phone, and 50 other fields).</p><p><strong><em># Java Implementation</em></strong></p><p>Create a <a href="https://start.spring.io/">new spring boot project</a> with dependency on spring web and lombok (optional). Then, add <a href="https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on">bouncycastle</a> dependency</p><pre>implementation ‘org.bouncycastle:bcprov-jdk15on:1.70’</pre><ul><li>Let’s just say we are going to send customer data (simplified): <a href="https://gist.github.com/timpamungkas/bb77d1dbfc134868e8a284c7afab5b70">here</a></li><li>This is the cryptography service for encrypt / decrypt RSA or AES : <a href="https://gist.github.com/timpamungkas/457f152443e77818d0b18902c317c96f">here</a></li><li>This is the API implementation for sending data : <a href="https://gist.github.com/timpamungkas/73ea229f0f2c225ab16db733b368a3cb">here</a></li></ul><p>Generating public / private key pair can be done by several means. There is also <a href="https://www.devglan.com/online-tools/rsa-encryption-decryption">online generator</a>, hence your company partner can generate by themselves.</p><p>For the sake of sample, let’s say that RSA public key is 1024 bit length : <strong><em>MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCF+7HXO77T1pO2tn1cFGC98ZsiYZCOXV4Psq3eRJ02wd5F4f5sdq+jdetBnvNJJ1ubO0dvCeC6zu89esgsEwz/6a+nZaRD0TUoXPsDnA/gsOi1IKMd9warVirjhfogfcj5yzAZMv9Vgbl+Zj5gXj7z6nvs6otyFtGOAu47RnvrSwIDAQAB</em></strong></p><p>And the matching RSA private key is <strong><em>MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIX7sdc7vtPWk7a2fVwUYL3xmyJhkI5dXg+yrd5EnTbB3kXh/mx2r6N160Ge80knW5s7R28J4LrO7z16yCwTDP/pr6dlpEPRNShc+wOcD+Cw6LUgox33BqtWKuOF+iB9yPnLMBky/1WBuX5mPmBePvPqe+zqi3IW0Y4C7jtGe+tLAgMBAAECgYB7R1yaKsnpxr0BWCY+bC2bd8wDNXw50eTzUreyFLYHJRisekWMbSQsphpBtcwqWkFqsn+GxrL1j+QHUIsQKrNBDGW0qwNa6X2DeOyf7OOTsOqLxvCMhBri1vesfK/xiB//UZLLXMOCnyapnCcXQRRRIPltN5xtsWKANuxrOMvF+QJBALm7w+/8NA3tFUfpED0qiG9cjte3oQL5ccqEdQ9op3JTgT/24j9jLgBJejV7z4quszhMI0s+KwvH7wDvHPa3u1UCQQC4q+3iF3OutxUl33T2b7qEa2TB9Dby22STwsahI5SdKF5shT/eZpFQe6ZSZ+VJjXeE/gs1dTQz9TcgRZdGI0wfAkATeEFj6NY0F4RBk4bmQo0mz1cR+efg/fEVv6jdwqS68VH9OI4jAuyRjyJGdQIekY2r+x9ABfZRN9YwDODGZCA5AkEAoRKE2DDwW7GgpnnzAIePPbSWG32w975YSXEX4rCwDSuKwEiw3oDDulk/Rp0MJk1XtA4JJMVnlPIK9QD94tUirQJBAJO49L8KLaC4bdPcqhikZN1rqNPViU0UKwsVDvPxTf2eG5PRi9z3LNMOtrzdMJIqLKxfy8vk5aPzP7nwLQF0O8Q=</em></strong></p><p>When running the app above and access endpoint with public RSA key using this curl</p><pre>curl -X &#39;GET&#39; \   &#39;http://localhost:8080/api/crypto/encrypted_string&#39; \   -H &#39;accept: text/plain&#39; \   -H &#39;public-key: MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCF+7HXO77T1pO2tn1cFGC98ZsiYZCOXV4Psq3eRJ02wd5F4f5sdq+jdetBnvNJJ1ubO0dvCeC6zu89esgsEwz/6a+nZaRD0TUoXPsDnA/gsOi1IKMd9warVirjhfogfcj5yzAZMv9Vgbl+Zj5gXj7z6nvs6otyFtGOAu47RnvrSwIDAQAB&#39;</pre><p>Then it will produce response body like this (will be different each hit, even if the data is same)</p><pre>dCuZsm96q2LuzkYtRoiZJo9jDohMLj8VFPmI3hO6IjlKaL4esLfnAbMe55dO1ttbvNUWJ3XqJe75jD8ns1F4KP3e4/Kgf7gWs8Fgh3q2lvLA6uauJfeo72DQNg6mMc4OpfuP10kB0I2/qdkn3vjESA==</pre><p>Also response header that contains AES key (encrypted using RSA, will be different for each hit)</p><pre>encrypted-aes-key: dNQluEjN+srTx2WrVwQvMGETfMBBc/7BoXYtqr/1DKOktrSWBdJJhFEJjayngU9CS9GzGFHzQlQt5WhszDcppwf29dDwt6PfcI1n+8KT8ntQIVj8vCLLgTAu4wW3HHKXYe1Tf93x7GZWqrk+XUlhmspVio7Jsh7MMmO54ryXyP0=</pre><p>Nice. You (the API provider) securely provides customer data.</p><p><strong># The Partner Side</strong></p><p>Partner, which has private key, then can decrypt the data they receive. A simplifed application, using data from above,will be like this.</p><pre>public class CustomerDecryptor {</pre><pre>  public static void main(String[] args) throws Exception {<br>    var cs = new CryptographyService();</pre><pre>    var rsaPrivateKey = cs.getRSAPrivateFromBase64(<br>   &quot;MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIX7sdc7vtPWk7a2fVwUYL3xmyJhkI5dXg+yrd5EnTbB3kXh/mx2r6N160Ge80knW5s7R28J4LrO7z16yCwTDP/pr6dlpEPRNShc+wOcD+Cw6LUgox33BqtWKuOF+iB9yPnLMBky/1WBuX5mPmBePvPqe+zqi3IW0Y4C7jtGe+tLAgMBAAECgYB7R1yaKsnpxr0BWCY+bC2bd8wDNXw50eTzUreyFLYHJRisekWMbSQsphpBtcwqWkFqsn+GxrL1j+QHUIsQKrNBDGW0qwNa6X2DeOyf7OOTsOqLxvCMhBri1vesfK/xiB//UZLLXMOCnyapnCcXQRRRIPltN5xtsWKANuxrOMvF+QJBALm7w+/8NA3tFUfpED0qiG9cjte3oQL5ccqEdQ9op3JTgT/24j9jLgBJejV7z4quszhMI0s+KwvH7wDvHPa3u1UCQQC4q+3iF3OutxUl33T2b7qEa2TB9Dby22STwsahI5SdKF5shT/eZpFQe6ZSZ+VJjXeE/gs1dTQz9TcgRZdGI0wfAkATeEFj6NY0F4RBk4bmQo0mz1cR+efg/fEVv6jdwqS68VH9OI4jAuyRjyJGdQIekY2r+x9ABfZRN9YwDODGZCA5AkEAoRKE2DDwW7GgpnnzAIePPbSWG32w975YSXEX4rCwDSuKwEiw3oDDulk/Rp0MJk1XtA4JJMVnlPIK9QD94tUirQJBAJO49L8KLaC4bdPcqhikZN1rqNPViU0UKwsVDvPxTf2eG5PRi9z3LNMOtrzdMJIqLKxfy8vk5aPzP7nwLQF0O8Q=&quot;);</pre><pre>    var encryptedAESCipherKey = &quot;dNQluEjN+srTx2WrVwQvMGETfMBBc/7BoXYtqr/1DKOktrSWBdJJhFEJjayngU9CS9GzGFHzQlQt5WhszDcppwf29dDwt6PfcI1n+8KT8ntQIVj8vCLLgTAu4wW3HHKXYe1Tf93x7GZWqrk+XUlhmspVio7Jsh7MMmO54ryXyP0=&quot;;<br>    var plainCipherKey = cs.decryptRSA(encryptedAESCipherKey, rsaPrivateKey);</pre><pre>    var encryptedCustomerResponse = &quot;dCuZsm96q2LuzkYtRoiZJo9jDohMLj8VFPmI3hO6IjlKaL4esLfnAbMe55dO1ttbvNUWJ3XqJe75jD8ns1F4KP3e4/Kgf7gWs8Fgh3q2lvLA6uauJfeo72DQNg6mMc4OpfuP10kB0I2/qdkn3vjESA==&quot;;<br>    <br>    var plainMsg = cs.decryptAES(encryptedCustomerResponse, plainCipherKey);</pre><pre>    System.out.println(&quot;Plain message : &quot; + plainMsg);<br>  }<br>}</pre><p>Which will produce output below.</p><pre>Plain message : {&quot;customerName&quot;:&quot;Customer name -2046994620&quot;,&quot;customerId&quot;:&quot;cust47174675&quot;,&quot;dateOfBirth&quot;:&quot;1993-08-26T00:00:00&quot;}</pre><p>Of course, since partner owns the private key, only partner company can obtain this data. If there is man-in-the middle attack, which intercepts traffic and get the public key and encrypted response, he cannot decrypt the customer data.</p><p><strong># More Way to Secure REST API</strong></p><p><a href="https://www.udemy.com/course/rest-api-security-with-java-spring-boot-what-how/?referralCode=1BD24AF33EB41F3336C3">Securing REST API</a> is more than encryption. There are <a href="https://www.udemy.com/course/rest-api-security-with-java-spring-boot-what-how/?referralCode=1BD24AF33EB41F3336C3">many ways and techniques</a> that can be used for various cases. For more technical implementation of REST API security, see <a href="https://www.udemy.com/course/rest-api-security-with-java-spring-boot-what-how/?referralCode=1BD24AF33EB41F3336C3">here</a>.</p><p>Just my 2 cents</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb3235b0c0cc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/batc/combining-rsa-aes-encryption-to-secure-rest-endpoint-with-sensitive-data-eb3235b0c0cc">Combining RSA + AES Encryption to secure REST Endpoint With Sensitive Data</a> was originally published in <a href="https://medium.com/batc">BATC — BFI Agile Thought Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KsqlDB User Defined Function (Scalar, Tabular, Aggregational) — UDF, UDTF, UDAF]]></title>
            <link>https://medium.com/batc/ksqldb-user-defined-function-scalar-tabular-aggregational-udf-udtf-udaf-dc0d4ea9bd23?source=rss----90163a577ddd---4</link>
            <guid isPermaLink="false">https://medium.com/p/dc0d4ea9bd23</guid>
            <category><![CDATA[ksql]]></category>
            <category><![CDATA[event-stream-processing]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Timotius Pamungkas]]></dc:creator>
            <pubDate>Mon, 25 Apr 2022 08:09:39 GMT</pubDate>
            <atom:updated>2022-05-03T00:44:55.138Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kafka &amp; KsqlDB User Defined Function (Scalar, Tabular, Aggregational) — UDF, UDTF, UDAF</h3><p>Apache kafka is good, and having kafka stream is great for transforming data stream as they arrived. Extend those items further, and we will get KsqlDB. KsqlDB basically is ”SQL for Kafka”. We can work using sql-like syntax (almost the same, but not really the same with relational database SQL), with quite many -but not as many as relational SQL- built in functions.</p><p>Instead of writing consumers for working with kafka stream using java or python or go client, we can do something like this, which is something like CREATE TABLE statement on relational database SQL. Note that this article is just a portion of Apache Kafka (and KsqlDB) power. For the full power of Apache Kafka ecosystem + Java Spring, you can <a href="https://www.udemy.com/course/apache-kafka-with-java-spring-boot-theory-hands-on-coding/?referralCode=5C42CAF98051BB9CBA0A">see this post</a>.</p><pre>CREATE STREAM mypeoplestream` (<br>  personid INT,<br>  firstname VARCHAR, <br>  lastname VARCHAR,<br>  birthdate DATE<br>) WITH (<br>  KAFKA_TOPIC=&#39;t-people&#39;,<br>  VALUE_FORMAT=&#39;JSON&#39;<br>);</pre><p>Then we can works with ksql, no coding required. You want to take current data? Then just use</p><pre>SELECT *<br>  FROM mypeoplestream;</pre><p>You want to get each data as soon as they arrive? Add EMIT CHANGES like this. This is what we call as event-streaming data.</p><pre>SELECT *<br>  FROM mypeoplestream<br>EMIT CHANGES;</pre><p>Want to take all people with first name starts with John?</p><pre>SELECT *<br>  FROM mypeoplestream<br>WHERE firstname LIKE &#39;John%&#39;;</pre><p>Or case sensitive “John”, “john”, “JoHn”, etc? Use function UCASE.</p><pre>SELECT *<br>  FROM mypeoplestream<br>WHERE UCASE(firstname) LIKE &#39;JOHN%&#39;;</pre><p>Want to count how many person with name like John? Use COUNT. Note, it has EMIT CHANGES statement since ksql is not exact match to relational database SQL. Aggregation function like COUNT requires EMIT CHANGES,which will continuously do the aggregation as the data arrived.</p><pre>SELECT UCASE(firstname), COUNT(personid)<br>  FROM mypeoplestream<br>GROUP BY UCASE(firstname)<br>EMIT CHANGES;</pre><p>So far, we have seen two KsqlDB functions : UCASE and COUNT. There are a lot of KsqlDB functions, which falls into three categories:</p><ul><li><a href="https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-reference/scalar-functions/">scalar functions</a> : simple functions, like <a href="https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-reference/scalar-functions/#parse_date">parse string to date</a>, <a href="https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-reference/scalar-functions/#round">rounding</a>, <a href="https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-reference/scalar-functions/#ifnull">null handler</a>, etc</li><li><a href="https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-reference/table-functions/">table functions</a>, or so called “flatmap” in several programming languages. Basically takes an input and produce one or more output</li><li><a href="https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-reference/aggregate-functions/">aggregation functions</a> : averaging, counting, summing, basically getting several data and deduct output from them</li></ul><p>In relational database, we can create function (stored procedure), defining custom logic according to our needs. In KsqlDB, we can also write our own functions. This custom function called as user-defined. As the function falls into three category, and so does the custom function:</p><ul><li>User-defined-function (UDF) : scalar</li><li>User-defined-table-function (UDTF) : tabular</li><li>User-defined-aggregation-function (UDAF) : aggregation</li></ul><p>The built-in functions are quite complete, but at times,it might not sufficient. Take, for example, if we work on loan company, we might need function to:</p><ul><li>estimate loan monthly installment <strong>(scalar)</strong></li><li>generate loan schedule, contains installment due date along the loan period <strong>(tabular)</strong></li><li>calculate loan rating based on actual payment date <strong>(aggregation)</strong></li></ul><p><strong># Let’s Start Code</strong></p><p>In this sample, I will use empty gradle project, but maven will works too. We later will need to package the udf as jar. For that, I will use gradle shadow plugin.</p><pre>plugins {<br>  id &#39;com.github.johnrengelman.shadow&#39; version &quot;7.1.2&quot;<br>}</pre><p>By the time this article written, ksqldb only support up to java 11. So we will use source compatibility version 11.</p><pre>sourceCompatibility = &#39;11&#39;</pre><p>The ksql udf library is available on confluent repository, we need to add that repository.</p><pre>repositories {<br>  mavenCentral()<br>  maven {<br>    url &quot;https://packages.confluent.io/maven&quot;<br>  }<br>}</pre><p>We need some library there : ksqldb udf, kafka api, and kafka connect api.</p><pre>dependencies {<br>  implementation &quot;io.confluent.ksql:ksqldb-udf:7.0.1&quot;<br>  implementation &quot;org.apache.kafka:kafka_2.13:3.1.0&quot;<br>  implementation &quot;org.apache.kafka:connect-api:3.1.0&quot;<br>}</pre><p>Add parameter to invoke java compiler with the -parameters flag. This enables the compiler to retain method parameter names at runtime, which ksqlDB can use as auto-generated documentation.</p><pre>compileJava {<br>  options.compilerArgs &lt;&lt; &quot;-parameters&quot;<br>}</pre><p>And this is the setting for generated jar file. It will later has name ksqldb-udf, version 1.0.0, located at folder build/udf-jar.</p><pre>shadowJar {<br>  archiveBaseName.set(&#39;ksqldb-udf&#39;)<br>  archiveClassifier.set(&#39;&#39;)<br>  archiveVersion.set(&#39;1.0.0&#39;)<br>  destinationDirectory.set(file(&#39;build/udf-jar&#39;))<br>}</pre><p>Full snippet for build.gradle available <a href="https://gist.github.com/timpamungkas/f96a19f3cafb45dd8577ae59f76672a2">here</a></p><p><strong># The Service Class</strong></p><p>For the business logic, create file LoanCalculator.java.</p><p>We later will round monthly payment calculation into two decimal, so add a static method for that purpose.</p><pre>public static double round(double original, int decimalPlaces) {<br>  double operand = Math.pow(10d, decimalPlaces);</pre><pre>  return Math.round(original * operand) / operand;<br>}</pre><p>Then the method to calculate the monthly installment. It needs principal loan amount, annual interest rate, and loan period in month. All of those values must be 1 or more. The loan formula is a simple mathematic, where we calculate the interest, the total payment which is principal plus interest, then divide the total payment with loan period month, rounding the result to two decimals.</p><pre>public static double calculateMonthlyInstallment(double principalLoanAmount, double annualInterestRate, int loanPeriodMonth) { <br>  if (principalLoanAmount &lt; 1 || annualInterestRate &lt; 1 || loanPeriodMonth &lt; 1) {<br>    throw new IllegalArgumentException(“All parameters value must be 1 or more”);<br>  }<br>  <br>  var interest = (annualInterestRate / 100d) * (loanPeriodMonth / 12d) * principalLoanAmount;<br>  var totalPayment = principalLoanAmount + interest;</pre><pre>  return round(totalPayment / loanPeriodMonth, 2);<br>}</pre><p><strong># Now, The UDF (Scalar KsqlDB Function) Implementation</strong></p><p>A UDF is just regular java class, with certain annotation. At class level, we need to annotate with <em>UdfDescription</em> , with the most important attribute is the udf name, the function name.</p><p>Each ksqldb function can has different input parameter. One ksqldb function with specific parameter is called as function variant. At the class,we can create methods and annotate those methods with <em>Udf. </em>This way, the method will be used as variant to function call.</p><p>Each ksqldb function can has different input parameter. We need to annotate the input parameter, which represented as method parameter, as <em>UdfParameter</em>.</p><p>Create file for the user defined function. Call it LoanUdf.java. Annotate the class as <em>UdfDescription</em>. The important parameter at <em>UdfDesctription</em> is <em>name</em>, this is the function name that we will call later. This has to be valid java variable identifier, means there must be no space. So in below sample, the name is <em>loan_installment</em>. The other attributes are optional, I will put it just for sample.</p><pre>@UdfDescription(name = &quot;loan_installment&quot;, category = &quot;LOAN&quot;, author = &quot;Timotius Pamungkas&quot;, version = &quot;1.0.0&quot;, description = &quot;User defined function for sample scalar loan business logic.&quot;)</pre><p>Create method to be called as function variant. You can have one or more variant, so this is just like overloading the function.</p><p>First sample will takes principal loan amount, annual interest rate, and loan period in months. Annotate this method as <em>Udf</em>, give the description. Annotate each parameter using <em>UdfParameter</em>. Iniside the method, we can do the logic for function. In this sample, I will use loan calculator to get the monthly installment.</p><pre>@Udf(description = &quot;Estimate monthly loan installment for loan principal amount X, with loan interest rate per year is Y %, over loan period Z month(s), roundest to 2 digit decimal. All parameters are mandatory and can only accept value greater than 1&quot;)</pre><pre>public double estimateMonthlyLoanInstallment(<br>  @UdfParameter(description = &quot;Loan principal amount&quot;) double principalLoanAmount,<br>  @UdfParameter(description = &quot;Annual interest rate (in percentage)&quot;) double annualInterestRate,<br>  @UdfParameter(description = &quot;Loan period (month), must be more than 0&quot;) int loanPeriodMonth) {<br>  return LoanCalculator.calculateMonthlyInstallment(principalLoanAmount, annualInterestRate, loanPeriodMonth);<br>}</pre><p>Sometimes, you might need an overloaded function : same function name, different parameters. For example, I will create second function, but this time I will not use loan period month. Instead, I will calculate loan, with loan period month is 12 month. So this is like having default value for the function parameter.</p><pre>@Udf(description = &quot;Estimate monthly loan installment for loan principal amount X, with loan interest rate per year is Y %, over loan period of 1 year, roundest to 2 digit decimal. All parameters are mandatory and can only accept value greater than 1&quot;)<br>public double estimateMonthlyLoanInstallment(<br>  @UdfParameter(description = “Loan principal amount”) double principalLoanAmount,<br>  @UdfParameter(description = “Annual interest rate (in percentage)”) double annualInterestRate) {<br>  return estimateMonthlyLoanInstallment(principalLoanAmount, annualInterestRate, 12);<br>}</pre><p>The complete LoanUdf.java can be seen <a href="https://gist.github.com/timpamungkas/4fccd99bd3a9e6119a95d72469c25cba">here</a></p><p><strong># Build &amp; deploy the UDF</strong></p><p>To deploy this udf, we need to create jar file. On the gradle task, we should have shadowJar task. Run it. You can use gradle command or gradle wrapper like this.</p><pre>#&gt; ./gradlew shadowJar</pre><p>For kafka &amp; KsqlDB, we will use docker. <a href="https://docs.docker.com/engine/install/">Install docker and docker-compose</a>. Then use this <a href="https://gist.github.com/timpamungkas/910cf6633d5cc5c3164579d9df671f56">docker-compose file</a>.</p><p>Run the docker compose script.</p><pre>#&gt; docker-compose up -d</pre><p>On the docker compose yml file, see the section on kafka ksqldb.</p><p>Settings for udf is on KSQL_EXTENSION_DIR, which tells ksqldb which folder to used as extension, or in other word: udf. Since we use docker, so we need to mount external folder into ksqldb extension dir, as defined on volume section. So what we need to do is paste the udf jar to mounted folder.</p><p>Restart the docker compose.</p><pre>#&gt; docker-compose restart</pre><p>The ksqldb should start and you can access the ksqldb console.</p><pre>#&gt; docker exec -ti kafka-ksqldb ksql</pre><p>If it is not started, check out the docker logs.</p><pre>#&gt; docker logs --tail 300 -f kafka-ksqldb</pre><p><strong># Use UDF</strong></p><p>From ksql console, check list of the function by using this command.</p><pre>ksql&gt; SHOW FUNCTIONS;</pre><p>We can see there is a loan_installment function, with category loan (ignore the other two, we will create them later).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*X_OEqqS4XjFAr9h-5EC48A.png" /><figcaption>UDF on ksqldb</figcaption></figure><p>To describe the function, we can use this statement.</p><pre>ksql&gt; DESCRIBE FUNCTION LOAN_INSTALLMENT;</pre><p>And we will see that the documentation is the same with the one we wrote on java source code. The function has two variants, as we also write on java code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MHy6HgYv8zJRcMkjFsx_gQ.png" /></figure><p>Let’s try the UDF. Create a dummy stream. This will also create new topic with 2 partitions.</p><pre>ksql&gt; CREATE STREAM `s-commodity-loan-request` (<br>  `username` VARCHAR,<br>  `principalLoanAmount` DOUBLE,<br>  `annualInterestRate` DOUBLE,<br>  `loanPeriodMonth` INT<br>) WITH (<br>  KAFKA_TOPIC = &#39;t-commodity-loan-request&#39;,<br>  PARTITIONS = 2,<br>  VALUE_FORMAT = &#39;JSON&#39;<br>);</pre><p>Insert several dummy data to the stream.</p><pre>ksql&gt; INSERT INTO `s-commodity-loan-request` (<br>  `username`,<br>  `principalLoanAmount`,<br>  `annualInterestRate`,<br>  `loanPeriodMonth`<br>) VALUES (<br>  &#39;danny&#39;,<br>  1000,<br>  12,<br>  12<br>);</pre><pre>ksql&gt; INSERT INTO `s-commodity-loan-request` (<br>  `username`,<br>  `principalLoanAmount`,<br>  `annualInterestRate`,<br>  `loanPeriodMonth`<br>) VALUES (<br>  &#39;melvin&#39;,<br>  1500,<br>  10.5,<br>  24<br>);</pre><pre>ksql&gt; INSERT INTO `s-commodity-loan-request` (<br>  `username`,<br>  `principalLoanAmount`,<br>  `annualInterestRate`,<br>  `loanPeriodMonth`<br>) VALUES (<br>  &#39;thomas&#39;,<br>  3500,<br>  11.2,<br>  36<br>);</pre><p>Try the udf. Set the offset to earliest.</p><pre>ksql&gt; SET &#39;auto.offset.reset&#39;=&#39;earliest&#39;;</pre><p>Then run query. Calling UDF is just like calling built-in function, writing the name and parameters.</p><pre>ksql&gt; SELECT `username`, `principalLoanAmount`, `annualInterestRate`, `loanPeriodMonth`,<br>       LOAN_INSTALLMENT(`principalLoanAmount`, `annualInterestRate`, `loanPeriodMonth`) AS `monthlyLoanInstallment`<br>  FROM `s-commodity-loan-request`<br>EMIT CHANGES;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LnjQfX1ldfnB3Z3GES-5ow.png" /><figcaption>Use the UDF for loan</figcaption></figure><p><strong># Need more returned result? See UDTF (Tabular KsqlDB) implementation</strong></p><p>Other than UDF, we can also create UDTF, or user defined tabular function. On udtf, we receive one input, and produce one or more output. So this is like a flatmap on kafka stream. In this part, we will learn how to write UDTF to create loan installment schedule. The input will be struct containing loan submission detail, and the output will be list of monthly loan schedule.</p><p>The blue part below will be our input, and the output will be list of pink struct. When writing UDTF, we need to define kafka struct, so we will not create java class for these input and output. Instead,we will define kafka struct schema to be used. In annotation, we need to define struct schema as string, or usually I called them descriptor. On the other hand, if we need to use the struct as java class, like setting the value for fields within struct, we need to create instance of Schema class.</p><p>We will see how we use the schema instance when building list of output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HSINlHdSJzheSvQA7nof3w.png" /></figure><p>Create file LoanUdtf.java. Annotate the class as Udtf Description.<br>Name it “loan_installment_schedule”. The other parameters is up to you.</p><pre><a href="http://twitter.com/UdtfDescription">@UdtfDescription</a>(name = &quot;loan_installment_schedule&quot;, category = &quot;LOAN&quot;, author = &quot;Timotius Pamungkas&quot;, version = &quot;1.0.0&quot;, description = &quot;User defined function for sample tabular loan business logic.&quot;)</pre><p>Create schema descriptor for input.</p><pre>public static final String LOAN_SUBMISSION_SCHEMA_DESCRIPTOR = &quot;STRUCT&lt;&quot; + &quot;`principalLoanAmount` DOUBLE, &quot;<br> + &quot;`annualInterestRate` DOUBLE, &quot; + &quot;`loanPeriodMonth` INT, &quot; + &quot;`loanApprovedDate` VARCHAR&quot; + “&gt;”;</pre><p>And schema descriptor for output.</p><pre>public static final String LOAN_MONTHLY_INSTALLMENT_SCHEMA_DESCRIPTOR = &quot;STRUCT&lt;&quot; + &quot;`installmentAmount` DOUBLE, &quot;<br> + &quot;`installmentDueDate` VARCHAR&quot; + &quot;&gt;&quot;;</pre><p>We later will also need to create instance of monthly installment and set the value, so we need schema instance. For the input, we only need to get the input value, but no modification on the input, so we don’t need schema instance for input.</p><pre>private static final Schema LOAN_MONTHLY_INSTALLMENT_SCHEMA = SchemaBuilder.struct()<br> .field(&quot;installmentAmount&quot;, Schema.FLOAT64_SCHEMA).field(&quot;installmentDueDate&quot;, Schema.STRING_SCHEMA);</pre><p>Then the method for tabular function. This method must accept one input and return list.</p><pre>public List&lt;Struct&gt; calculateLoanSchedule(Struct loanSubmission) {<br>}</pre><p>For the annotation, annotate the method as <a href="http://twitter.com/Udtf">@Udtf</a>. We need to pass the schema descriptor for output as annotation parameter.</p><pre><a href="http://twitter.com/Udtf">@Udtf</a>(description = &quot;Calculate loan installment schedule, comprise of installment amount and due date&quot;, schema = LOAN_MONTHLY_INSTALLMENT_SCHEMA_DESCRIPTOR)</pre><p>At the method input, annotate with UdfParameter, also supplying struct schema descriptor for input.</p><pre><a href="http://twitter.com/UdfParameter">@UdfParameter</a>(schema = LOAN_SUBMISSION_SCHEMA_DESCRIPTOR) Struct loanSubmission</pre><p>In the body, we will need to get the input value from struct. Struct provides get methods, where we can retrieve data based on struct field name. So I will retrieve the four inputs from struct. For the date, I will parse it to local date, because the original input is string.</p><pre>var principalLoanAmount = loanSubmission.getFloat64(“principalLoanAmount”);<br>var annualInterestRate = loanSubmission.getFloat64(“annualInterestRate”);<br>var loanPeriodMonth = loanSubmission.getInt32(“loanPeriodMonth”);<br>var loanApprovedDate = LocalDate.parse(loanSubmission.getString(“loanApprovedDate”));</pre><p>Create empty list for method output.</p><pre>var result = new ArrayList&lt;Struct&gt;();</pre><p>Calculate monthly installment amount using loan calculator. The installment amount will be the same for all monthly installment.</p><pre>var monthlyInstallmentAmount = LoanCalculator.calculateMonthlyInstallment(principalLoanAmount,<br> annualInterestRate, loanPeriodMonth);</pre><p>The difference for each monthly installment is on the due date. Create a loop to calculate each installment due date,which is loan approve date plus months. For the list element, create a new struct using monthly installment schema instance. Then put the installment amount and due date to each struct. Add the struct to the list result.</p><pre>IntStream.rangeClosed(1, loanPeriodMonth).forEachOrdered(i -&gt; {<br>  var installmentDueDate = loanApprovedDate.plusMonths(i);<br>  var monthlyInstallment = new   Struct(LOAN_MONTHLY_INSTALLMENT_SCHEMA);<br>  monthlyInstallment.put(&quot;installmentAmount&quot;,   monthlyInstallmentAmount);<br>  monthlyInstallment.put(&quot;installmentDueDate&quot;,   installmentDueDate.toString());<br>  result.add(monthlyInstallment);<br>});</pre><pre>return result;</pre><p>Full code for UDTF available <a href="https://gist.github.com/timpamungkas/984d42787bb23bd6306d03a2135aaea1">here</a></p><p>Like on udf, generate the shadow jar for this udtf. Copy paste the jar to ksqldb udf folder. Then restart the ksqldb container.</p><p>Try it. Drop stream if exists, including delete the topic.</p><pre>DROP STREAM IF EXISTS `s-commodity-loan-submission` DELETE TOPIC;</pre><p>Create a loan submission stream. The data will be struct, using same struct schema as we describe on java code.</p><pre>CREATE STREAM `s-commodity-loan-submission` (<br> `loanSubmission` STRUCT&lt;<br> `principalLoanAmount` DOUBLE, <br> `annualInterestRate` DOUBLE, <br> `loanPeriodMonth` INT, <br> `loanApprovedDate` VARCHAR <br> &gt;<br>) WITH (<br> KAFKA_TOPIC = &#39;t-commodity-loan-submission&#39;,<br> PARTITIONS = 2,<br> VALUE_FORMAT = &#39;JSON&#39;<br>);</pre><p>Insert dummy data to the stream.</p><pre>INSERT INTO `s-commodity-loan-submission` (<br> `loanSubmission`<br>) VALUES (<br> STRUCT(<br> `principalLoanAmount` := 6000,<br> `annualInterestRate` := 11.5,<br> `loanPeriodMonth` := 24,<br> `loanApprovedDate` := &#39;2022–11–21&#39;<br> )<br>);</pre><p>Run query using udtf and see the generated installment schedule.</p><pre>SET &#39;auto.offset.reset&#39;=&#39;earliest&#39;;</pre><pre>SELECT LOAN_INSTALLMENT_SCHEDULE(`loanSubmission`)<br> FROM `s-commodity-loan-submission`;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*ItRvHUPVwo_uiw4uwdSQnA.png" /></figure><p><strong>## Your own custom Kafka (KsqlDB) Aggregation Function (UDAF)</strong></p><p>Of course we also has user defined aggregation function, or UDAF.<br>Unlike UDF or UDTF, defining UDAF requires UdafFactory annotation and class implementation.</p><p>The logic for loan rating is like this. For each payment, we calculate payment latency, which is date difference between actual payment date and due date. Positive value, means customer late pay the installment, and counted as bad payment. In the contrary, zero or negative value means good payment. We later calculate percentage of good payment, and based on certain threshold, we will give loan rating as string. For example, if we have this data, where 2 out of 5 payments is late, means we have 60% good payment, and the loan rating is moderate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJyInLmUPgOAxLsPnaZv-A.png" /><figcaption>Logic we will use for UDAF sample</figcaption></figure><p>Create file LoanUdaf.java. Annotate the class as Udaf Description. Give it name “loan_rating”. The other parameters is up to you.</p><pre><a href="http://twitter.com/UdafDescription">@UdafDescription</a>(name = &quot;loan_rating&quot;, category = &quot;LOAN&quot;, author = &quot;Timotius Pamungkas&quot;, version = &quot;4.0.0&quot;, description = &quot;User defined function for sample aggregation loan business logic.&quot;)</pre><p>Create schema descriptor for input.</p><pre>public static final String LOAN_SUBMISSION_SCHEMA_DESCRIPTOR = &quot;STRUCT&lt;&quot; + &quot;`principalLoanAmount` DOUBLE, &quot;<br> + &quot;`annualInterestRate` DOUBLE, &quot; + &quot;`loanPeriodMonth` INT, &quot; + &quot;`loanApprovedDate` VARCHAR&quot; + &quot;&gt;&quot;;</pre><p>Udaf requires three things : input, output, and aggregate. In this case, the input is integer, the latency days. The output is string, loan rating. The aggregate is count of good payment and count of bad payment.</p><p>Input and output is just primitive data type. But for the aggregate, we will need struct that contains good payment and bad payment. We need the descriptor, and the schema instance to be used later.</p><p>On UDAF, we need to define the schema instance using optional for schema itself, and all fields within.</p><pre>public static final String AGGREGATE_SCHEMA_DESCRIPTOR = &quot;STRUCT&lt;`goodPayment` INT, `badPayment` INT&gt;&quot;;</pre><pre>public static final Schema AGGREGATE_SCHEMA = SchemaBuilder.struct().optional()<br> .field(&quot;goodPayment&quot;, Schema.OPTIONAL_INT32_SCHEMA).field(&quot;badPayment&quot;, Schema.OPTIONAL_INT32_SCHEMA)<br> .build();</pre><p>Creating udaf requires special class, and we need to return the udaf as static method. Like this. The generic has three parameters : input, aggregate, and string. So the input is integer, aggregate is struct, and output is string, as I explained just now. Ignore the compile error. <br>We will create LoanUdafImpl class soon.</p><pre>public static Udaf&lt;Integer, Struct, String&gt; createUdaf() {<br> return new LoanUdafImpl();<br> }</pre><p>For now, annotate the method as UdafFactory.</p><p>For non primitive data type, we need to define the schema string.<br>So in this case, we use aggregate schema descriptor, since the input and output is just primitive type.</p><pre><a href="http://twitter.com/UdafFactory">@UdafFactory</a>(description = &quot;Compute loan rating based on payment latency. The smaller the latency, the better.&quot;, aggregateSchema = AGGREGATE_SCHEMA_DESCRIPTOR)</pre><p>Now create a class as udaf implementation.<br>This must implements Udaf interface, with three generics : input, aggregate, and output.</p><pre>private static class LoanUdafImpl implements Udaf&lt;Integer, Struct, String&gt; {<br>}</pre><p>Create skeleton for unimplemented methods.</p><p>The initialize method is for creating,or initializing aggregator.<br>So we create struct with aggregation schema, and give goodPayment and badPayment initial value, which is zero.</p><pre>var initializer = new Struct(AGGREGATE_SCHEMA);<br>initializer.put(&quot;goodPayment&quot;, 0);<br>initializer.put(&quot;badPayment&quot;, 0);<br>return initializer;</pre><p>Aggregate method is where aggregation happened, when a new data arrived. In this case, we see the input, the latency days. If input is 0 or less, it means a good payment, so we update the aggregate good payment, increment it by one. Otherwise, it means bad payment, so we increment aggregate bad payment by one.</p><pre>if (current &lt;= 0) {<br>  var currentGoodPayment = aggregate.getInt32(&quot;goodPayment&quot;);<br> aggregate.put(&quot;goodPayment&quot;, currentGoodPayment + 1);<br> } else {<br>  var currentBadPayment = aggregate.getInt32(&quot;badPayment&quot;);<br> aggregate.put(&quot;badPayment&quot;, currentBadPayment + 1);<br> }</pre><pre>return aggregate;</pre><p>The merge method is not used, so we just return first input.</p><pre>return aggOne;</pre><p>The map method is where we map aggregate into output. We take the good payment and bad payment count from aggregate. Then we calculate the good payment percentage. Based on good payment percentage and threshold on previous diagram, we then generate string as the UDAF output.</p><pre>  var goodPayment = (double) agg.getInt32(&quot;goodPayment&quot;);<br>  var badPayment = (double) agg.getInt32(&quot;badPayment&quot;);<br>  var totalPayment = goodPayment + badPayment;</pre><pre>  var goodPaymentPercentage = (goodPayment / totalPayment) * 100d;</pre><pre>  if (goodPaymentPercentage &lt;= 25) {<br>     return &quot;VERY BAD : &quot;+ LoanCalculator.round(goodPaymentPercentage, 2) + &quot;%&quot;;<br>  } else if (goodPaymentPercentage &lt;= 50) {<br>     return &quot;BAD : &quot;+ LoanCalculator.round(goodPaymentPercentage, 2) + &quot;%&quot;;<br>  } else if (goodPaymentPercentage &lt;= 75) {<br>     return &quot;MODERATE : &quot;+ LoanCalculator.round(goodPaymentPercentage, 2) + &quot;%&quot;;<br> } else {<br>     return &quot;GOOD : &quot;+ LoanCalculator.round(goodPaymentPercentage, 2) + &quot;%&quot;;<br> }</pre><p>Like on udf, generate the shadow jar for this udaf. Copy paste the jar to ksqldb udf folder. Then restart the ksqldb container. Try it.</p><p>Drop stream if exists, including delete the topic.</p><pre>TERMINATE ALL;<br>DROP STREAM IF EXISTS `s-commodity-loan-payment-latency` DELETE TOPIC;<br>DROP STREAM IF EXISTS `s-commodity-loan-payment` DELETE TOPIC;</pre><p>Create loan payment stream.<br>Make it simple, just add loan number, installment due date, and payment due date.</p><pre>CREATE STREAM `s-commodity-loan-payment` (<br> `loanNumber` VARCHAR,<br> `installmentDueDate` VARCHAR,<br> `installmentPaidDate` VARCHAR<br>) WITH (<br> KAFKA_TOPIC = ‘t-commodity-loan-payment’,<br> PARTITIONS = 2,<br> VALUE_FORMAT = ‘JSON’<br>);</pre><p>We need to create stream with payment latency. Positive latency means late payment (bad). Payment latency is payment paid date minus payment due date.</p><pre>CREATE STREAM `s-commodity-loan-payment-latency`<br>AS<br>SELECT `loanNumber`, <br> `installmentDueDate`,<br> `installmentPaidDate`,<br> UNIX_DATE(PARSE_DATE(`installmentPaidDate`, ‘yyyy-MM-dd’)) -<br> UNIX_DATE(PARSE_DATE(`installmentDueDate`, ‘yyyy-MM-dd’)) AS `paymentLatency`<br> FROM `s-commodity-loan-payment`;</pre><p>Insert several dummy data.</p><pre>INSERT INTO `s-commodity-loan-payment` (<br> `loanNumber`,<br> `installmentDueDate`,<br> `installmentPaidDate`<br>) VALUES (<br> ‘LOAN-111’,<br> ‘2023–04–17’,<br> ‘2023–04–15’<br>);</pre><pre>INSERT INTO `s-commodity-loan-payment` (<br> `loanNumber`,<br> `installmentDueDate`,<br> `installmentPaidDate`<br>) VALUES (<br> ‘LOAN-111’,<br> ‘2023–05–17’,<br> ‘2023–05–05’<br>);</pre><pre>INSERT INTO `s-commodity-loan-payment` (<br> `loanNumber`,<br> `installmentDueDate`,<br> `installmentPaidDate`<br>) VALUES (<br> ‘LOAN-111’,<br> ‘2023–06–17’,<br> ‘2023–06–09’<br>);</pre><pre>INSERT INTO `s-commodity-loan-payment` (<br> `loanNumber`,<br> `installmentDueDate`,<br> `installmentPaidDate`<br>) VALUES (<br> &#39;LOAN-111&#39;,<br> &#39;2023–07–17&#39;,<br> &#39;2023–07–17&#39;<br>);</pre><pre>INSERT INTO `s-commodity-loan-payment` (<br> `loanNumber`,<br> `installmentDueDate`,<br> `installmentPaidDate`<br>) VALUES (<br> &#39;LOAN-111&#39;,<br> &#39;2023–08–17&#39;,<br> &#39;2023–08–15&#39;<br>);</pre><pre>INSERT INTO `s-commodity-loan-payment` (<br> `loanNumber`,<br> `installmentDueDate`,<br> `installmentPaidDate`<br>) VALUES (<br> &#39;LOAN-222&#39;,<br> &#39;2023–04–14&#39;,<br> &#39;2023–04–15&#39;<br>);</pre><pre>INSERT INTO `s-commodity-loan-payment` (<br> `loanNumber`,<br> `installmentDueDate`,<br> `installmentPaidDate`<br>) VALUES (<br> &#39;LOAN-222&#39;,<br> &#39;2023–05–14&#39;,<br> &#39;2023–05–05&#39;<br>);</pre><pre>INSERT INTO `s-commodity-loan-payment` (<br> `loanNumber`,<br> `installmentDueDate`,<br> `installmentPaidDate`<br>) VALUES (<br> &#39;LOAN-222&#39;,<br> &#39;2023–06–14&#39;,<br> &#39;2023–06–19&#39;<br>);</pre><pre>INSERT INTO `s-commodity-loan-payment` (<br> `loanNumber`,<br> `installmentDueDate`,<br> `installmentPaidDate`<br>) VALUES (<br> &#39;LOAN-222&#39;,<br> &#39;2023–07–14&#39;,<br> &#39;2023–07–22&#39;<br>);</pre><pre>INSERT INTO `s-commodity-loan-payment` (<br> `loanNumber`,<br> `installmentDueDate`,<br> `installmentPaidDate`<br>) VALUES (<br> &#39;LOAN-222&#39;,<br> &#39;2023–08–14&#39;,<br> &#39;2023–08–15&#39;<br>);</pre><p>Then run query.<br>In the data sample, we will get something like this.</p><pre>SET &#39;auto.offset.reset&#39;=&#39;earliest&#39;;</pre><pre>SELECT `loanNumber`, LOAN_RATING(`paymentLatency`) AS `loanRating`<br> FROM `s-commodity-loan-payment-latency`<br>GROUP BY `loanNumber`<br>EMIT CHANGES;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bvxW1Huok2ajJcGmO5fSGA.png" /><figcaption>UDAF on action</figcaption></figure><p>Feel free to learn more… Full study of Apache Kafka ecosystem + Java Spring, <a href="https://www.udemy.com/course/apache-kafka-with-java-spring-boot-theory-hands-on-coding/?referralCode=5C42CAF98051BB9CBA0A">see this post</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc0d4ea9bd23" width="1" height="1" alt=""><hr><p><a href="https://medium.com/batc/ksqldb-user-defined-function-scalar-tabular-aggregational-udf-udtf-udaf-dc0d4ea9bd23">KsqlDB User Defined Function (Scalar, Tabular, Aggregational) — UDF, UDTF, UDAF</a> was originally published in <a href="https://medium.com/batc">BATC — BFI Agile Thought Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Single Source of Truth : Business Process Automation With Camunda]]></title>
            <link>https://medium.com/batc/single-source-of-truth-business-process-automation-with-camunda-77c9aafb4797?source=rss----90163a577ddd---4</link>
            <guid isPermaLink="false">https://medium.com/p/77c9aafb4797</guid>
            <category><![CDATA[camunda]]></category>
            <category><![CDATA[bpmn]]></category>
            <dc:creator><![CDATA[Timotius Pamungkas]]></dc:creator>
            <pubDate>Thu, 17 Mar 2022 02:55:16 GMT</pubDate>
            <atom:updated>2022-03-16T07:17:25.455Z</atom:updated>
            <content:encoded><![CDATA[<h3>Single Source of Truth : Business Process Automation With Camunda</h3><p>Business user requirement usually involves complex workflow. For example:</p><ul><li>request user input to do process A</li><li>If user input is I1, go to process B. If input is I2, go to process B. Otherwise, request another input on process C</li><li>On process B, do sub-process B1, B2, and approval using B3</li><li>On process C, check certain condition and do branching to C1 and C2</li><li>etc</li></ul><p>Having text requirement is confusing, hence business user requirement is usually written in form of flow diagram / flow chart by business team, or someone in engineering team which closely related to funtional (e.g. Product Owner).</p><p>Wouldn’t it be nice when the technical team and business team can agree on the same workflow? There will be one source of truth, where the business can visually write their business process, and engineering team implement the technical team, based on that diagram.</p><p>Having written flowchart (e.g. using <a href="https://app.diagrams.net/">online diagram software</a>) is easy to understand by business user, but the technical implementation might missed. To avoid that problem, we use BPM (Business Process Modelling) tool : <a href="https://camunda.com/">Camunda</a>. The goal is single diagram for both business requirement and technical implementation, and Camunda can helps with this part. It is quite helpful, although we are still early adopting <a href="https://camunda.com/">Camunda</a>.</p><p>In this post, we will show simple diagram on Camunda,which is understandable visually (hence business user can understand it), along with Java (Spring boot) code to implement the diagram (the technical side refers to same diagram).</p><p>There are several components on <a href="https://camunda.com/">Camunda</a>, as shown below.</p><p>It has modeler, in which we can create the diagram. At the end user, we can assign task to be done by human using built-in tasklist. Or we can use custom application, leveraging built-in Camunda REST API to trigger the diagram (aka workflow engine). On the operation side, Camunda provides cockpit, a GUI to monitor each workflow individually (E.g. workflow number 888 is now on process A, while workflow number 555 on process B). Of course, there is an admin console to manage Camunda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UfUr2-IkPiHuBv2E-O9CVQ.png" /></figure><p>Some useful links for Camunda:</p><ul><li><a href="https://camunda.com/download/modeler/">Modeler</a></li><li><a href="https://start.camunda.com/">Camunda Spring Boot Starter</a></li></ul><p>During our last meetup (March 2022), one of our tech lead (Yosef Samuel) share how we can communicate a simple diagram within camunda. He demonstrated the use of workflow, and decision table through Camunda + Spring Boot.</p><p>It is a simple workflow, but in less 30 minutes we can get forms, user entry, and branching workflow. See the code for his demonstration at <a href="https://github.com/bfi-finance/batc/tree/master/2022/03/single-source-of-truth-business-process-automation-with-camunda">batc github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77c9aafb4797" width="1" height="1" alt=""><hr><p><a href="https://medium.com/batc/single-source-of-truth-business-process-automation-with-camunda-77c9aafb4797">Single Source of Truth : Business Process Automation With Camunda</a> was originally published in <a href="https://medium.com/batc">BATC — BFI Agile Thought Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automated API Testing and Test Case Management using Postman, Jira, & Zephyr Schale]]></title>
            <link>https://medium.com/batc/automated-api-testing-and-test-case-management-using-postman-jira-zephyr-schale-1935d8f61533?source=rss----90163a577ddd---4</link>
            <guid isPermaLink="false">https://medium.com/p/1935d8f61533</guid>
            <category><![CDATA[jira]]></category>
            <category><![CDATA[postman]]></category>
            <category><![CDATA[zephyr]]></category>
            <dc:creator><![CDATA[Timotius Pamungkas]]></dc:creator>
            <pubDate>Thu, 10 Mar 2022 11:01:03 GMT</pubDate>
            <atom:updated>2022-03-16T07:12:56.256Z</atom:updated>
            <content:encoded><![CDATA[<p>When we have APIs deployed, we should test it against multiple test cases (positive &amp; negative). For each test, we should also know the result, whether test case failed or passed.</p><p>If you are using agile &amp; <a href="https://www.atlassian.com/software/jira">Jira</a>, likely you familiar with creating <a href="https://www.atlassian.com/agile/project-management/user-stories">user stories</a> at <a href="https://www.atlassian.com/software/jira">Jira</a>. But Jira is not API tool. A popular tool to working with API is <a href="http://postman.com/">postman</a>, in which we can write <a href="https://learning.postman.com/docs/writing-scripts/test-scripts/">postman test cases</a> for the API.</p><p>In this post, we will learn how to use test cases written in postman, to be executed automatically, and the result (pass / fail) can be uploaded to Jira. Also, how to link the jira user story with test result. For this, we will use <a href="https://smartbear.com/test-management/zephyr-scale/">Zephyr Scale</a>, a test case management plugin for Jira.</p><p><em>Note : </em><a href="https://www.atlassian.com/software/jira/pricing"><em>Jira</em></a><em> and </em><a href="https://smartbear.com/test-management/zephyr-scale/pricing/"><em>Zephyr Scale</em></a><em> needs paid license, although the trial version might provides limited number of free usage.</em></p><p>Here are the tools we are going to use, and each functionalities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_REd98JxFn-kh-Cjhv1Taw.png" /></figure><p>And here is the working process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6cwzrIad3eK3dE3H1oM6Cw.png" /></figure><p>We will use Jira issue key as common key. Zephyr does not has direct integration with Jira, but both products provides API. And Zephyr API includes functionality to link Zephyr test case to Jira issue.</p><p>For that, we will need something in common, but unique. Fortunately, Jira already provides auto-generated issue key that we can use.</p><p>Postman is API development tools, and it has <a href="https://www.npmjs.com/package/newman">Newman</a> to run Postman collection via CLI, and generates report. The report can then uploaded to Zephyr as test result.</p><p>So here is the working process, in sequence:</p><ol><li>Create a user story in Jira. The important part here is just the issue key (e.g. JIRA-922)</li><li>Create request on postman. Since we later will connect Jira (Zephyr) with Postman request, use the issue key (JIRA-922) as postman request title</li><li>Save the request into postman collection</li><li>Install <a href="https://www.npmjs.com/package/newman">newman</a></li><li>Export postman collection (e.g to local file <em>postman-collection.json</em>)</li><li>If you use postman environment to save data like credential, url, etc (which you should), export your postman environment (e.g. to local file <em>postman-environment.json</em>)</li><li>Run newman from cli :</li></ol><pre>newman run postman-collection.json -e postman-environment.json -r cli,junit</pre><p>This will generates junit xml output, which later we will upload to jira. The cli output is optional, but it is nice since you can know the current execution progress on CLI. Optionally, if you need nice html report, you can use newman plugin : <a href="https://www.npmjs.com/package/newman-reporter-htmlextra">htmlextra</a>.</p><p>8. The output file from step 7 will be generated under subfolder <em>newman.</em> For example, let’s call it <em>newman-output.xml. </em>Zephyr provides API to upload this xml result. You need to get zephyr API token by following <a href="https://support.smartbear.com/zephyr-scale-cloud/docs/rest-api/generating-api-access-tokens.html">these steps</a>. Then, upload the xml, for example like this (assuming your project name is JIRA):</p><pre>curl -L -X POST &quot;https://api.zephyrscale.smartbear.com/v2/automations/executions/junit?projectKey=JIRA&amp;autoCreateTestCases=true&quot; -H &quot;Authorization: Bearer yourZephyrAccessToken&quot; -F &quot;file=@\&quot;/path/to/xml/file\&quot;&quot; -F &quot;type=\&quot;application/xml\&quot;&quot;</pre><p>This will upload the newman result, generating test cases, and a test cycle. You can check it through Jira, via menu Zephyr Scale. But the Jira issue, and the zephyr test cases that has just generated is not linked yet.</p><p>9. To link jira issue with zephyr test case, we can use Jira API. To access Jira API, you need to <a href="https://support.atlassian.com/atlassian-account/docs/manage-api-tokens-for-your-atlassian-account/">generate Jira API token</a> for API basic authentication. Later on you use your email as username and API token as basic auth password. There are several API to works with this. Assuming your project name is JIRA, then</p><pre># Get Jira issues</pre><pre>curl -L -X GET &quot;https://bfifinance.atlassian.net/rest/api/2/search?jql=project=JIRA&amp;maxResults=100&amp;startAt=200&amp;fields=id,key&quot; -H &quot;Authorization: Basic base64(yourJiraEmail:yourJiraApiToken)&quot;</pre><pre># Get Zephyr test cases<br>curl -L -X GET &quot;https://api.zephyrscale.smartbear.com/v2/testcases?projectKey=SMG&amp;maxResults=500&amp;startAt=5500&quot; -H &quot;Authorization: Bearer yourZephyrAccessToken&quot;</pre><pre># Link jira issue with zephyr<br>curl -L -X POST &quot;https://api.zephyrscale.smartbear.com/v2/testcases/{ZEPHYR-ISSUE-KEY}/links/issues&quot; -H &quot;Authorization: Bearer yourZephyrAccessToken&quot; -H &quot;Content-Type: application/json&quot; --data-raw &quot;{\&quot;issueId\&quot;: jiraIssueId}&quot;</pre><p>If you have thousands of test cases, it will not be practical to execute those APIs. For that, you can use <a href="https://github.com/bfi-finance/batc/tree/master/2022/03/automated-api-testing-test-case-management-postman-jira-zephyr-schale">this simple app</a> to link the Jira issue with Zephyr, as long as you follows step 1–8 above (especially the naming).</p><p>Here is the source code on <a href="https://github.com/bfi-finance/batc/tree/master/2022/03/automated-api-testing-test-case-management-postman-jira-zephyr-schale">github</a>. It is a Java spring boot app. Just note that the code is a quick work, no optimization at all. Feel free to fork and PR. The main application is at JiraZephyrApplication.java. In there, find all <strong>TODO</strong> comments, and change the item at each <strong>TODO </strong>(e.g. credentials).</p><p>If you want to see the demo video, checkout this youtube</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F0ZcFYFbci8U%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D0ZcFYFbci8U&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F0ZcFYFbci8U%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd9cd098d1c096a0bfed4d57dfe7fbb1/href">https://medium.com/media/bd9cd098d1c096a0bfed4d57dfe7fbb1/href</a></iframe><p>Just my 2 cents</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1935d8f61533" width="1" height="1" alt=""><hr><p><a href="https://medium.com/batc/automated-api-testing-and-test-case-management-using-postman-jira-zephyr-schale-1935d8f61533">Automated API Testing and Test Case Management using Postman, Jira, &amp; Zephyr Schale</a> was originally published in <a href="https://medium.com/batc">BATC — BFI Agile Thought Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Cache Strategy To Use?]]></title>
            <link>https://medium.com/batc/what-cache-strategy-to-use-d740199eb41?source=rss----90163a577ddd---4</link>
            <guid isPermaLink="false">https://medium.com/p/d740199eb41</guid>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Timotius Pamungkas]]></dc:creator>
            <pubDate>Wed, 02 Mar 2022 01:29:16 GMT</pubDate>
            <atom:updated>2022-03-02T05:34:31.437Z</atom:updated>
            <content:encoded><![CDATA[<h3>What Cache Strategy To Use</h3><p><strong>What is Cache?</strong></p><p>Cache is temporary storage to speed up performance. At times, we might have data that frequently used. For example, a function need interest rate based on loan period (tenure). In database, you might have table like this (simplified):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*671WKsyAh4laghw6s7qL4A.png" /><figcaption>table loan_interests</figcaption></figure><p>If your logic need to process total loan, with this formula :</p><pre>total_loan = principal_amount * (100 + interest_rate)</pre><p>where <em>principal_amount</em> is user input, then to get <em>interest_rate </em>you need to query database</p><pre>SELECT interest_rate FROM loan_interests WHERE tenure_month = x</pre><p>Database operation is expensive. You need to take connection from pool (assuming you use database connection pool!), or worst, creating new connection. Then there is network overhead. Those costs might be just several milliseconds (for example, 10ms). But if you need to process 200k data, the overhead for database query will be at least 2 million (10 * 200k) milliseconds, which is roughly 33 minutes! And that’s only for getting interest rate, not the application logic itself.</p><p>Here, the cache can help. Instead of querying database, put the data on the cache. Cache is usually a key-value pair, so in sample case above, the key is <em>tenure_month </em>and value is <em>interest_rate.</em></p><p>The common cache how-to are (in sequence):</p><ol><li>find <em>interest_rate </em>(value)<em> </em>at cache, based on <em>tenure_month</em> (key)</li><li>If the key does not exists on cache, query to database</li><li>Put the key &amp; value from step #2 into cache, so next logic which uses same <em>tenure_month</em> (key) will get data from cache (step #1)</li><li>Expire (remove) the key after certain time. This step is usually from cache config, or pre-defined during set the key (step #3)</li></ol><p><strong>Cache Sample?</strong></p><p>When the word ‘cache’ mentioned, some people might correlate it with <a href="https://redis.io/">redis</a>. Not wrong, but <a href="https://redis.io/">redis</a> is just one product for cache (distributed cache, to be exact). Redis can be used and helpful, but depends on the case, it might not be the most suitable.</p><p>There are application cache, and distributed cache (e.g. redis). As stated above, cache is basically key-value pair. You find a value based on key, and when the key not exists, you query the original data store and put the key-value pair to the cache.</p><p>Every modern programming language already has data structure for key-value pair. Java has Map. Python with dictionary. C# also called as dictionary. This should be the fastest performance cache, but it is very primitive. It will eat up memory. You need to remove key manually, while cache mostly will remove key automatically after certain configured period. But this is the fastest, since it live locally on the application memory itself.</p><p>Other than primitive map (dictionary), there are some in-memory cache, which the backing implementation might be primitive map (dictionary), but has cache capability (auto expire, etc). In java language, this is something like <a href="https://github.com/ben-manes/caffeine">caffeine</a>.</p><p>Then if your application is distributed microservice, but need to cache response (JSON) from multiple deployment nodes, use something like redis. Also, if your cache can be very large, that it will consume memory if put on local application node, use redis.</p><p><strong>Cache is key-value!</strong></p><p>Note one thing : cache is key-value pair, so <strong>don’t use </strong>array or list as cache. This is seemingly a cache, but not. From the sample above:</p><ol><li>load all the table rows to array / list</li><li>When application logic requires <em>interest_rate</em>, iterate through array / list to find the matching data, and return it.</li></ol><p>Regardless that the array / list is live locally in memory, the time complexity (<a href="https://en.wikipedia.org/wiki/Big_O_notation#:~:text=Big%20O%20notation%20is%20a,a%20particular%20value%20or%20infinity.">Big O</a>) will be different. Using Java Map, the complexity is O(1). Using list with n elements, finding a matching element will have complexity of O(n). That’s a lot!</p><p><strong>Performance Benchmark</strong></p><p>Theorically, the performance should be (fastest to slowest)</p><ol><li>in-memory primitive map / dictionary</li><li>in-memory cache with primitive map / dictionary as implementation</li><li>redis (due to network overhead)</li><li>list. OK, this is <strong>WRONG </strong>implementation. But just to give a view, I will include this on the benchmark.</li></ol><p>The benchmark will has following criterias:</p><p>a. using 500k cache data</p><p>b. using a list with 500k data, all data exists on cache. We will just count how many data on this list exists on cache (should be 100%, 500k)</p><p>c. runs on same machine : Java using Amazon Coretto 17, quad-core i7 Intel CPU each 1.8 GHz, and 16 GB RAM</p><p>d. For each benchmark iteration, data cleared out (e.g. removing data from docker redis)</p><p><strong>Benchmark Result</strong></p><p>If you just interested on the result, this is it. Using 5 runs for each cache scenario.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*hu1gYhz-NAtsnrf8gVhZ8g.png" /></figure><p>Summary:</p><ul><li>ConcurrentHashMap (primitive map) is the fastest, with only 0.17 second to lookup data. If you need fast operation with bulk data, with less feature (no key removal), for example where the cache is live as local variable (or something that can be garbage collected by JVM), ConcurrentHashMap is best.</li><li>Caffeine (backed by map) is the second fastest, around 0.35 second to lookup data. Use this if you need cache feature (e.g. auto key removal, limiting number of keys), and the cache lives on local application node, but need to be persisted for long time, not local method variable.</li><li>Redis tooks 362 seconds, that around 6 minutes. This seems the effect of json de/serialization. So redis is not always the best choice. For API response cache, connected with API gateway, or when the app deployment is distributed among machines (VMs / K8s worker nodes), redis is good though.</li><li>List? It tooks almost 2 hours just for one iteration. So I don’t want to continue this wrong case. And you shouldn’t use this kind of implementation too.</li></ul><p><strong>Codes</strong></p><p>The value class to be saved. Given example above, this should be JPA class.</p><pre>package com.course.kafka;</pre><pre>import java.time.LocalDate;<br>import java.util.Objects;</pre><pre>public class MySomething {</pre><pre>private String name;<br> private String address;<br> private LocalDate birthDate;</pre><pre>public MySomething(String name, String address, LocalDate birthDate) {<br>  super();<br>  this.name = name;<br>  this.address = address;<br>  this.birthDate = birthDate;<br> }</pre><pre><a href="http://twitter.com/Override">@Override</a><br> public int hashCode() {<br>  return Objects.hash(address, birthDate, name);<br> }</pre><pre><a href="http://twitter.com/Override">@Override</a><br> public boolean equals(Object obj) {<br>  if (this == obj)<br>   return true;<br>  if (obj == null)<br>   return false;<br>  if (getClass() != obj.getClass())<br>   return false;<br>  MySomething other = (MySomething) obj;<br>  return Objects.equals(address, other.address) &amp;&amp; Objects.equals(birthDate, other.birthDate)<br>    &amp;&amp; Objects.equals(name, other.name);<br> }</pre><pre><a href="http://twitter.com/Override">@Override</a><br> public String toString() {<br>  return &quot;MySomething [name=&quot; + name + &quot;, address=&quot; + address + &quot;, birthDate=&quot; + birthDate + &quot;]&quot;;<br> }</pre><pre>public String getName() {<br>  return name;<br> }</pre><pre>public void setName(String name) {<br>  this.name = name;<br> }</pre><pre>public String getAddress() {<br>  return address;<br> }</pre><pre>public void setAddress(String address) {<br>  this.address = address;<br> }</pre><pre>public LocalDate getBirthDate() {<br>  return birthDate;<br> }</pre><pre>public void setBirthDate(LocalDate birthDate) {<br>  this.birthDate = birthDate;<br> }</pre><pre>}</pre><p>This is the code for primitive cache using ConcurrentHashMap.</p><pre>package com.course.kafka;</pre><pre>import java.time.LocalDate;<br>import java.util.ArrayList;<br>import java.util.Collections;<br>import java.util.Optional;<br>import java.util.concurrent.ConcurrentHashMap;<br>import java.util.concurrent.atomic.AtomicInteger;<br>import java.util.stream.IntStream;</pre><pre>public class MapCache {</pre><pre>public static void main(String[] args) {<br>  var cacheNumbers = 500_000;<br>  var dataAgainstCache = new ArrayList&lt;MySomething&gt;();<br>  var cache = new ConcurrentHashMap&lt;String, MySomething&gt;();<br>  var start = 0l;<br>  var end = 0l;<br>  var counterExistsInCache = new AtomicInteger();<br>  var counterNotExistsInCache = new AtomicInteger();</pre><pre>IntStream.range(0, cacheNumbers).forEach(i -&gt; {<br>   var name = &quot;name-&quot; + i;<br>   dataAgainstCache.add(new MySomething(name, &quot;Some dummy address &quot; + i, LocalDate.now()));<br>  });</pre><pre>Collections.shuffle(dataAgainstCache);<br>  <br>  // populate cache<br>  start = System.currentTimeMillis();<br>  IntStream.range(0, cacheNumbers).forEach(i -&gt; {<br>   var name = &quot;name-&quot; + i;<br>   var mySomething = new MySomething(name, &quot;address-&quot; + i, LocalDate.now());<br>   cache.put(name, mySomething);<br>  });<br>  end = System.currentTimeMillis();</pre><pre>System.out.println(&quot;Populating cache took &quot; + (end - start) + &quot; ms&quot;);</pre><pre>// validating cache<br>  start = System.currentTimeMillis();<br>  dataAgainstCache.forEach(d -&gt; {<br>   var cacheResult = Optional.ofNullable(cache.get(d.getName()));</pre><pre>if (cacheResult.isEmpty()) {<br>    counterNotExistsInCache.incrementAndGet();<br>   } else {<br>    counterExistsInCache.incrementAndGet();<br>   }<br>  });<br>  end = System.currentTimeMillis();</pre><pre>System.out.println(&quot;Validating against cache took &quot; + (end - start) + &quot; ms&quot;);<br>  System.out.println(&quot;Exists : &quot; + counterExistsInCache.get() + &quot;, not exists : &quot; + counterNotExistsInCache.get()<br>    + &quot; total : &quot; + (counterExistsInCache.get() + counterNotExistsInCache.get()));<br> }</pre><pre>}</pre><p>This is the code for in-memory cache using <a href="https://github.com/ben-manes/caffeine">Caffeine</a>,where data expires after one hour. I use caffeine 3.0.5 on build.gradle</p><pre>implementation &#39;com.github.ben-manes.caffeine:caffeine:3.0.5&#39;</pre><p>This is the caffeine code.</p><pre>package com.course.kafka;</pre><pre>import java.time.Duration;<br>import java.time.LocalDate;<br>import java.util.ArrayList;<br>import java.util.Collections;<br>import java.util.Optional;<br>import java.util.concurrent.atomic.AtomicInteger;<br>import java.util.stream.IntStream;</pre><pre>import com.github.benmanes.caffeine.cache.Cache;<br>import com.github.benmanes.caffeine.cache.Caffeine;</pre><pre>public class CaffeineCache {</pre><pre>public static void main(String[] args) {<br>  var cacheNumbers = 500_000;<br>  var dataAgainstCache = new ArrayList&lt;MySomething&gt;();<br>  Cache&lt;String, MySomething&gt; cache = Caffeine.newBuilder().expireAfterAccess(Duration.ofHours(1)).build();<br>  var start = 0l;<br>  var end = 0l;<br>  var counterExistsInCache = new AtomicInteger();<br>  var counterNotExistsInCache = new AtomicInteger();</pre><pre>IntStream.range(0, cacheNumbers).forEach(i -&gt; {<br>   var name = &quot;name-&quot; + i;<br>   dataAgainstCache.add(new MySomething(name, &quot;Some dummy address &quot; + i, LocalDate.now()));<br>  });</pre><pre>Collections.shuffle(dataAgainstCache);</pre><pre>// populate cache<br>  start = System.currentTimeMillis();<br>  IntStream.range(0, cacheNumbers).forEach(i -&gt; {<br>   var name = &quot;name-&quot; + i;<br>   var mySomething = new MySomething(name, &quot;address-&quot; + i, LocalDate.now());<br>   cache.put(name, mySomething);<br>  });<br>  end = System.currentTimeMillis();</pre><pre>System.out.println(&quot;Populating cache took &quot; + (end - start) + &quot; ms&quot;);</pre><pre>// validating cache<br>  start = System.currentTimeMillis();<br>  dataAgainstCache.forEach(d -&gt; {<br>   var cacheResult = Optional.ofNullable(cache.getIfPresent(d.getName()));</pre><pre>if (cacheResult.isEmpty()) {<br>    counterNotExistsInCache.incrementAndGet();<br>   } else {<br>    counterExistsInCache.incrementAndGet();<br>   }<br>  });<br>  end = System.currentTimeMillis();</pre><pre>System.out.println(&quot;Validating against cache took &quot; + (end - start) + &quot; ms&quot;);<br>  System.out.println(&quot;Exists : &quot; + counterExistsInCache.get() + &quot;, not exists : &quot; + counterNotExistsInCache.get()<br>    + &quot; total : &quot; + (counterExistsInCache.get() + counterNotExistsInCache.get()));<br> }</pre><pre>}</pre><p>This is the code using Redis on localhost (docker based), and java jedis library. Note that redis cannot save java object, so we need to serialize / deserialize the java object. In this case, I serialize it into JSON using java jackson library.</p><p>On build.gradle.</p><pre>implementation &#39;redis.clients:jedis:4.1.1&#39;</pre><pre>implementation &#39;com.fasterxml.jackson.core:jackson-databind:2.13.1&#39;</pre><pre>implementation &#39;com.fasterxml.jackson.core:jackson-annotations:2.13.1&#39;</pre><p>This is the implementation for benchmark.</p><pre>package com.course.kafka;</pre><pre>import java.time.Duration;</pre><pre>import java.time.LocalDate;</pre><pre>import java.util.ArrayList;</pre><pre>import java.util.Optional;</pre><pre>import java.util.concurrent.atomic.AtomicInteger;</pre><pre>import java.util.stream.IntStream;</pre><pre>import com.fasterxml.jackson.core.JsonProcessingException;</pre><pre>import com.fasterxml.jackson.databind.ObjectMapper;</pre><pre>import redis.clients.jedis.Jedis;</pre><pre>public class RedisCache {</pre><pre>public static void main(String[] args) {</pre><pre>var cacheNumbers = 500_000;</pre><pre>var dataAgainstCache = new ArrayList&lt;MySomething&gt;();</pre><pre>var cache = new Jedis(&quot;localhost&quot;, 6379);</pre><pre>var start = 0l;</pre><pre>var end = 0l;</pre><pre>var counterExistsInCache = new AtomicInteger();</pre><pre>var counterNotExistsInCache = new AtomicInteger();</pre><pre>var expiryTime = Duration.ofHours(1).getSeconds();</pre><pre>var om = new ObjectMapper();</pre><pre>IntStream.range(0, cacheNumbers).forEach(i -&gt; {</pre><pre>var name = &quot;name-&quot; + i;</pre><pre>dataAgainstCache.add(new MySomething(name, &quot;Some dummy address &quot; + i, LocalDate.now()));</pre><pre>});</pre><pre>//  Collections.shuffle(dataAgainstCache);</pre><pre>// populate cache</pre><pre>start = System.currentTimeMillis();</pre><pre>IntStream.range(0, cacheNumbers).forEach(i -&gt; {</pre><pre>var name = &quot;name-&quot; + i;</pre><pre>var mySomething = new MySomething(name, &quot;address-&quot; + i, LocalDate.now());</pre><pre>try {</pre><pre>cache.setex(name, expiryTime, om.writeValueAsString(mySomething));</pre><pre>} catch (JsonProcessingException e) {</pre><pre>}</pre><pre>});</pre><pre>end = System.currentTimeMillis();</pre><pre>System.out.println(&quot;Populating cache took &quot; + (end - start) + &quot; ms&quot;);</pre><pre>// validating cache</pre><pre>start = System.currentTimeMillis();</pre><pre>dataAgainstCache.forEach(d -&gt; {</pre><pre>var cacheResult = Optional.ofNullable(cache.get(d.getName()));</pre><pre>if (cacheResult.isEmpty()) {</pre><pre>counterNotExistsInCache.incrementAndGet();</pre><pre>} else {</pre><pre>counterExistsInCache.incrementAndGet();</pre><pre>}</pre><pre>});</pre><pre>end = System.currentTimeMillis();</pre><pre>System.out.println(&quot;Validating against cache took &quot; + (end - start) + &quot; ms&quot;);</pre><pre>System.out.println(&quot;Exists : &quot; + counterExistsInCache.get() + &quot;, not exists : &quot; + counterNotExistsInCache.get()</pre><pre>+ &quot; total : &quot; + (counterExistsInCache.get() + counterNotExistsInCache.get()));</pre><pre>cache.close();</pre><pre>}</pre><pre>}</pre><p>And this is the WRONG implementation using ArrayList. Never do this.</p><pre>package com.course.kafka;</pre><pre>import java.time.LocalDate;<br>import java.util.ArrayList;<br>import java.util.concurrent.ThreadLocalRandom;<br>import java.util.concurrent.atomic.AtomicInteger;<br>import java.util.stream.Collectors;<br>import java.util.stream.IntStream;</pre><pre>public class ListCache {</pre><pre>public static void main(String[] args) {<br>  var cacheNumbers = 500_000;<br>  var dataAgainstCache = new ArrayList&lt;MySomething&gt;();<br>  var cache = new ArrayList&lt;MySomething&gt;();<br>  var start = 0l;<br>  var end = 0l;<br>  var counterExistsInCache = new AtomicInteger();<br>  var counterNotExistsInCache = new AtomicInteger();</pre><pre>IntStream.range(0, cacheNumbers * 2).forEach(i -&gt; {<br>   var name = &quot;name-&quot; + ThreadLocalRandom.current().nextInt(cacheNumbers);<br>   dataAgainstCache.add(new MySomething(name, &quot;Some dummy address &quot; + i, LocalDate.now()));<br>  });</pre><pre>// populate cache<br>  start = System.currentTimeMillis();<br>  IntStream.range(0, cacheNumbers).forEach(i -&gt; {<br>   var name = &quot;name-&quot; + i;<br>   var mySomething = new MySomething(name, &quot;address-&quot; + i, LocalDate.now());<br>   cache.add(mySomething);<br>  });<br>  end = System.currentTimeMillis();</pre><pre>System.out.println(&quot;Populating cache took &quot; + (end - start) + &quot; ms&quot;);</pre><pre>// validating cache<br>  start = System.currentTimeMillis();<br>  dataAgainstCache.forEach(d -&gt; {<br>   var cacheResult = cache.stream().filter(f -&gt; f.getName().equals(d.getName())).collect(Collectors.toList());</pre><pre>if (cacheResult.isEmpty()) {<br>    counterNotExistsInCache.incrementAndGet();<br>   } else {<br>    counterExistsInCache.incrementAndGet();<br>   }<br>  });<br>  end = System.currentTimeMillis();</pre><pre>System.out.println(&quot;Validating against cache took &quot; + (end - start) + &quot; ms&quot;);<br>  System.out.println(&quot;Exists : &quot; + counterExistsInCache.get() + &quot;, not exists : &quot; + counterNotExistsInCache.get()<br>    + &quot; total : &quot; + (counterExistsInCache.get() + counterNotExistsInCache.get()));<br> }</pre><pre>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d740199eb41" width="1" height="1" alt=""><hr><p><a href="https://medium.com/batc/what-cache-strategy-to-use-d740199eb41">What Cache Strategy To Use?</a> was originally published in <a href="https://medium.com/batc">BATC — BFI Agile Thought Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write (Spring Boot) GraphQL Backend As Easy as You Write Rest API]]></title>
            <link>https://medium.com/batc/write-spring-boot-graphql-backend-as-easy-as-you-write-rest-api-55d80917eb8?source=rss----90163a577ddd---4</link>
            <guid isPermaLink="false">https://medium.com/p/55d80917eb8</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Timotius Pamungkas]]></dc:creator>
            <pubDate>Mon, 07 Jun 2021 10:32:14 GMT</pubDate>
            <atom:updated>2022-03-02T05:35:58.554Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What Is Graph?</strong></p><p>I am graph, I go to work on graph. It’s everywhere, really.</p><p>I have a sister. Both of us has same parents. Our mom has parents, which is our grandparents from mom’s side. And so our dad, which means we have grandparents from dad’s side. And together, this is he “myself” graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFgpL239x1fPDqKQz6lxBQ.png" /><figcaption>“myself” graph</figcaption></figure><p>Tweet something on twitter, and it’s a graph. See: 8 people likes the tweet, and 3 people retweet my original tweet, so this is the graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BD5VEx5Xf2KaectZ6nzXyw.png" /><figcaption>tweet graph</figcaption></figure><p><strong>What Is QL?</strong></p><p>QL in GraphQL is shorthand for query language. If it seems familiar, you are right. SQL, or the structured query language, has the same shorthand.<br>SQL used to read and manipulate data in database. During SQL read, we can select multiple columns as we need, from one table, or several connected tables, usually through foreign key.<br>The same way with GraphQL. Like SQL, a single GraphQL query can return multiple columns from connected data. We can also use GraphQL to change or remove data.</p><p><strong>So What is GraphQL?</strong></p><p>GraphQL is a query language which uses graph concept. GraphQL is also a runtime that needs to be implemented on the backend, so the frontend application can use it as the query language.</p><p>To implement graphql, we need runtime frameworks, which each programming language has their own implementation. GraphQL itself is a specification, means whatever the framework, it must comply to the graphql specification, so the user can use GraphQL without even need to know what the GraphQL backend language is.<br>GraphQL is a service, where we need two items for creating Graphql backend. First, is the schema, which represents GraphQL structure. It is like database tables and relationships. Second is the resolver, which is logic for each field on schema to represents data. A resolver tells how and where to access certain field. For example, whether to get field’s data from database, or text file.</p><p><strong>More on GraphQL Theory</strong></p><p>GraphQL is (relatively) new, started by Facebook on 2015, and some large names currently use it (Github, Shopify, Twitter, etc). More of the GraphQL theory, including how it stands with REST API, the proc-cons of GraphQL, schema and operations, are available here.</p><p><strong>How to Write GraphQL code?</strong></p><p>What we will see, is the technical things, particularly, how to write GraphQL backend with Java (Spring Boot). To create graphql service we need graphql implementation library. If we see the <a href="https://graphql.org/code/">graphql website</a>, it will shows us library for many languages. To write graphql application, we can use <a href="https://github.com/graphql-java/graphql-java">graphql java</a>.</p><p>It is powerful, but we have another alternatives that built on top of graphql-java. Using that alternative, we can easily write GraphQL endpoint, using Java Spring Boot. If you are a Spring developer that familiars with Spring Web or Webflux, then learning how to write GraphQL Spring is easy.</p><p>The alternative I’m talking about is Netflix DGS (yes, that Netflix), which is released to public on early 2021. It has tutorial on the website, and if you need more than the provided (free) GraphQL Netflix DGS, you can see <a href="https://www.udemy.com/course/code-graphql-application-with-java-spring-boot-netflix-dgs/?referralCode=CF435DB5AF1257C6AFF2">my reference here</a>.</p><p>Le’t start by see, how easy to implements GraphQL. First, the dependency. If you use gradle, add this on the Gradle build file. Replace the XXX with <a href="https://mvnrepository.com/artifact/com.netflix.graphql.dgs/graphql-dgs">latest GraphQL Netflix version</a>:</p><pre>dependencies <strong>{</strong></pre><pre>    implementation(platform(‘com.netflix.graphql.dgs:graphql-dgs-platform-dependencies:XXX’))</pre><pre>    implementation ‘com.netflix.graphql.dgs:graphql-dgs-spring-boot-starter’</pre><pre><em>// other dependencies, omitted for readability</em></pre><pre><strong>}</strong></pre><p>GraphQL uses schema as it’s heart. But when we talks programming language (including Java), the GraphQL schema must be “translated” to respective source code. Luckily, great people at Netflix already provides <a href="https://plugins.gradle.org/plugin/com.netflix.dgs.codegen">Gradle code generator plugin</a>. So, in build.gradle file, add this plugin.</p><pre>plugins <strong>{</strong></pre><pre>    id &#39;com.netflix.dgs.codegen&#39; version &#39;XXX&#39;</pre><pre><em>    // other plugins, omitted for readability</em></pre><pre><strong>}</strong></pre><p>And add the task for java source code generation.</p><pre>generateJava{<br>  packageName = &#39;com.course.graphql.generated&#39;<br>}</pre><p>Now, anytime we run gradle build task, we will have Java classes from graphql schema, on package <em>com.course.graphql.generated</em>.</p><p>We are ready to code. For working with GraphQL, I reccomend IntelliJ (athough I’m a fan of Eclipse). This is because IntelliJ currently provides GraphQL schema editor plugin, while eclipse not (yet).</p><p>Since we will working with Spring boot, generate one project on <a href="http://start.spring.io/">spring initializr</a>. Create a gradle java project, nd the only dependency we needs is Spring Web (or Webflux). On this article, let’s use Spring Web.</p><p>Write some simple graphql schema on folder <em>src/main/resources/schema</em> (create the <em>schema</em> subfolder, netflix DGS will find the schema from there). Use this sample schema, name it <em>sample.graphql</em>.</p><pre>type Address {<br>    street: String!<br>    city: String!<br>    zipCode: String<br>    country: String!<br>}</pre><pre>type Author {<br>    name: String!<br>    originCountry: String<br>    addresses: [Address!]!<br>}</pre><pre>type ReleaseHistory {<br>    year: Int!<br>    printedEdition: Boolean<br>    releasedCountry: String<br>}</pre><pre>type Book {<br>    title: String!<br>    publisher: String!<br>    author: Author!<br>    released: ReleaseHistory<br>}</pre><pre>input ReleaseHistoryInput {<br>    year: Int<br>    printedEdition: Boolean<br>}</pre><pre>type Query {<br>    books(author: String): [Book]<br>    booksByReleased(releasedInput: ReleaseHistoryInput!): [Book]<br>}</pre><p>If you’re not familiar reading the GraphQL schema above, see <a href="https://www.udemy.com/course/code-graphql-application-with-java-spring-boot-netflix-dgs/?referralCode=CF435DB5AF1257C6AFF2">this complete reference</a> for detailed tutorial.</p><p>Run the gradle build task, and we will get several classes on build folder. Each <em>type</em> and <em>input</em> above will become one class. So we will have <em>Address, Author, ReleaseHistory, Book, and ReleaseHistoryInput</em>. The Query is special type, which is not generated as class.</p><p>In the query, we define two operations: find books by author, and find books by released history. Accessing graphql endpoint, the graphql query language syntax, and autocomplete is not detailed in this article, but you can see the <a href="https://www.udemy.com/course/code-graphql-application-with-java-spring-boot-netflix-dgs/?referralCode=CF435DB5AF1257C6AFF2">detail on this reference</a>. A popular GraphQL client we can use is <a href="https://altair.sirmuel.design/">altair</a>.</p><p>Let’s focus on what’s this article about: write GraphQL backend on Java Spring Boot. We will use dummy data source to create books. So, add this dependency on build.gradle.</p><pre>implementation &#39;com.github.javafaker:javafaker:1.0.2&#39;</pre><p>Then, on the java code, create package <em>datasource </em>(this is just example, you can use any name). Add this data source (<em>FakeBookDataSource.java</em>) for book. The classes we use, are classes generated from gradle plugin, which is located on package <em>com.course.graphql.generated.types.</em></p><p>Note that the generated classes already has fields, builder methods, and relationship among classes, as we define on GraphQL schema. And we got all of them on a single click, by running the gradle build task.</p><pre>@Configuration<br>public class FakeBookDataSource {<br><br>    private Faker faker = new Faker();<br><br>    public static final List&lt;Book&gt; <em>BOOK_LIST </em>= new ArrayList&lt;&gt;();<br><br>    @PostConstruct<br>    private void postConstruct() {<br>        for (int i = 0; i &lt; 20; i++) {<br>            var addresses = new ArrayList&lt;Address&gt;();<br>            var author = Author.<em>newBuilder</em>().addresses(addresses)<br>                    .name(faker.book().author())<br>                    .originCountry(faker.country().name())<br>                    .build();<br>            var released = ReleaseHistory.<em>newBuilder</em>()<br>                    .printedEdition(faker.bool().bool())<br>                    .releasedCountry(faker.country().name())<br>                    .year(faker.number().numberBetween(2019, 2021))<br>                    .build();<br>            var book = Book.<em>newBuilder</em>().author(author)<br>                    .publisher(faker.book().publisher())<br>                    .title(faker.book().title())<br>                    .released(released)<br>                    .build();<br><br>            for (int j = 0; j &lt; ThreadLocalRandom.<em>current</em>().nextInt(1, 3); j++) {<br>                var address = Address.<em>newBuilder</em>()<br>                        .country(faker.address().country())<br>                        .city(faker.address().cityName())<br>                        .country(faker.address().country())<br>                        .street(faker.address().streetAddress())<br>                        .zipCode(faker.address().zipCode())<br>                        .build();<br><br>                addresses.add(address);<br>            }<br><br>            <em>BOOK_LIST</em>.add(book);<br>        }<br>    }<br><br>}</pre><p>We have the data source, and now it’s time to write the GraphQL service. Something like <em>RestController</em> on the Spring REST world. This is where Netflix DGS takes place. Create package <em>component</em> (again, just example name). And write this class.</p><pre>@DgsComponent<br>public class FakeBookDataResolver {<br><br>    @DgsData(parentType = &quot;Query&quot;, field = &quot;books&quot;)<br>    public List&lt;Book&gt; booksWrittenBy(@InputArgument(name = &quot;author&quot;) Optional&lt;String&gt; authorName) {<br>        if (authorName.isEmpty() || StringUtils.<em>isBlank</em>(authorName.get())) {<br>            return FakeBookDataSource.<em>BOOK_LIST</em>;<br>        }<br><br>        return FakeBookDataSource.<em>BOOK_LIST</em>.stream()<br>                .filter(b -&gt; StringUtils.<em>containsIgnoreCase</em>(<br>                        b.getAuthor().getName(), authorName.get()<br>                )).collect(Collectors.<em>toList</em>());<br>    }<br><br>    @DgsData(<br>            parentType = DgsConstants.<em>QUERY_TYPE</em>,<br>            field = DgsConstants.QUERY.<em>BooksByReleased<br>    </em>)<br>    public List&lt;Book&gt; getBooksByReleased(DataFetchingEnvironment dataFetchingEnvironment) {<br>        var releasedMap = (Map&lt;String, Object&gt;) dataFetchingEnvironment.getArgument(&quot;releasedInput&quot;);<br>        var releasedInput = ReleaseHistoryInput.<em>newBuilder</em>()<br>                .printedEdition((boolean) releasedMap.get(DgsConstants.RELEASEHISTORYINPUT.<em>PrintedEdition</em>))<br>                .year((int) releasedMap.get(DgsConstants.RELEASEHISTORYINPUT.<em>Year</em>))<br>                .build();<br><br>        return FakeBookDataSource.<em>BOOK_LIST</em>.stream().filter(<br>                b -&gt; this.matchReleaseHistory(releasedInput, b.getReleased())<br>        ).collect(Collectors.<em>toList</em>());<br>    }<br><br>    private boolean matchReleaseHistory(ReleaseHistoryInput input, ReleaseHistory element) {<br>        return input.getPrintedEdition().equals(element.getPrintedEdition())<br>                &amp;&amp; input.getYear() == element.getYear();<br>    }<br><br>}</pre><p>The two main annotation provided by netflix are</p><p><em>@DgsComponent</em> (consider it something like Spring @RestController), to let Spring know that this class is Dgs GraphQL handler.</p><p><em>@DgsData</em> (consider it something like Spring <em>@RequestMapping</em> <em>@GetMapping</em> or other <em>@XxxMapping</em>)</p><p>In the code above, we will have two graphql operations, each annotated with @DgsData.</p><p>The first, booksWrittenBy, will returns List of Book, and it takes one input argument (As stated on @InputArgument annotation), which is author name. So in this case, <em>@InputArgument</em> is something like REST <em>@RequestParam</em> or <em>@PathVariable</em>. Although, it can receives not just simple tring, but also more complex object like class <em>ReleaseHistoryInput</em> (although not written on code above, but tutorial is available <a href="https://www.udemy.com/course/code-graphql-application-with-java-spring-boot-netflix-dgs/?referralCode=CF435DB5AF1257C6AFF2">on this reference</a>). So, the <em>@InputArgument</em> can also act like <em>@RequestBody</em> on Spring REST.</p><p>Well, the code inside itself is not special. It’s just regular java code to fetch data requested based on optional parameter (author’s name in this case), and return list of matching books. That’s all. Using Spring with Netflix DGS means the implementation detail is hidden from us, and we can write just like regular java code.</p><p>If we need more complex input, netflix DGS also provides <em>DataFetchingEnvironment</em> class, which is something like <em>ServletContext</em> on Spring REST. We can get the GraphQL request detail from it, something like the input class (Although there is simpler way to do this, also provided by Netflix).</p><p>The fundamental of using Netflix DGS as GraphQL backend, is way moreee than this article. Thus, I provide longer (5 hours+) <a href="https://www.udemy.com/course/code-graphql-application-with-java-spring-boot-netflix-dgs/?referralCode=CF435DB5AF1257C6AFF2">video reference</a>, dedicated for GraphQL netflix.</p><p>But I hope you get the idea, that using Netflix DGS is a simple and quick way to works, writing GraphQL backend with Spring boot.</p><p>See you on the next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55d80917eb8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/batc/write-spring-boot-graphql-backend-as-easy-as-you-write-rest-api-55d80917eb8">Write (Spring Boot) GraphQL Backend As Easy as You Write Rest API</a> was originally published in <a href="https://medium.com/batc">BATC — BFI Agile Thought Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Kafka Without “Writing” Code]]></title>
            <link>https://medium.com/batc/using-kafka-without-writing-code-b029f1d73fc4?source=rss----90163a577ddd---4</link>
            <guid isPermaLink="false">https://medium.com/p/b029f1d73fc4</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Timotius Pamungkas]]></dc:creator>
            <pubDate>Sun, 25 Apr 2021 04:59:30 GMT</pubDate>
            <atom:updated>2021-04-25T04:59:12.905Z</atom:updated>
            <content:encoded><![CDATA[<p>Kafka has good integration with Java spring, as you can see <a href="https://www.udemy.com/course/apache-kafka-with-java-spring-boot-theory-hands-on-coding/?referralCode=5C42CAF98051BB9CBA0A">here</a>. Spring provides KafkaTemplate and annotations to easily produce and consume kafka.</p><p>But not everybody uses Spring. Sometimes even team working on other programming language than java. This means, learning kafka needs another learning curve, especially when uses native library. If the kafka usage is only basic publish &amp; consume, we can shorten this learning curve, by using kafka without coding.</p><p>How we do that?</p><p>Basically, we still write codes to publish and consume from kafka. But instead using native library, we use REST API. Most developers are familiar with REST API, so learning curve generally shorter.</p><p>Sad news : Kafka does not comes with REST API as built-in feature. Fortunately, confluent provides Kafka Rest Proxy as open source project to access kafka using API. This means, we got Kafka REST API as ready-to-use-(and reliable) product, and no need to write our own Kafka REST API.</p><p>We can even use Confluent Kafka Rest proxy with binary, json, or avro message. When we use schema-based message like avro, Confluent Kafka REST Proxy also integrates well with Confluent Schema Registry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zn5Crj0JIxY1vd29uBck1Q.png" /><figcaption>Kafka REST Proxy with Schema Registry Architecture</figcaption></figure><p>Using Kafka REST Proxy, we can have non java producers and consumer, which talks to kafka REST proxy, via REST API for publish and consume. The one who talks with kafka broker, and schema registry, is the REST proxy</p><p>However, using REST API has drawbacks compared to native library, which is slower performance, and less error handler mechanism. Use either REST API or native library, depends on your need. In case you need basic produce-consume, and no time for your team to learn, Kafka REST proxy can be a solution. However, <a href="https://www.udemy.com/course/apache-kafka-with-java-spring-boot-theory-hands-on-coding/?referralCode=5C42CAF98051BB9CBA0A">learning Kafka native coding</a> might still the best option.</p><p>Let’s see a little sample to produce message using Kafka REST Proxy.</p><p>To produce data using API, we must set content type header on API request. For producing, we will use v2 endpoints, and the rule is this. There are 4 segments, and the difference is on segment 2. We need to set segment 2, depends on what kind of data we will publish. For example, see the following picture, where we will change the segment 2 depends on what data will publish (binary, json, or avro).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dylwmN8uFAWXx0mc_yMOIA.png" /><figcaption>request header</figcaption></figure><p>Assuming kafka REST Proxy runs on localhost:8082, here are sample curl to publish message to kafka. We define topic name on the URL. For example, to publish to topic my-kafka-topic-name we must use URL like this</p><p><a href="http://localhost:8082/topics/my-kafka-topic-name"><em>http://localhost:8082/topics/my-kafka-topic-name</em></a></p><p><strong>Sample CURL : Publish Binary Message</strong></p><pre>curl --location --request POST &#39;<a href="http://localhost:8082/topics/my-topic-from-api-binary&#39;">http://localhost:8082/topics/my-topic-from-api-binary&#39;</a> \<br>--header &#39;Content-Type: application/vnd.kafka.binary.v2+json&#39; \<br>--data-raw &#39;{<br>    &quot;records&quot;: [<br>        {<br>            &quot;key&quot;: &quot;kafka record key&quot;,<br>            &quot;value&quot;: &quot;SnVzdCBzb21lIHZhbHVlIGZvciBrYWZrYQ==&quot;<br>        }<br>    ]<br>}&#39;</pre><p>For example, to produce binary, we can use this endpoint. The request content type header already set. To publish binary, we must encode the binary data as base64 string. On example above, the value is base64 encoded for string <em>Just some value for kafka</em>.</p><p>We can publish several data at once, on the array “records”.</p><p><strong>Sample CURL : Publish JSON Message</strong></p><pre>curl --location --request POST &#39;<a href="http://localhost:8082/topics/my-topic-from-api-json&#39;">http://localhost:8082/topics/my-topic-from-api-json&#39;</a> \<br>--header &#39;Content-Type: application/vnd.kafka.json.v2+json&#39; \<br>--data-raw &#39;{<br>    &quot;records&quot;: [<br>        {<br>            &quot;key&quot;: &quot;this record has key&quot;,<br>            &quot;value&quot;: {<br>                &quot;name&quot;: &quot;Steve Rogers&quot;,<br>                &quot;gender&quot;: &quot;MALE&quot;<br>            }<br>        },<br>        {<br>            &quot;value&quot;: [<br>                {<br>                    &quot;name&quot;: &quot;Anna&quot;,<br>                    &quot;gender&quot;: &quot;FEMALE&quot;<br>                },<br>                {<br>                    &quot;name&quot;: &quot;Olaf&quot;,<br>                    &quot;gender&quot;: &quot;MALE&quot;<br>                }<br>            ]<br>        },<br>        {<br>            &quot;key&quot;:&quot;this is another record key&quot;, <br>            &quot;value&quot;: [<br>                109,<br>                289,<br>                442<br>            ]<br>        }<br>    ]<br>}&#39;</pre><p>Producing json is almost same with producing binary. Just keep in mind that the content-type request header must be changed. See the body, on records. On this sample, we will publish several json records at once. The value field is the json body, so we can give any valid json format as a value.</p><p><strong>Sample CURL : Publish Avro Message</strong></p><p><em>Sample 1</em></p><pre>curl --location --request POST &#39;<a href="http://localhost:8082/topics/my-topic-from-api-avro&#39;">http://localhost:8082/topics/my-topic-from-api-avro&#39;</a> \<br>--header &#39;Content-Type: application/vnd.kafka.avro.v2+json&#39; \<br>--data-raw &#39;{<br>    &quot;value_schema&quot;: &quot;{\&quot;type\&quot;:\&quot;record\&quot;, \&quot;name\&quot;:\&quot;MySchema\&quot;, \&quot;fields\&quot;:[{\&quot;name\&quot;:\&quot;field1\&quot;, \&quot;type\&quot;:\&quot;string\&quot;}]}&quot;,<br>    &quot;records&quot;: [<br>        {<br>            &quot;value&quot;: {<br>                &quot;field1&quot;: &quot;A sample&quot;<br>            }<br>        }<br>    ]<br>}&#39;</pre><p>To produce avro, we must adjust the content type request header to avor. In the first example, see the request body. In there, we define the schema and records. If we send it, we will get value_schema_id (for example : 402).</p><p>See that on 2nd sample below, the request body has field value_schema_id In case we already get the value schema id, we don’t need to embed avro schema into request body. Just inform value_schema_id the and execute.</p><p><em>Sample 2</em></p><pre>curl --location --request POST &#39;<a href="http://localhost:8082/topics/my-topic-from-api&#39;">http://localhost:8082/topics/my-topic-from-api&#39;</a> \<br>--header &#39;Content-Type: application/vnd.kafka.avro.v2+json&#39; \<br>--data-raw &#39;{<br>    &quot;value_schema_id&quot;: 402,<br>    &quot;records&quot;: [<br>        {<br>            &quot;value&quot;: {<br>                &quot;field1&quot;: &quot;this is another value for field1&quot;<br>            }<br>        }<br>    ]<br>}&#39;</pre><p>What about consuming using Kafka REST Proxy? Consuming from API needs several steps, all through REST API :</p><ol><li>Create consumer</li><li>Subscribe this consumer to certain topic</li><li>Start consuming</li></ol><p>All these steps can be done through different endpoints. On create and subscribe, we must set content type request header as explained before. On consume, we must set Accept request header. The rule is the same with content-type request header (change the segment 2).</p><p><strong>Sample CURL : Consume Binary Message</strong></p><p>The following are three sample endpoints, that must be runs in sequence, to consume binary message.</p><pre>1. Create Consumer<br>curl --location --request POST &#39;<a href="http://localhost:8082/consumers/myConsumerGroupFromApi&#39;">http://localhost:8082/consumers/myConsumerGroupFromApi&#39;</a> \<br>--header &#39;Content-Type: application/vnd.kafka.binary.v2+json&#39; \<br>--data-raw &#39;{<br>    &quot;name&quot;: &quot;avroConsumerFromApi-binary&quot;,<br>    &quot;format&quot;: &quot;binary&quot;,<br>    &quot;auto.offset.reset&quot;: &quot;earliest&quot;,<br>    &quot;auto.commit.enable&quot;: &quot;true&quot;<br>}&#39;</pre><pre>2. Subscribe to topic<br>curl --location --request POST &#39;<a href="http://localhost:8082/consumers/myConsumerGroupFromApi/instances/avroConsumerFromApi-binary/subscription&#39;">http://localhost:8082/consumers/myConsumerGroupFromApi/instances/avroConsumerFromApi-binary/subscription&#39;</a> \<br>--header &#39;Content-Type: application/vnd.kafka.binary.v2+json&#39; \<br>--data-raw &#39;{<br>    &quot;topics&quot;: [<br>        &quot;my-topic-from-api-binary&quot;<br>    ]<br>}&#39;</pre><pre>3. Consume from topic<br>curl --location --request GET &#39;<a href="http://localhost:8082/consumers/myConsumerGroupFromApi/instances/avroConsumerFromApi-binary/records&#39;">http://localhost:8082/consumers/myConsumerGroupFromApi/instances/avroConsumerFromApi-binary/records&#39;</a> \<br>--header &#39;Accept: application/vnd.kafka.binary.v2+json&#39;</pre><p><strong>Sample CURL : Consume JSON Message</strong></p><p>The following are three sample endpoints, that must be runs in sequence, to consume JSON message.</p><pre>1. Create Consumer<br>curl --location --request POST &#39;<a href="http://localhost:8082/consumers/myConsumerGroupFromApi&#39;">http://localhost:8082/consumers/myConsumerGroupFromApi&#39;</a> \<br>--header &#39;Content-Type: application/vnd.kafka.json.v2+json&#39; \<br>--data-raw &#39;{<br>    &quot;name&quot;: &quot;avroConsumerFromApi-json&quot;,<br>    &quot;format&quot;: &quot;json&quot;,<br>    &quot;auto.offset.reset&quot;: &quot;earliest&quot;,<br>    &quot;auto.commit.enable&quot;: &quot;true&quot;<br>}&#39;</pre><pre>2. Subscribe to topic<br>curl --location --request POST &#39;<a href="http://localhost:8082/consumers/myConsumerGroupFromApi/instances/avroConsumerFromApi-json/subscription&#39;">http://localhost:8082/consumers/myConsumerGroupFromApi/instances/avroConsumerFromApi-json/subscription&#39;</a> \<br>--header &#39;Content-Type: application/vnd.kafka.json.v2+json&#39; \<br>--data-raw &#39;{<br>    &quot;topics&quot;: [<br>        &quot;my-topic-from-api-json&quot;<br>    ]<br>}&#39;</pre><pre>3. Consume from topic<br>curl --location --request GET &#39;<a href="http://localhost:8082/consumers/myConsumerGroupFromApi/instances/avroConsumerFromApi-json/records&#39;">http://localhost:8082/consumers/myConsumerGroupFromApi/instances/avroConsumerFromApi-json/records&#39;</a> \<br>--header &#39;Accept: application/vnd.kafka.json.v2+json&#39;</pre><p><strong>Sample CURL : Consume Avro Message</strong></p><p>The following are three sample endpoints, that must be runs in sequence, to consume Avro message.</p><pre>1. Create Consumer<br>curl --location --request POST &#39;<a href="http://localhost:8082/consumers/myConsumerGroupFromApi&#39;">http://localhost:8082/consumers/myConsumerGroupFromApi&#39;</a> \<br>--header &#39;Content-Type: application/vnd.kafka.avro.v2+json&#39; \<br>--data-raw &#39;{<br>    &quot;name&quot;: &quot;avroConsumerFromApi-avro&quot;,<br>    &quot;format&quot;: &quot;avro&quot;,<br>    &quot;auto.offset.reset&quot;: &quot;earliest&quot;,<br>    &quot;auto.commit.enable&quot;: &quot;true&quot;<br>}&#39;</pre><pre>2. Subscribe to topic<br>curl --location --request POST &#39;<a href="http://localhost:8082/consumers/myConsumerGroupFromApi/instances/avroConsumerFromApi-avro/subscription&#39;">http://localhost:8082/consumers/myConsumerGroupFromApi/instances/avroConsumerFromApi-avro/subscription&#39;</a> \<br>--header &#39;Content-Type: application/vnd.kafka.avro.v2+json&#39; \<br>--data-raw &#39;{<br>    &quot;topics&quot;: [<br>        &quot;my-topic-from-api-avro&quot;<br>    ]<br>}&#39;</pre><pre>3. Consume from topic<br>curl --location --request GET &#39;<a href="http://localhost:8082/consumers/myConsumerGroupFromApi/instances/avroConsumerFromApi-avro/records&#39;">http://localhost:8082/consumers/myConsumerGroupFromApi/instances/avroConsumerFromApi-avro/records&#39;</a> \<br>--header &#39;Accept: application/vnd.kafka.avro.v2+json&#39;</pre><p>So, without <a href="https://www.udemy.com/course/apache-kafka-with-java-spring-boot-theory-hands-on-coding/?referralCode=5C42CAF98051BB9CBA0A">learning native code</a> (although it’s certainly worth a lot), you or your teammate can works with Kafka.</p><p>For more information on Kafka, including avro, &amp; Kafka REST Proxy, <a href="https://www.udemy.com/course/apache-kafka-with-java-spring-boot-theory-hands-on-coding/?referralCode=5C42CAF98051BB9CBA0A">see this video</a>.</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b029f1d73fc4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/batc/using-kafka-without-writing-code-b029f1d73fc4">Using Kafka Without “Writing” Code</a> was originally published in <a href="https://medium.com/batc">BATC — BFI Agile Thought Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWT for Dummies (OK, not 100% dummies)]]></title>
            <link>https://medium.com/batc/jwt-for-dummies-ok-not-100-dummies-1f08d3279a0b?source=rss----90163a577ddd---4</link>
            <guid isPermaLink="false">https://medium.com/p/1f08d3279a0b</guid>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[api-security]]></category>
            <dc:creator><![CDATA[Timotius Pamungkas]]></dc:creator>
            <pubDate>Tue, 16 Feb 2021 11:49:18 GMT</pubDate>
            <atom:updated>2021-03-16T10:58:44.742Z</atom:updated>
            <content:encoded><![CDATA[<p>We need to secure API.<br>One common way to secure this is using token, some long-character-sequence, attached on HTTP request (the good practice is in HTTP request header), where API server (or API gateway) validates the token against some database.</p><p>There are two types of tokens:</p><ul><li><strong>stateful </strong>: where server save the token data (e.g. on Redis), and validates each request against this token</li><li><strong>stateless </strong>: in the contrary, server save nothing. The token itself contains all information required for validation.</li></ul><p>There is a common way to create stateless tokens, using JSON web token, or JWT.<br>In simple words, it is a string consists of 3 parts. Each part separated by dot.<br>1st part is header.<br>2nd part is payload.<br>And 3rd part is signature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*opylT3le-JKZ-paWKYRcYQ.png" /><figcaption>JWT structure</figcaption></figure><p>The <strong>header </strong>is a JSON object containing information about how the JWT signature should be computed. This header sometimes called as JOSE (Javascript Object Signing &amp; Encryption)<br>In sample above, there are two fields for header JSON object.</p><ul><li>“typ” which value is “JWT”</li><li>“alg” which shows hash algorithm to create JWT signature component.<br>In this example, we use HMAC SHA 256 to calculate signature.<br>The 1st JWT token component, is base64 encode of this JSON object.</li></ul><p><strong>Payload </strong>is JWT component which is JSON that contains “claim” data. This data is used by consumer to claim that this information belongs to consumer.<br>There are several standard “claim” field as defined on RFC-7519 about JWT. We can also add as many custom claim as we want. <br>Note that this payload, is not the payload for transaction data, but payload used for JWT token. <br>These claims must be validated on the API side, or if using api management, on api management side<br>In example above, we have two claims : the issuer of the token, and the token expired date is epoch time in second.<br>Epoch time is a number of seconds since January 1, 1970.<br>To calculate epoch time, you can use online tools like epochconverter.com or time library on most programming language.<br>The 2nd JWT token component, is base64 encode of this claim object.</p><p>In <strong>signature</strong>, the 3rd component, we hash the first two parts of JWT which is base64(header) and base64(payload), with . (dot) to separate them. <br>This component is hashed using algorithm in header part, and encrypted using secret key for specific consumer. <br>Unless someone has the secret key, they can not decrypt this information, so this is where JWT goes secure.<br>In this example, we hash using HMAC SHA256 algorithm, as defined in header. <br>And the secret key is <em>mySecretKey123</em>.<br>The 3rd JWT token part, is hashed string, in base64 encode</p><p>Using previous example, we will get JWT token like picture below. This JWT token can be calculated by using libraries, or online JWT calculator. See website jwt.io for calculator or list of libraries for many programming language. We can then attach this token as authorization mechanism. In this case we can use HTTP “Authorization” header with value “Bearer token”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XbhmVsWnrxfD2OZoFEZ6hg.png" /><figcaption>Calculated JWT token</figcaption></figure><p>Being widely used, JWT also provides standard fields for first part, the header, and also second part, the payload. Being standard doesn’t mean we have to use all of them. Some fields are optional, and we can also add our own field, usually on the payload part.</p><p>These are standard fields for header. Notice the note on yellow rows, where using the field will make JWT vulnerable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pZAFtZbWT9IckR-1ynt2Jg.png" /><figcaption>JWT Header standard fields</figcaption></figure><p>Below is some sample for header. Note that fields order is not important. Notice the green sample, where we use kid or key id field. Also notice the red sample, where we put the HMAC key on the header, field “jwk”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P4DmKh_iKtbXO0DjmmlQDg.png" /></figure><p>It is a good practice to change keys regularly, or use multiple keys. When having multiple keys for HMAC, we can put the keys on server. This can be file, database, et cetera. For each key, we have key id. On the JWT header, we specify which secret key to use for HMAC on “kid” field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*90NCHUnintB-XLx_ajuIMw.png" /><figcaption>kid field in JWT header</figcaption></figure><p>JWT specification also provides two standard fields : jwk and jku, which basically to tell the server : use this secret key, or you can retrieve secret key in this location. Using this fields means we give secret key, something that supposedly secret, over the network. So an attacker that intercepts the communication will easily retrieve the valid HMAC key and reuse it to generate fake JWT tokens. Although HTTPS can secure some part of this, its useless if attacker herself is valid user and intercept traffic from her own computer. Since hmac key generally same for all other tokens, having one secret key for attacker can be enough. That’s why, using jwk or jku means making JWT token vulnerable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rfPuqlTK-2_qmrfNQ7gEZQ.png" /><figcaption>jwk, jku, and security vulnerability</figcaption></figure><p>These are standard fields for payload. These fields usually called as claims.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kTD1eWdsNlZy4rUiWeyzVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*looW0AuIxSqKn6i3oILfLg.png" /></figure><p>Other than the standard payload fields, or usually called as standard claims, we can also has our own fields, depends to our own need. It is called as private claims. For example, we can have these private claims</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yPOzNACO1pG9qrqJvG2ZRw.png" /></figure><p>This is some sample for payload. Note that fields order is not important. Basically we can use any private claims, but doesnt mean we have to put all of our business fields in JWT tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RbmcAQESOLE6QGqaozOsgQ.png" /><figcaption>Sample JWT payload</figcaption></figure><p>In the payload, we have several fields for time validation : not before (nbf), and expired at (exp). Since we talk about networks, there might be a clock skew, or time difference, from one node to another. This time difference can means one node clock is faster or slower than the other. For example, client clock is currently 10:19, but server clock is already at 10:21.</p><p>Server is responsible to validate these time fields. During server validation, it is better to give time tolerance to handle the clock skew. This tolerance should be no more than few minutes. This time tolerance is usually called as leeway.</p><p>For sample code on JWT and encrypted JWT (JWE), see here.</p><p>Cheers</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f08d3279a0b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/batc/jwt-for-dummies-ok-not-100-dummies-1f08d3279a0b">JWT for Dummies (OK, not 100% dummies)</a> was originally published in <a href="https://medium.com/batc">BATC — BFI Agile Thought Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Our Own “Google Form”, in our Data Center]]></title>
            <link>https://medium.com/batc/our-own-google-form-in-our-data-center-c7c8889d234a?source=rss----90163a577ddd---4</link>
            <guid isPermaLink="false">https://medium.com/p/c7c8889d234a</guid>
            <category><![CDATA[forms]]></category>
            <dc:creator><![CDATA[Timotius Pamungkas]]></dc:creator>
            <pubDate>Tue, 16 Feb 2021 11:18:10 GMT</pubDate>
            <atom:updated>2021-02-16T11:17:53.728Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://www.udemy.com/course/microservice-pattern-architecture-java-spring-cloud-boot/?referralCode=1C822DAF42A54D36CD56">C</a>ovid has been a year by now, and the needs of digitalization is spiking. In simple form, we need data-entry form, digitally accessible (simple words : I want entry from <a href="http://www.something)./">www.something).</a></p><p>We have classic problem : more requests compared than engineers.</p><p>So the business user became creative. Instead of waiting engineering build forms, they build their form on google form.</p><p>Frankly speaking, google form is a form builder. But form builder is not just google form. Problem is, most of those good form builders store data on cloud. If we put customer data on google form, we must open internet access to every employee. Due to internal policy, it is not possible for that. After all, some remote areas has bad internet connection.</p><p>So we decide to have something like google form in our data center.</p><p>Build it? Nope, it will take a lot of time and effort, luxuries we don’t have. So we take a look to some form builder products, which needs to match these criterias:</p><ol><li>need to put on-premise</li><li>need to integrate well with our system (through API / message broker / direct database in some cases)</li><li>business user can use it (and customize it) easily</li></ol><p>After some time, we decide to put a try on form.io</p><p>So far, it is quite good. All of those criterias are fulfilled, and our engineering team load for working on small, ad-hoc forms can be decreased.</p><p>Well, I’m not going to explain a lot of form.io here. After all, it’s not as popular as kafka or spring or go. Just to want you to know that personally, I think form.io is good alternative if you need some form builder on your own data center (although they come in cloud too).</p><p>Cheers</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7c8889d234a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/batc/our-own-google-form-in-our-data-center-c7c8889d234a">Our Own “Google Form”, in our Data Center</a> was originally published in <a href="https://medium.com/batc">BATC — BFI Agile Thought Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explaining Pub/Sub Pattern for Noob]]></title>
            <link>https://medium.com/batc/explaining-pub-sub-pattern-for-noob-12a75cd63864?source=rss----90163a577ddd---4</link>
            <guid isPermaLink="false">https://medium.com/p/12a75cd63864</guid>
            <category><![CDATA[scratch-programming]]></category>
            <category><![CDATA[message-broker]]></category>
            <category><![CDATA[pub-sub]]></category>
            <dc:creator><![CDATA[Timotius Pamungkas]]></dc:creator>
            <pubDate>Wed, 25 Nov 2020 11:06:41 GMT</pubDate>
            <atom:updated>2020-11-25T11:44:56.626Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s just take a little break from all of those text-based, black (or white) IDE screens and pick something colorful.</p><p>I have a niece, currently on 6th grade and I’d like to teach her some tech stuff (although she prefers digital drawing using some manga tools, which I know nothing). Of course, It’s a bad idea to teach her kafka with avro serialization. So I’d like to teach her how to make some simple animation or game. For this, I just use <a href="https://scratch.mit.edu/">scratch</a>. For those who don’t know, it’s a simple, kid-friendly “programming” tools, where “programmer” arrange block statements.</p><p>In <a href="https://scratch.mit.edu/">scratch</a>, the “programmer” arrange this colorful block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*90D9Zqe9GEEstcmw8E3q1A.png" /><figcaption>scratch blocks</figcaption></figure><p>Instead of the usual boring stuff like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*HH_iGjNcOz6pCvF_JHSFDA.png" /><figcaption>In go, for simplicity</figcaption></figure><p>It’s simple and kid friendly. Nice for a break with my niece. One thing that quite catch my mind, is that scratch has <em>broadcast</em> and <em>receive</em> block. Seems familiar? Well, this is not really a message broker (kafka, rabbitmq) things. More like event bus… But they share the same basic concept. Publisher publish, and Listener that receives message reacts. Simply said, implementation of <strong>pub/sub pattern</strong>.</p><p>In scrath, this can be done when a character (or sprite in scratch term) publish message, the other character react. Take this for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*egUared5eRcB9sRyNhw_EQ.gif" /></figure><p>Basically, when I press space, the wizard publish a message. Princess listens (subscribe) and react to that message by turning into rabbit.</p><p>Here is the block code on wizard (publisher)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*eHBeojn15PTEQ8Aa8mJlQA.png" /></figure><p>And this is the block code on princess (subscriber)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*DuyrkYwXfV602BE5CzPr5Q.png" /></figure><p>Now, you that read this message might things “this is just simple pub/sub, nothing special”. Well, I’m trying to explain this to 6th grade girl who like to draw manga. Now, that’s a challenge!</p><p>So I’m thinking quite a bit how to explain this pub/sub. Now this is what I came in mind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fGB0hivPmD8jdBfhPQH-Tw.png" /></figure><p>Is this clear enough?</p><ol><li>There’s an event</li><li>Wizard shout a message (abracadabra)</li><li>Princess hear the shout (abracadabra)</li><li>Princess react to message by turning into rabbit</li></ol><p>P.S : happened instantly, only true love kiss can change the princess back</p><p>Hmmm, should be simple enough. In more technical terms (not for my niece of course)</p><ol><li>There’s an event (e.g. data change)</li><li>Publisher publish specific message regarding data change</li><li>Subscriber listens to particular message</li><li>Subscriber react to that particular message (do some API call, update data, etc)</li></ol><p>P.S : happened near-real-time, for all subscriber(s)</p><p>What do you think?</p><p>Here’s the project if you like : <a href="https://scratch.mit.edu/projects/454666154">https://scratch.mit.edu/projects/454666154</a></p><p>Just some random thoughts</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12a75cd63864" width="1" height="1" alt=""><hr><p><a href="https://medium.com/batc/explaining-pub-sub-pattern-for-noob-12a75cd63864">Explaining Pub/Sub Pattern for Noob</a> was originally published in <a href="https://medium.com/batc">BATC — BFI Agile Thought Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>