<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Muhammad Umar Al Fajar on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Umar Al Fajar on Medium]]></description>
        <link>https://medium.com/@umar-fajar14?source=rss-3e59dd4ecc8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8hHG_PKjVtNftvFD6gAnNA.jpeg</url>
            <title>Stories by Muhammad Umar Al Fajar on Medium</title>
            <link>https://medium.com/@umar-fajar14?source=rss-3e59dd4ecc8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 05:54:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@umar-fajar14/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Ekosistem dan Arsitektur Sains Data: Dari Raw Data sampai Jadi Insight]]></title>
            <link>https://umar-fajar14.medium.com/ekosistem-dan-arsitektur-sains-data-dari-raw-data-sampai-jadi-insight-e5c815d0b7a3?source=rss-3e59dd4ecc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5c815d0b7a3</guid>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Muhammad Umar Al Fajar]]></dc:creator>
            <pubDate>Fri, 14 Nov 2025 14:47:10 GMT</pubDate>
            <atom:updated>2025-11-14T14:47:10.175Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*I1w17tmaCdPsN-8DrbXFDA.jpeg" /><figcaption><a href="https://storyset.com/illustration/data-report/pana#4E7FE3FF&amp;hide=&amp;hide=complete">https://storyset.com/illustration/data-report/pana#4E7FE3FF&amp;hide=&amp;hide=complete</a></figcaption></figure><p>Kalau ngomongin <em>data science</em>, banyak orang langsung kebayang Python dan machine learning.<br>Padahal, sebelum itu, ada “sesuatu” besar yang kerja di belakang: <strong>ekosistem dan arsitektur sains data</strong>.<br>Tanpa ekosistem yang rapi, model sebagus apa pun bakal kesulitan dipakai di dunia nyata.</p><h3>Kenapa Sains Data Butuh Ekosistem?</h3><p>Setiap hari kita ninggalin jejak digital: belanja online, scroll media sosial, pakai aplikasi ojek online, nonton film streaming, dan lain-lain. Semuanya menghasilkan data dalam jumlah besar, dari berbagai sumber, dengan bentuk yang beda-beda.</p><p>Masalahnya, data itu:</p><ul><li>nggak selalu rapi,</li><li>datang terus-menerus,</li><li>dan nyebar di banyak sistem.</li></ul><p>Karena itu, data science butuh <strong>ekosistem</strong>:<br>kumpulan alat, proses, dan orang yang saling terhubung, dari mulai data dikumpulkan sampai akhirnya dipakai buat ambil keputusan.</p><h3>Apa Itu Ekosistem Sains Data?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*f_5VotLYSEuUqgSun-0eUg.jpeg" /><figcaption><a href="https://storyset.com/illustration/on-the-office/amico#4E7FE3FF&amp;hide=&amp;hide=complete">https://storyset.com/illustration/on-the-office/amico#4E7FE3FF&amp;hide=&amp;hide=complete</a></figcaption></figure><p>Secara sederhana, <strong>ekosistem sains data</strong> adalah “dunia lengkap” yang mengelilingi aktivitas data science.</p><p>Di dalamnya ada:</p><ul><li><strong>Teknologi</strong>: database, data lake, data warehouse, pipeline, dashboard, model ML, API, dan sebagainya.</li><li><strong>Proses</strong>: mengumpulkan data, membersihkan, menyimpan, menganalisis, sampai deployment.</li><li><strong>Orang</strong>: data engineer, data scientist, data analyst, ML engineer, dan stakeholder bisnis.</li></ul><p>Semua bagian ini saling bergantung. Kalau pipeline data putus, kualitas model ikut kena. Kalau data nggak beres, insight juga jadi menyesatkan.</p><h3>Komponen Utama Ekosistem Sains Data</h3><p>Supaya lebih kebayang, ini beberapa komponen penting di dalamnya.</p><h4>1. Sumber Data</h4><p>Ini titik awal. Data bisa datang dari:</p><ul><li>aplikasi web dan mobile,</li><li>sistem transaksi,</li><li>sensor IoT,</li><li>log server dan event sistem,</li><li>sampai interaksi user di media sosial.</li></ul><p>Bentuk datanya bisa terstruktur (tabel), semi-terstruktur (JSON, log), atau tidak terstruktur (teks, gambar, video).</p><h4>2. Penyimpanan: Data Lake &amp; Data Warehouse</h4><p>Begitu terkumpul, data butuh tempat tinggal.</p><ul><li><strong>Data lake</strong>: menyimpan data mentah dalam berbagai format. Cocok untuk eksplorasi dan big data.</li><li><strong>Data warehouse</strong>: menyimpan data yang sudah dirapikan dan disusun untuk analisis dan laporan.</li></ul><p>Seringnya, data masuk dulu ke data lake, lalu sebagian diolah dan dipindah ke data warehouse untuk kebutuhan report dan dashboard.</p><h4>3. Pemrosesan: Batch dan Stream</h4><p>Sebelum dianalisis, data biasanya dibersihkan dan ditransformasi dulu.</p><ul><li><strong>Batch processing</strong>: data diproses per “paket”, misalnya sekali sehari. Cocok untuk laporan berkala.</li><li><strong>Stream processing</strong>: data diproses real-time saat masuk. Cocok untuk deteksi fraud, notifikasi langsung, atau monitoring sensor.</li></ul><p>Dua-duanya sama-sama penting, tergantung kebutuhan.</p><h4>4. Analytical Data Store &amp; Analisis</h4><p>Data yang sudah siap pakai disimpan di tempat yang enak untuk di-<em>query</em>: data warehouse, OLAP, atau tabel analitik.</p><p>Dari sini:</p><ul><li>data analyst bikin laporan dan dashboard,</li><li>data scientist mengambil data untuk eksplorasi dan training model.</li></ul><p>Tools yang sering dipakai misalnya SQL, Python, R, Power BI, atau Tableau.</p><h3>Dari Model sampai Production: Deployment &amp; MLOps</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*RMTE8vzSI2XANHFle3zrHg.jpeg" /><figcaption><a href="https://storyset.com/illustration/online-world/amico#688FC8FF&amp;hide=&amp;hide=complete">https://storyset.com/illustration/online-world/amico#688FC8FF&amp;hide=&amp;hide=complete</a></figcaption></figure><p>Model yang dibuat di laptop belum otomatis siap dipakai jutaan user.</p><p>Supaya benar-benar berguna, model perlu:</p><ul><li>dijadikan service (misalnya REST API),</li><li>di-deploy ke server atau cloud,</li><li>dihubungkan ke aplikasi.</li></ul><p>Di tahap ini, muncul konsep <strong>MLOps</strong>: praktik mengelola lifecycle model, dari eksperimen, deployment, sampai monitoring dan retraining ketika performa mulai turun.</p><h3>Siapa Saja yang Main di Ekosistem Ini?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*KW79DsY8o8ck5_WoV0kcKw.jpeg" /><figcaption><a href="https://storyset.com/illustration/team-work/rafiki">https://storyset.com/illustration/team-work/rafiki</a></figcaption></figure><p>Ekosistem sains data bukan kerja satu orang saja. Ada beberapa peran penting, misalnya:</p><ul><li><strong>Data Engineer</strong> — bangun dan rawat infrastruktur data: pipeline, data lake, dan data warehouse.</li><li><strong>Data Scientist</strong> — eksplorasi data, bangun dan menguji model machine learning.</li><li><strong>Data Analyst</strong> — fokus ke dashboard, report, dan insight yang bisa langsung dipakai tim bisnis.</li><li><strong>Machine Learning Engineer</strong> — memastikan model bisa jalan stabil di production dan skala besar.</li><li><strong>Stakeholder / Business User</strong> — orang-orang yang memakai insight dan prediksi untuk ambil keputusan.</li></ul><p>Setiap peran punya fokus beda, tapi semuanya tinggal di ekosistem yang sama.</p><h3>Tantangan dan Masa Depan Ekosistem Sains Data</h3><p>Membangun ekosistem sains data bukan hal sepele. Beberapa tantangan yang sering muncul:</p><ul><li>Data tersebar di banyak sistem (data silo).</li><li>Kualitas data kurang baik.</li><li>Gap antara model di eksperimen dan performa di produksi.</li><li>Isu privasi dan keamanan data user.</li></ul><p>Di sisi lain, banyak tren menarik yang mulai muncul:</p><ul><li><strong>MLOps dan DataOps</strong> untuk mengelola pipeline dan model secara lebih rapi.</li><li><strong>AutoML</strong> yang membantu mempercepat eksperimen.</li><li><strong>Lakehouse</strong> yang menggabungkan konsep data lake dan data warehouse.</li><li><strong>Edge AI</strong> dan <strong>Responsible AI</strong> yang fokus ke AI yang lebih dekat ke pengguna dan lebih etis.</li></ul><p>Pada akhirnya, memahami ekosistem dan arsitektur sains data membuat kita sadar bahwa:</p><p>Data science bukan cuma soal bikin model,<br>tapi bagaimana keseluruhan sistem dari ujung ke ujung bisa bekerja dengan baik.</p><p>Dan dari situ, kita bisa mulai mikir:<br><strong>“Di bagian mana kita ingin berperan di ekosistem ini?”</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5c815d0b7a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your First CRUD Web Service with .NET Core: A Beginner’s Guide]]></title>
            <link>https://umar-fajar14.medium.com/build-your-first-crud-web-service-with-net-core-a-beginners-guide-27ca3ba32b7e?source=rss-3e59dd4ecc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/27ca3ba32b7e</guid>
            <category><![CDATA[net-core]]></category>
            <dc:creator><![CDATA[Muhammad Umar Al Fajar]]></dc:creator>
            <pubDate>Thu, 14 Mar 2024 09:00:09 GMT</pubDate>
            <atom:updated>2024-03-14T09:00:09.657Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Build Your First CRUD Web Service with .NET Core: A Beginner’s Guide</strong></h3><p>Web services are the invisible workhorses of the modern internet, allowing websites and apps to talk to each other and share data. CRUD web services are a powerful type of web service, designed to manage data in a structured way. By learning to build a CRUD web service with .NET Core, you’ll gain a core skill that’s vital for tons of web development projects. We’ll start from the ground up, and by the end, you’ll have a working CRUD web service ready to power your own ideas.</p><h4>Tools and Setup</h4><p>Before we start, make sure we have downloaded and installed everything we need.</p><ol><li>Visual Studio</li></ol><p><a href="https://learn.microsoft.com/en-us/visualstudio/releases/2022/release-notes">Visual Studio Community</a> will be our central hub, providing a streamlined development environment with code editing, debugging, and project management tools all in one place.</p><p>2. .NET SDK</p><p>.NET SDK is a set of tools for developing and running .NET applications. You can download it from the <a href="https://dotnet.microsoft.com/en-us/download">official Microsoft website</a>.</p><p>3. Microsoft SQL Server</p><p><a href="https://www.microsoft.com/en-us/sql-server/sql-server-downloads">Microsoft SQL Server</a> is a robust database management system, allowing us to store and manage the data our CRUD web service will work with.</p><p>4. SQL Server Management Studio (SSMS)</p><p><a href="https://learn.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-ver16">SSMS</a> is a graphical tool for managing MS SQL Server. It makes it easier to create databases, tables, and write queries.</p><h4>Create Database</h4><p>To start, create a database called ‘db_restaurant’ (or any name you prefer) using SSMS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*wvlxprCwE7AY-SCPeSP4GQ.png" /></figure><p>Then, right click in the database and choose New Query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*JAZRR3PhFMxrSWvBooXI2Q.png" /></figure><p>Add the tables ‘customers’, ‘foods’, and ‘transactions’ using the following SQL queries:</p><pre>CREATE TABLE customers (<br> customer_id INT PRIMARY KEY IDENTITY(1,1),<br> customer_name VARCHAR(100),<br> customer_address VARCHAR(255),<br> customer_phone VARCHAR(13),<br> created_at DATETIME2,<br> updated_at DATETIME2<br>)<br><br>CREATE TABLE foods (<br> food_id INT PRIMARY KEY IDENTITY(1,1),<br> food_name VARCHAR(100),<br> food_price DECIMAL(10,2),<br> created_at DATETIME2,<br> updated_at DATETIME2<br>)<br><br>CREATE TABLE transactions (<br> transaction_id INT PRIMARY KEY IDENTITY(1,1),<br> customer_id INT,<br> food_id INT,<br> quantity INT,<br> total_price DECIMAL(10,2),<br> transaction_date DATETIME2,<br> created_at DATETIME2,<br> updated_at DATETIME2<br> FOREIGN KEY (customer_id) REFERENCES customers(customer_id),<br> FOREIGN KEY (food_id) REFERENCES foods(food_id)<br>)</pre><p>After that, execute the query with Execute button or press (Alt + X).</p><h4>Create Project</h4><p>To get started, follow these steps to create a new project in Visual Studio 2022:</p><ul><li>Launch Visual Studio 2022 and select the option to “Create a New Project”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*6fUzfpeJz1s6euNnL9mgWQ.png" /></figure><ul><li>In the search bar, type “web api” and select the ASP.NET Core Web API template. Click “Next” to proceed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*v7U6nPC1vS78ADFp1eXGCw.png" /></figure><ul><li>In the next step, enter your project name and then click next.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*MhZJrL-8rV7bGVp5TPejyw.png" /></figure><ul><li>On the following page, select .NET 8.0 as the target framework, uncheck the “Configure for HTTPS” and click “Create” to proceed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*iAvcqp7AGO7tnBVQgNTmmQ.png" /></figure><p>After the project was successfully created, delete the <strong>WeatherForecast.cs</strong> and <strong>WeatherForecastController.cs </strong>because we won’t need it. Then, we need to install additional packages required for the project.</p><p>Within the project, go to Tools &gt; NuGet Package Manager &gt; Manage NuGet Packages for Solution. In the Browse tab, search for “Microsoft.EntityFrameworkCore” and install it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_mtoyp5aTpV_R3KSkNb-g.png" /></figure><h4><strong>Database Configuration</strong></h4><p>After creating the project, the next step is to add configuration details to connect to your database. Open the ‘appsettings.json’ file and add the following code:</p><pre>&quot;ConnectionStrings&quot;: {<br>  &quot;DefaultConnection&quot;: &quot;Data Source=your_db_server;Initial Catalog=your-db_name;Integrated Security=True;Connect Timeout=30;Encrypt=True;Trust Server Certificate=True;Application Intent=ReadWrite;Multi Subnet Failover=False&quot;<br>}</pre><ul><li><strong>‘appsettings.json’:</strong> This file is a core configuration file in ASP.NET Core projects. It’s used to store settings that the application can access.</li><li><strong>“ConnectionStrings”:</strong> This section within ‘appsettings.json’ is specifically designed to store database connection details.</li><li><strong>“DefaultConnection”:</strong> This is the name you’ll use to reference this connection string within your code.</li><li><strong>The Connection String Itself:</strong></li><li><strong>Data Source=your_db_server:</strong> Replace “your_db_server” with the actual address or name of your database server.</li><li><strong>Initial Catalog=your-db_name:</strong> Replace “your-db_name” with the name of the database you want to connect to.</li><li><strong>Integrated Security=True:</strong> This indicates using your Windows login credentials for authentication (if your database supports it).</li><li><strong>The other parameters (Connect Timeout, Encrypt, etc.)</strong> are security and connection management settings. You might need to adjust them for your specific database setup.</li></ul><h4>Create Models</h4><p>Once you have created the project and configured the database, it’s time to create the models. To do this, create a new folder called ‘Models’ and add three files as follows:</p><p><strong>Customer.cs</strong></p><pre>[Table(&quot;customers&quot;)]<br>    public class Customer<br>    {<br>        [Column(&quot;customer_id&quot;)]<br>        [Required]<br>        public int CustomerId { get; set; }<br><br>        [Column(&quot;customer_name&quot;)]<br>        [Required]<br>        [MinLength(1, ErrorMessage = &quot;Customer name cannot be empty&quot;)]<br>        [MaxLength(100, ErrorMessage = &quot;Customer name must not exceed 100 characters&quot;)]<br>        public string CustomerName { get; set; }<br><br>        [Column(&quot;customer_address&quot;)]<br>        [Required]<br>        [MinLength(1, ErrorMessage = &quot;Customer address cannot be empty&quot;)]<br>        [MaxLength(255, ErrorMessage = &quot;Customer address must not exceed 255 characters&quot;)]<br>        public string CustomerAddress { get; set; }<br><br>        [Column(&quot;customer_phone&quot;)]<br>        [Required]<br>        [MinLength(1, ErrorMessage = &quot;Customer phone cannot be empty&quot;)]<br>        [MaxLength(13, ErrorMessage = &quot;Customer phone must not exceed 13 characters&quot;)]<br>        public string CustomerPhone { get; set; }<br><br>        [Column(&quot;created_at&quot;)]<br>        public DateTime CreatedAt { get; set; }<br><br>        [Column(&quot;updated_at&quot;)]<br>        public DateTime UpdatedAt { get; set; }<br><br>        public ICollection&lt;Transaction&gt; Transactions { get; set; }<br>    }</pre><p>This code defines a C# class called Customer. This class represents a customer entity within your application&#39;s data model. It&#39;s likely to map directly to a &#39;customers&#39; table in your database.</p><p><strong>Explanation</strong></p><ul><li><strong>[Table(“customers”)]<br></strong>This is an attribute from Entity Framework Core. It instructs EF Core to map this Customer class to a database table named &quot;customers&quot;.</li><li><strong>public class Customer<br></strong>This line simply defines the class with the name Customer.</li><li><strong>Properties (e.g., CustomerId, CustomerName)<br></strong>Each property with get; set; represents a column in the &#39;customers&#39; database table.<br>The [Column] attributes above the properties allow you to further control the mapping (like specifying exact column names).</li><li><strong>Data Annotations (e.g., [Required], [MinLength], [MaxLength])<br></strong>These attributes add validation rules to your model:<br>[Required] means the field cannot be empty.<br>[MinLength], [MaxLength] enforce minimum and maximum lengths for the values in those columns.</li><li><strong>ICollection&lt;Transaction&gt; Transactions { get; set; }<br></strong>This defines a relationship. This property is likely used for navigation and indicates that a customer can have multiple transactions associated with them (a one-to-many relationship).</li></ul><p><strong>Food.cs</strong></p><pre>[Table(&quot;foods&quot;)]<br>    public class Food<br>    {<br>        [Column(&quot;food_id&quot;)]<br>        [Required]<br>        public int FoodId { get; set; }<br><br>        [Column(&quot;food_name&quot;)]<br>        [Required]<br>        [MinLength(1, ErrorMessage = &quot;Food name cannot be empty&quot;)]<br>        [MaxLength(100, ErrorMessage = &quot;Food name must not exceed 100 characters&quot;)]<br>        public string FoodName { get; set; }<br><br>        [Column(&quot;food_price&quot;)]<br>        [Required]<br>        public decimal FoodPrice { get; set; }<br><br>        [Column(&quot;created_at&quot;)]<br>        public DateTime CreatedAt { get; set; }<br><br>        [Column(&quot;updated_at&quot;)]<br>        public DateTime UpdatedAt { get; set; }<br><br>        public ICollection&lt;Transaction&gt; Transactions { get; set; }<br>    }</pre><p><strong>Transaction.cs</strong></p><pre>[Table(&quot;transactions&quot;)]<br>    public class Transaction<br>    {<br>        [Column(&quot;transaction_id&quot;)]<br>        [Required]<br>        public int TransactionId { get; set; }<br><br>        [Column(&quot;customer_id&quot;)]<br>        [Required]<br>        public int CustomerId { get; set; }<br><br>        [Column(&quot;food_id&quot;)]<br>        [Required]<br>        public int FoodId { get; set; }<br><br>        [Column(&quot;quantity&quot;)]<br>        [Required]<br>        public int Quantity { get; set; }<br><br>        [Column(&quot;total_price&quot;)]<br>        [Required]<br>        public decimal TotalPrice { get; set; }<br><br>        [Column(&quot;transaction_date&quot;)]<br>        [Required]<br>        public DateTime TransactionDate { get; set; }<br><br>        [Column(&quot;created_at&quot;)]<br>        public DateTime CreatedAt { get; set; }<br><br>        [Column(&quot;updated_at&quot;)]<br>        public DateTime UpdatedAt { get; set; }<br><br>        public Customer Customer { get; set; }<br><br>        public Food Food { get; set; }<br>    }</pre><ul><li><strong>Customer Customer { get; set; }</strong> &amp; <strong>Food Food { get; set; }</strong> These properties establish the relationships to the Customer and Food models, allowing you to easily navigate between related data.</li></ul><h4><strong>Create DbContext</strong></h4><pre>public class RestaurantDbContext : DbContext<br>{<br>    public RestaurantDbContext(DbContextOptions&lt;RestaurantDbContext&gt; options) : base(options)<br>    {<br><br>    }<br><br>    public DbSet&lt;Customer&gt; Customers { get; set; }<br>    public DbSet&lt;Food&gt; Foods { get; set; }<br>    public DbSet&lt;Transaction&gt; Transactions { get; set; }<br><br>    public override int SaveChanges()<br>    {<br>        foreach (var entry in ChangeTracker.Entries())<br>        {<br>            if (entry.State == EntityState.Added)<br>            {<br>                entry.Property(&quot;CreatedAt&quot;).CurrentValue = DateTime.UtcNow;<br>            }<br>            else if (entry.State == EntityState.Modified)<br>            {<br>                entry.Property(&quot;UpdatedAt&quot;).CurrentValue = DateTime.UtcNow;<br>            }<br>        }<br>        return base.SaveChanges();<br>    }<br>}</pre><p><strong>Explanations:</strong></p><ul><li><strong>DbContext Inheritance:<br></strong>public class RestaurantDbContext : DbContext - The class inherits from DbContext, a core class in Entity Framework Core. This inheritance is what allows it to interact with your database.</li><li><strong>Constructor:<br></strong>public RestaurantDbContext(DbContextOptions&lt;RestaurantDbContext&gt; options) : base(options)<br>The constructor is essential for setting up the DbContext.<br>It receives DbContextOptions (configuration settings) and passes them to the base class (DbContext)&#39;s constructor.</li><li><strong>DbSets:<br></strong>public DbSet&lt;Customer&gt; Customers { get; set; }<br>public DbSet&lt;Food&gt; Foods { get; set; }<br>public DbSet&lt;Transaction&gt; Transactions { get; set; }<br>These properties represent the tables in your database and provide a way for your application to query and manipulate data within those tables.</li><li><strong>SaveChanges Override:<br></strong>public override int SaveChanges()<br>This method overrides the default behavior of how Entity Framework Core saves changes to the database.</li></ul><p><strong>Inside the code:</strong></p><ul><li>foreach (var entry in ChangeTracker.Entries()) - It loops through changed entities EF is tracking.</li><li>if (entry.State == EntityState.Added) ... - Checks if an entity is new (being added).</li><li>entry.Property(&quot;CreatedAt&quot;).CurrentValue = DateTime.UtcNow; - Automatically sets the &#39;CreatedAt&#39; property to the current date and time (UTC).</li><li>else if (entry.State == EntityState.Modified) ... - Checks if an entity is being modified.</li><li>entry.Property(&quot;UpdatedAt&quot;).CurrentValue = DateTime.UtcNow; - Sets the &#39;UpdatedAt&#39; property to the current date and time (UTC).</li><li>return base.SaveChanges(); - Finally, calls the base implementation to actually persist the changes to the database.</li></ul><p><strong>Key Points</strong></p><ul><li><strong>Context Purpose:</strong> This class defines a data context, specifically named RestaurantDbContext, likely modeling a restaurant&#39;s data.</li><li><strong>DbSets = Tables:</strong> Think of Customers, Foods, and Transactions as representations of their corresponding database tables.</li><li><strong>Automatic Timestamps:</strong> The SaveChanges() override provides a convenient way to manage creation and update timestamps without extra code elsewhere in your application.</li></ul><h4>Create DTO</h4><p>The next step is to create Data Transfer Objects (DTOs). DTOs are used to wrap requests and responses. They can be customized to fit the specific needs of your application.</p><ol><li>Create a new folder called DTO in the Models folder.</li><li>Create two new folders inside the DTO folder, called Request and Response.</li><li>Add files to each folder as needed.</li></ol><p><strong>CustomerRequest.cs</strong></p><pre>public class CustomerRequest<br>    {<br>        [Required]<br>        [MinLength(1, ErrorMessage = &quot;Customer name cannot be empty&quot;)]<br>        [MaxLength(100, ErrorMessage = &quot;Customer name must not exceed 100 characters&quot;)]<br>        public string CustomerName { get; set; }<br><br>        [Required]<br>        [MinLength(1, ErrorMessage = &quot;Customer address cannot be empty&quot;)]<br>        [MaxLength(255, ErrorMessage = &quot;Customer address must not exceed 255 characters&quot;)]<br>        public string CustomerAddress { get; set; }<br><br>        [Required]<br>        [MinLength(1, ErrorMessage = &quot;Customer phone cannot be empty&quot;)]<br>        [MaxLength(13, ErrorMessage = &quot;Customer phone must not exceed 13 characters&quot;)]<br>        public string CustomerPhone { get; set; }<br>    }</pre><p><strong>CustomerResponse.cs</strong></p><pre>public class CustomerResponse<br>    {<br>        public int CustomerId { get; set; }<br><br>        public string CustomerName { get; set; }<br><br>        public string CustomerAddress { get; set; }<br><br>        public string CustomerPhone { get; set; }<br>    }</pre><p>You’ll also need to create request and response DTOs specifically for handling food and transaction data.</p><h4>Create Services</h4><p>The next step in building your ASP.NET Core application involves creating <strong>Services</strong>. Services are classes responsible for specific functionalities within your application.</p><p>First, create a new folder in the root directory named <strong>Services, </strong>also create a folder named <strong>Interfaces</strong> in it.</p><p>Interfaces in C# define a contract. A class that implements an interface <strong>must</strong> provide implementations for the methods defined in the interface.</p><p><strong>ICustomerService.cs</strong></p><pre>public interface ICustomerService<br>{<br>    ICollection&lt;Customer&gt; GetCustomers();<br>    ResponseAPI&lt;CustomerResponse&gt; GetDetailCustomer(int customerId);<br>    ResponseAPI&lt;CustomerResponse&gt; AddCustomer(CustomerRequest request);<br>    ResponseAPI&lt;CustomerResponse&gt; EditCustomer(int customerId, CustomerRequest request);<br>    ResponseAPI&lt;CustomerResponse&gt; DeleteCustomer(int customerId);<br>}</pre><ul><li>GetCustomers(): Likely retrieves a list of all customers from the database.</li><li>GetDetailCustomer(int cust): Retrieves the details of a specific customer based on their ID.</li><li>AddCustomer(CustomerRequest request): Adds a new customer, taking a CustomerRequest DTO as input.</li><li>EditCustomer(int customerId, CustomerRequest request): Updates an existing customer.</li><li>DeleteCustomer(int customerId): Deletes a customer.</li></ul><p><strong>IFoodService.cs</strong></p><pre>public interface IFoodService<br>{<br>    ICollection&lt;Food&gt; GetFoods();<br>    ResponseAPI&lt;FoodResponse&gt; GetDetailFood(int foodId);<br>    ResponseAPI&lt;FoodResponse&gt; AddFood(FoodRequest request);<br>    ResponseAPI&lt;FoodResponse&gt; EditFood(int foodId, FoodRequest request);<br>    ResponseAPI&lt;FoodResponse&gt; DeleteFood(int foodId);<br>}</pre><ul><li><strong>IFoodService:</strong> Has a very similar structure to ICustomerService but focuses on food items.</li></ul><p><strong>ITransactionService.cs</strong></p><pre>public interface ITransactionService<br>{<br>    ICollection&lt;Transaction&gt; GetTransactions();<br>    ResponseAPI&lt;TransactionResponse&gt; GetDetailTransaction(int transactionId);<br>    ResponseAPI&lt;TransactionResponse&gt; AddTransaction(TransactionRequest request);<br>    ResponseAPI&lt;TransactionResponse&gt; EditTransaction(int transactionId, TransactionRequest request);<br>    ResponseAPI&lt;TransactionResponse&gt; DeleteTransaction(int transactionId);<br>}</pre><ul><li><strong>ITransactionService:</strong> Also follows the same core pattern but manages transactions (orders) within your system.</li></ul><p>Now let’s create the service:</p><p><strong>CustomerService.cs</strong></p><pre>public class CustomerService : ICustomerService<br>{<br>    private readonly RestaurantDbContext _context;<br><br>    public CustomerService(RestaurantDbContext context)<br>    {<br>        _context = context;<br>    }<br><br>    public ICollection&lt;Customer&gt; GetCustomers()<br>    {<br>        try<br>        {<br>            return _context.Customers.ToList();<br>        }<br>        catch (Exception ex)<br>        {<br>            throw new Exception(ex.Message);<br>        }<br>    }<br><br>    public ResponseAPI&lt;CustomerResponse&gt; GetDetailCustomer(int customerId)<br>    {<br>        try<br>        {<br>            var customer = _context.Customers.FirstOrDefault(c =&gt; c.CustomerId == customerId);<br>            if (customer != null)<br>            {<br>                return new ResponseAPI&lt;CustomerResponse&gt;<br>                {<br>                    Data = new CustomerResponse<br>                    {<br>                        CustomerId = customer.CustomerId,<br>                        CustomerName = customer.CustomerName,<br>                        CustomerAddress = customer.CustomerAddress,<br>                        CustomerPhone = customer.CustomerPhone,<br>                    },<br>                    Message = &quot;Successfully loaded customer data&quot;<br>                };<br>            }<br>            else<br>            {<br>                return new ResponseAPI&lt;CustomerResponse&gt;<br>                {<br>                    Message = &quot;Customer not found&quot;<br>                };<br>            }<br>        }<br>        catch (Exception ex)<br>        {<br>            throw new Exception(ex.Message);<br>        }<br>    }<br><br>    public ResponseAPI&lt;CustomerResponse&gt; AddCustomer(CustomerRequest request)<br>    {<br>        var newCustomer = new Customer<br>        {<br>            CustomerName = request.CustomerName,<br>            CustomerAddress = request.CustomerAddress,<br>            CustomerPhone = request.CustomerPhone<br>        };<br><br>        try<br>        {<br>            _context.Customers.Add(newCustomer);<br>            _context.SaveChanges();<br><br>            return new ResponseAPI&lt;CustomerResponse&gt;<br>            {<br>                Data = new CustomerResponse<br>                {<br>                    CustomerId = newCustomer.CustomerId,<br>                    CustomerName = newCustomer.CustomerName,<br>                    CustomerAddress = newCustomer.CustomerAddress,<br>                    CustomerPhone = newCustomer.CustomerPhone,<br>                },<br>                Message = &quot;Successfully added customer data&quot;<br>            };<br>        }<br>        catch (Exception ex)<br>        {<br>            throw new Exception(ex.Message);<br>        }<br>    }<br><br>    public ResponseAPI&lt;CustomerResponse&gt; EditCustomer(int customerId, CustomerRequest request)<br>    {<br>        try<br>        {<br>            var customer = _context.Customers.FirstOrDefault(x =&gt; x.CustomerId == customerId);<br>            if (customer != null)<br>            {<br>                customer.CustomerName = request.CustomerName;<br>                customer.CustomerAddress = request.CustomerAddress;<br>                customer.CustomerPhone = request.CustomerPhone;<br>                _context.SaveChanges();<br><br>                return new ResponseAPI&lt;CustomerResponse&gt;<br>                {<br>                    Data = new CustomerResponse<br>                    {<br>                        CustomerId = customerId,<br>                        CustomerName = customer.CustomerName,<br>                        CustomerAddress = customer.CustomerAddress,<br>                        CustomerPhone = customer.CustomerPhone<br>                    },<br>                    Message = &quot;Successfully updated customer data&quot;<br>                };<br>            }<br>            else<br>            {<br>                return new ResponseAPI&lt;CustomerResponse&gt;<br>                {<br>                    Message = &quot;Customer not found&quot;<br>                };<br>            }<br>        }<br>        catch (Exception ex)<br>        {<br>            throw new Exception(ex.Message);<br>        }<br>    }<br><br>    public ResponseAPI&lt;CustomerResponse&gt; DeleteCustomer(int customerId)<br>    {<br>        try<br>        {<br>            var customer = _context.Customers.FirstOrDefault(c =&gt; c.CustomerId == customerId);<br>            if (customer != null)<br>            {<br>                _context.Customers.Remove(customer);<br>                _context.SaveChanges();<br><br>                return new ResponseAPI&lt;CustomerResponse&gt;<br>                {<br>                    Message = &quot;Successfully deleted customer data&quot;<br>                };<br>            }<br>            else<br>            {<br>                return new ResponseAPI&lt;CustomerResponse&gt;<br>                {<br>                    Message = &quot;Customer not found&quot;<br>                };<br>            }<br>        }<br>        catch (Exception ex)<br>        {<br>            throw new Exception(ex.Message);<br>        }<br>    }<br>}</pre><p><strong>FoodService.cs</strong></p><pre>public class FoodService : IFoodService<br>{<br>    private readonly RestaurantDbContext _context;<br><br>    public FoodService(RestaurantDbContext context)<br>    {<br>        _context = context;<br>    }<br><br>    public ICollection&lt;Food&gt; GetFoods()<br>    {<br>        try<br>        {<br>            return _context.Foods.ToList();<br>        }<br>        catch (Exception ex)<br>        {<br>            throw new Exception(ex.Message);<br>        }<br>    }<br><br>    public ResponseAPI&lt;FoodResponse&gt; GetDetailFood(int foodId)<br>    {<br>        try<br>        {<br>            var food = _context.Foods.FirstOrDefault(f =&gt; f.FoodId == foodId);<br>            if (food != null)<br>            {<br>                return new ResponseAPI&lt;FoodResponse&gt;<br>                {<br>                    Data = new FoodResponse<br>                    {<br>                        FoodId = food.FoodId,<br>                        FoodName = food.FoodName,<br>                        FoodPrice = food.FoodPrice<br>                    },<br>                    Message = &quot;Successfully loaded food data&quot;<br>                };<br>            }<br>            else<br>            {<br>                return new ResponseAPI&lt;FoodResponse&gt;<br>                {<br>                    Message = &quot;Food not found&quot;<br>                };<br>            }<br>        }<br>        catch (Exception ex)<br>        {<br>            throw new Exception(ex.Message);<br>        }<br>    }<br><br>    public ResponseAPI&lt;FoodResponse&gt; AddFood(FoodRequest request)<br>    {<br>        var newFood = new Food<br>        {<br>            FoodName = request.FoodName,<br>            FoodPrice = request.FoodPrice<br>        };<br><br>        try<br>        {<br>            _context.Foods.Add(newFood);<br>            _context.SaveChanges();<br><br>            return new ResponseAPI&lt;FoodResponse&gt;<br>            {<br>                Data = new FoodResponse<br>                {<br>                    FoodId = newFood.FoodId,<br>                    FoodName = newFood.FoodName,<br>                    FoodPrice = newFood.FoodPrice<br>                },<br>                Message = &quot;Successfully added food data&quot;<br>            };<br>        }<br>        catch (Exception ex)<br>        {<br>            throw new Exception(ex.Message);<br>        }<br>    }<br><br>    public ResponseAPI&lt;FoodResponse&gt; EditFood(int foodId, FoodRequest request)<br>    {<br>        try<br>        {<br>            var food = _context.Foods.FirstOrDefault(f =&gt; f.FoodId == foodId);<br>            if (food != null)<br>            {<br>                food.FoodName = request.FoodName;<br>                food.FoodPrice = request.FoodPrice;<br>                _context.SaveChanges();<br><br>                return new ResponseAPI&lt;FoodResponse&gt;<br>                {<br>                    Data = new FoodResponse<br>                    {<br>                        FoodId = food.FoodId,<br>                        FoodName = food.FoodName,<br>                        FoodPrice = food.FoodPrice<br>                    },<br>                    Message = &quot;Successfully updated food data&quot;<br>                };<br>            }<br>            else<br>            {<br>                return new ResponseAPI&lt;FoodResponse&gt;<br>                {<br>                    Message = &quot;Food not found&quot;<br>                };<br>            }<br>        }<br>        catch (Exception ex)<br>        {<br>            throw new Exception(ex.Message);<br>        }<br>    }<br><br>    public ResponseAPI&lt;FoodResponse&gt; DeleteFood(int foodId)<br>    {<br>        try<br>        {<br>            var food = _context.Foods.FirstOrDefault(f =&gt; f.FoodId == foodId);<br>            if (food != null)<br>            {<br>                _context.Remove(food);<br>                _context.SaveChanges();<br><br>                return new ResponseAPI&lt;FoodResponse&gt;<br>                {<br>                    Message = &quot;Successfully deleted food data&quot;<br>                };<br>            }<br>            else<br>            {<br>                return new ResponseAPI&lt;FoodResponse&gt;<br>                {<br>                    Message = &quot;Food not found&quot;<br>                };<br>            };<br>        }<br>        catch (Exception ex)<br>        {<br>            throw new Exception(ex.Message);<br>        }<br>    }<br>}</pre><p><strong>TransactionService.cs</strong></p><pre>public class TransactionService : ITransactionService<br>{<br>    private readonly RestaurantDbContext _context;<br><br>    public TransactionService(RestaurantDbContext context)<br>    {<br>        _context = context;<br>    }<br><br>    public ICollection&lt;Transaction&gt; GetTransactions()<br>    {<br>        try<br>        {<br>            return _context.Transactions.Include(t =&gt; t.Customer).Include(t =&gt; t.Food).ToList();<br>        }<br>        catch (Exception ex)<br>        {<br>            throw new Exception(ex.Message);<br>        }<br>    }<br><br>    public ResponseAPI&lt;TransactionResponse&gt; GetDetailTransaction(int transactionId)<br>    {<br>        try<br>        {<br>            var transaction = _context.Transactions.Include(t =&gt; t.Customer).Include(t =&gt; t.Food).FirstOrDefault(t =&gt; t.TransactionId == transactionId);<br><br>            if (transaction != null)<br>            {<br>                return new ResponseAPI&lt;TransactionResponse&gt;<br>                {<br>                    Data = new TransactionResponse<br>                    {<br>                        TransactionId = transaction.TransactionId,<br>                        Customer = new CustomerResponse<br>                        {<br>                            CustomerId = transaction.CustomerId,<br>                            CustomerName = transaction.Customer.CustomerName,<br>                            CustomerAddress = transaction.Customer.CustomerAddress,<br>                            CustomerPhone = transaction.Customer.CustomerPhone<br>                        },<br>                        Food = new FoodResponse<br>                        {<br>                            FoodId = transaction.FoodId,<br>                            FoodName = transaction.Food.FoodName,<br>                            FoodPrice = transaction.Food.FoodPrice,<br>                        },<br>                        Quantity = transaction.Quantity,<br>                        TotalPrice = transaction.TotalPrice,<br>                        TransactionDate = transaction.TransactionDate<br>                    },<br>                    Message = &quot;Successfully loaded data&quot;<br>                };<br>            }<br>            else<br>            {<br>                return new ResponseAPI&lt;TransactionResponse&gt;<br>                {<br>                    Message = &quot;Transaction not found&quot;<br>                };<br>            }<br>        }<br>        catch (Exception ex)<br>        {<br>            throw new Exception(ex.Message);<br>        }<br>    }<br><br>    public ResponseAPI&lt;TransactionResponse&gt; AddTransaction(TransactionRequest request)<br>    {<br>        try<br>        {<br>            var customer = _context.Customers.FirstOrDefault(c =&gt; c.CustomerId == request.CustomerId);<br>            var food = _context.Foods.FirstOrDefault(f =&gt; f.FoodId == request.FoodId);<br><br>            if (customer == null)<br>            {<br>                return new ResponseAPI&lt;TransactionResponse&gt;<br>                {<br>                    Message = &quot;Customer not found&quot;<br>                };<br>            }<br>            else if (food == null)<br>            {<br>                return new ResponseAPI&lt;TransactionResponse&gt;<br>                {<br>                    Message = &quot;Food not found&quot;<br>                };<br>            }<br>            else<br>            {<br>                var newTransaction = new Transaction<br>                {<br>                    Customer = customer,<br>                    Food = food,<br>                    Quantity = request.Quantity,<br>                    TotalPrice = request.Quantity * food.FoodPrice,<br>                    TransactionDate = DateTime.Now<br>                };<br><br>                _context.Transactions.Add(newTransaction);<br>                _context.SaveChanges();<br><br>                return new ResponseAPI&lt;TransactionResponse&gt;<br>                {<br>                    Data = new TransactionResponse<br>                    {<br>                        TransactionId = newTransaction.TransactionId,<br>                        Customer = new CustomerResponse<br>                        {<br>                            CustomerId = customer.CustomerId,<br>                            CustomerName = customer.CustomerName,<br>                            CustomerAddress = customer.CustomerAddress,<br>                            CustomerPhone = customer.CustomerPhone,<br>                        },<br>                        Food = new FoodResponse<br>                        {<br>                            FoodId = food.FoodId,<br>                            FoodName = food.FoodName,<br>                            FoodPrice = food.FoodPrice,<br>                        },<br>                        Quantity = newTransaction.Quantity,<br>                        TotalPrice = newTransaction.TotalPrice,<br>                        TransactionDate = newTransaction.TransactionDate<br>                    },<br>                    Message = &quot;Successfully added transaction data&quot;<br>                };<br>            }<br>        }<br>        catch (Exception ex)<br>        {<br>            throw new Exception(ex.Message);<br>        }<br>    }<br><br>    public ResponseAPI&lt;TransactionResponse&gt; EditTransaction(int transactionId, TransactionRequest request)<br>    {<br>        try<br>        {<br>            var transaction = _context.Transactions.Include(t =&gt; t.Customer).Include(t =&gt; t.Food).FirstOrDefault(t =&gt; t.TransactionId == transactionId);<br>            if (transaction != null)<br>            {<br>                var food = _context.Foods.FirstOrDefault(f =&gt; f.FoodId == request.FoodId);<br>                transaction.CustomerId = request.CustomerId;<br>                transaction.FoodId = request.FoodId;<br>                transaction.Quantity = request.Quantity;<br>                transaction.TotalPrice = request.Quantity * food.FoodPrice;<br>                transaction.TransactionDate = DateTime.Now;<br>                _context.SaveChanges();<br><br>                return new ResponseAPI&lt;TransactionResponse&gt;<br>                {<br>                    Data = new TransactionResponse<br>                    {<br>                        TransactionId = transaction.TransactionId,<br>                        Customer = new CustomerResponse<br>                        {<br>                            CustomerId = transaction.CustomerId,<br>                            CustomerName = transaction.Customer.CustomerName,<br>                            CustomerAddress = transaction.Customer.CustomerAddress,<br>                            CustomerPhone = transaction.Customer.CustomerPhone<br>                        },<br>                        Food = new FoodResponse<br>                        {<br>                            FoodId = transaction.FoodId,<br>                            FoodName = transaction.Food.FoodName,<br>                            FoodPrice = transaction.Food.FoodPrice,<br>                        },<br>                        Quantity = transaction.Quantity,<br>                        TotalPrice = transaction.TotalPrice,<br>                        TransactionDate = transaction.TransactionDate<br>                    },<br>                    Message = &quot;Successfully updated transaction data&quot;<br>                };<br>            }<br>            else<br>            {<br>                return new ResponseAPI&lt;TransactionResponse&gt;<br>                {<br>                    Message = &quot;Transaction not found&quot;<br>                };<br>            }<br>        }<br>        catch (Exception ex)<br>        {<br>            throw new Exception(ex.Message);<br>        }<br>    }<br><br>    public ResponseAPI&lt;TransactionResponse&gt; DeleteTransaction(int transactionId)<br>    {<br>        try<br>        {<br>            var transaction = _context.Transactions.FirstOrDefault(t =&gt; t.TransactionId == transactionId);<br>            if (transaction != null)<br>            {<br>                _context.Remove(transaction);<br>                _context.SaveChanges();<br><br>                return new ResponseAPI&lt;TransactionResponse&gt;<br>                {<br>                    Message = &quot;Successfully deleted transaction data&quot;<br>                };<br>            }<br>            else<br>            {<br>                return new ResponseAPI&lt;TransactionResponse&gt;<br>                {<br>                    Message = &quot;Transaction not found&quot;<br>                };<br>            }<br>        }<br>        catch (Exception ex)<br>        {<br>            throw new Exception(ex.Message);<br>        }<br>    }<br>}</pre><h4>Create Controllers</h4><p>First, create controllers filder in the root directory. <br>Controllers are intermediary classes responsible for handling incoming HTTP requests from the client (usually a web browser) and sending back HTTP responses. They act as the entry point for your application’s functionality.</p><p><strong>CustomersController.cs</strong></p><pre>[Route(&quot;api/customers&quot;)]<br>[ApiController]<br>public class CustomerController : Controller<br>{<br>    private readonly ICustomerService _customerService;<br><br>    public CustomerController(ICustomerService customerService)<br>    {<br>        _customerService = customerService;<br>    }<br><br>    [HttpGet]<br>    [ProducesResponseType(200, Type = typeof(IEnumerable&lt;CustomerResponse&gt;))]<br>    public IActionResult GetCustomers()<br>    {<br>        try<br>        {<br>            var data = _customerService.GetCustomers();<br>            var response = data.Select(c =&gt; new CustomerResponse<br>            {<br>                CustomerId = c.CustomerId,<br>                CustomerName = c.CustomerName,<br>                CustomerAddress = c.CustomerAddress,<br>                CustomerPhone = c.CustomerPhone<br>            });<br><br>            return Ok(response);<br>        }<br>        catch (Exception ex)<br>        {<br>            return BadRequest(ex.Message);<br>        }<br>    }<br><br>    [HttpGet(&quot;{customerId}&quot;)]<br>    [ProducesResponseType(200, Type = typeof(ResponseAPI&lt;CustomerResponse&gt;))]<br>    public IActionResult GetDetailCustomer([FromRoute] int customerId)<br>    {<br>        try<br>        {<br>            var response = _customerService.GetDetailCustomer(customerId);<br>            return Ok(response);<br>        }<br>        catch (Exception ex)<br>        {<br>            return BadRequest(ex.Message);<br>        }<br>    }<br><br>    [HttpPost(&quot;add&quot;)]<br>    [ProducesResponseType(200, Type = typeof(ResponseAPI&lt;CustomerResponse&gt;))]<br>    public IActionResult AddCustomer([FromBody] CustomerRequest request)<br>    {<br>        try<br>        {<br>            var response = _customerService.AddCustomer(request);<br>            return Ok(response);<br>        }<br>        catch (Exception ex)<br>        {<br>            return BadRequest(ex.Message);<br>        }<br>    }<br><br>    [HttpPut(&quot;edit/{customerId}&quot;)]<br>    [ProducesResponseType(200, Type = typeof(ResponseAPI&lt;CustomerResponse&gt;))]<br>    public IActionResult EditCustomer([FromRoute] int customerId, [FromBody] CustomerRequest request)<br>    {<br>        try<br>        {<br>            var response = _customerService.EditCustomer(customerId, request);<br>            return Ok(response);<br>        }<br>        catch (Exception ex)<br>        {<br>            return BadRequest(ex.Message);<br>        }<br>    }<br><br>    [HttpDelete(&quot;delete/{customerId}&quot;)]<br>    [ProducesResponseType(200, Type = typeof(ResponseAPI&lt;CustomerResponse&gt;))]<br>    public IActionResult DeleteCustomer([FromRoute] int customerId)<br>    {<br>        try<br>        {<br>            var response = _customerService.DeleteCustomer(customerId);<br>            return Ok(response);<br>        }<br>        catch (Exception ex)<br>        {<br>            return BadRequest(ex.Message);<br>        }<br>    }<br>}</pre><p><strong>FoodsController.cs</strong></p><pre>[Route(&quot;api/foods&quot;)]<br>[ApiController]<br>public class FoodController : Controller<br>{<br>    private readonly IFoodService _foodService;<br><br>    public FoodController(IFoodService foodService)<br>    {<br>        _foodService = foodService;<br>    }<br><br>    [HttpGet]<br>    [ProducesResponseType(200, Type = typeof(IEnumerable&lt;FoodResponse&gt;))]<br>    public IActionResult GetFoods()<br>    {<br>        try<br>        {<br>            var data = _foodService.GetFoods();<br>            var response = data.Select(f =&gt; new FoodResponse<br>            {<br>                FoodId = f.FoodId,<br>                FoodName = f.FoodName,<br>                FoodPrice = f.FoodPrice<br>            });<br><br>            return Ok(response);<br>        }<br>        catch (Exception ex)<br>        {<br>            return BadRequest(ex.Message);<br>        }<br>    }<br><br>    [HttpGet(&quot;{foodId}&quot;)]<br>    [ProducesResponseType(200, Type = typeof(ResponseAPI&lt;FoodResponse&gt;))]<br>    public IActionResult GetDetailFood([FromRoute] int foodId)<br>    {<br>        try<br>        {<br>            var response = _foodService.GetDetailFood(foodId);<br>            return Ok(response);<br>        }<br>        catch (Exception ex)<br>        {<br>            return BadRequest(ex.Message);<br>        }<br>    }<br><br>    [HttpPost(&quot;add&quot;)]<br>    [ProducesResponseType(200, Type = typeof(ResponseAPI&lt;FoodResponse&gt;))]<br>    public IActionResult AddFood([FromBody] FoodRequest request)<br>    {<br>        try<br>        {<br>            var response = _foodService.AddFood(request);<br>            return Ok(response);<br>        }<br>        catch (Exception ex)<br>        {<br>            return BadRequest(ex.Message);<br>        }<br>    }<br><br>    [HttpPut(&quot;edit/{foodId}&quot;)]<br>    [ProducesResponseType(200, Type = typeof(ResponseAPI&lt;FoodResponse&gt;))]<br>    public IActionResult EditFood([FromRoute] int foodId, [FromBody] FoodRequest request)<br>    {<br>        try<br>        {<br>            var response = _foodService.EditFood(foodId, request);<br>            return Ok(response);<br>        }<br>        catch (Exception ex)<br>        {<br>            return BadRequest(ex.Message);<br>        }<br>    }<br><br>    [HttpDelete(&quot;delete/{foodId}&quot;)]<br>    [ProducesResponseType(200, Type = typeof(ResponseAPI&lt;FoodResponse&gt;))]<br>    public IActionResult DeleteFood([FromRoute] int foodId)<br>    {<br>        try<br>        {<br>            var response = _foodService.DeleteFood(foodId);<br>            return Ok(response);<br>        }<br>        catch (Exception ex)<br>        {<br>            return BadRequest(ex.Message);<br>        }<br>    }<br>}</pre><p>TransactionsController.cs</p><pre>[Route(&quot;api/transactions&quot;)]<br>[ApiController]<br>public class TransactionController : Controller<br>{<br>    private readonly ITransactionService _transactionService;<br><br>    public TransactionController(ITransactionService transactionService)<br>    {<br>        _transactionService = transactionService;<br>    }<br><br>    [HttpGet]<br>    [ProducesResponseType(200, Type = typeof(IEnumerable&lt;TransactionResponse&gt;))]<br>    public IActionResult GetTransactions()<br>    {<br>        try<br>        {<br>            var data = _transactionService.GetTransactions();<br>            var response = data.Select(t =&gt; new TransactionResponse<br>            {<br>                TransactionId = t.TransactionId,<br>                Customer = new CustomerResponse { CustomerId = t.Customer.CustomerId, CustomerName = t.Customer.CustomerName, CustomerAddress = t.Customer.CustomerAddress, CustomerPhone = t.Customer.CustomerPhone },<br>                Food = new FoodResponse { FoodId = t.Food.FoodId, FoodName = t.Food.FoodName, FoodPrice = t.Food.FoodPrice },<br>                Quantity = t.Quantity,<br>                TotalPrice = t.TotalPrice,<br>                TransactionDate = t.TransactionDate,<br>            });<br><br>            return Ok(response);<br>        }<br>        catch (Exception ex)<br>        {<br>            return BadRequest(ex.Message);<br>        }<br>    }<br><br>    [HttpGet(&quot;{transactionId}&quot;)]<br>    [ProducesResponseType(200, Type = typeof(ResponseAPI&lt;TransactionResponse&gt;))]<br>    public IActionResult GetDetailTransaction([FromRoute] int transactionId)<br>    {<br>        try<br>        {<br>            var response = _transactionService.GetDetailTransaction(transactionId);<br>            return Ok(response);<br>        }<br>        catch (Exception ex)<br>        {<br>            return BadRequest(ex.Message);<br>        }<br>    }<br><br>    [HttpPost(&quot;add&quot;)]<br>    [ProducesResponseType(200, Type = typeof(ResponseAPI&lt;TransactionResponse&gt;))]<br>    public IActionResult AddTransaction([FromBody] TransactionRequest request)<br>    {<br>        try<br>        {<br>            var response = _transactionService.AddTransaction(request);<br>            return Ok(response);<br>        }<br>        catch (Exception ex)<br>        {<br>            return BadRequest(ex.Message);<br>        }<br>    }<br><br>    [HttpPut(&quot;edit/{transactionId}&quot;)]<br>    [ProducesResponseType(200, Type = typeof(ResponseAPI&lt;TransactionResponse&gt;))]<br>    public IActionResult EditTransaction([FromRoute] int transactionId, [FromBody] TransactionRequest request)<br>    {<br>        try<br>        {<br>            var response = _transactionService.EditTransaction(transactionId, request);<br>            return Ok(response);<br>        }<br>        catch (Exception ex)<br>        {<br>            return BadRequest(ex.Message);<br>        }<br>    }<br><br>    [HttpDelete(&quot;delete/{transactionId}&quot;)]<br>    [ProducesResponseType(200, Type = typeof(ResponseAPI&lt;TransactionResponse&gt;))]<br>    public IActionResult DeleteTransaction([FromRoute] int transactionId)<br>    {<br>        try<br>        {<br>            var response = _transactionService.DeleteTransaction(transactionId);<br>            return Ok(response);<br>        }<br>        catch (Exception ex)<br>        {<br>            return BadRequest(ex.Message);<br>        }<br>    }<br>}</pre><h4>Configure Program.cs</h4><p>We need to add:</p><pre>builder.Services.AddScoped&lt;ICustomerService, CustomerService&gt;();<br>builder.Services.AddScoped&lt;IFoodService, FoodService&gt;();<br>builder.Services.AddScoped&lt;ITransactionService, TransactionService&gt;();</pre><p><strong>Dependency Injection Registrations</strong></p><ul><li><strong>Lines like <br></strong>builder.Services.AddScoped&lt;ICustomerService, CustomerService&gt;();</li><li><strong>Purpose:</strong> These lines tell the built-in Dependency Injection (DI) system in ASP.NET Core how to fulfill requests for your interfaces (ICustomerService, IFoodService, etc.).</li><li><strong>How it works:</strong> When a controller needs an ICustomerService, the DI system knows to create a CustomerService instance because of this registration.</li></ul><p>and:</p><pre>builder.Services.AddDbContext&lt;RestaurantDbContext&gt;(options =&gt;<br>{<br>    options.UseSqlServer(builder.Configuration.GetConnectionString(&quot;DefaultConnection&quot;));<br>});</pre><p><strong>Adding the Database Context<br></strong>builder.Services.AddDbContext&lt;RestaurantDbContext&gt;(options =&gt; options.UseSqlServer(...));</p><ul><li><strong>Purpose:</strong> This registers RestaurantDbContext with the DI system and configures it to use SQL Server.</li><li><strong>How it works:<br></strong>options.UseSqlServer(...) tells Entity Framework Core to use SQL Server and provides the connection string to your database (DefaultConnection).</li><li><strong>Why it’s important:<br></strong>Services, such as CustomerService, need the RestaurantDbContext to interact with the database. This registration makes it available to them via Dependency Injection.</li></ul><h4>Run The Project</h4><p>Finally, we can try to run the project by pressing F5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RCDJHPdNMgwRkq21lq5stA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27ca3ba32b7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot, Kafka, and WebSocket: A Practical Approach to Real-Time Messaging]]></title>
            <link>https://umar-fajar14.medium.com/spring-boot-kafka-and-websocket-a-practical-approach-to-real-time-messaging-6169f5995fe1?source=rss-3e59dd4ecc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6169f5995fe1</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Muhammad Umar Al Fajar]]></dc:creator>
            <pubDate>Tue, 19 Dec 2023 10:24:50 GMT</pubDate>
            <atom:updated>2023-12-19T16:34:05.009Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZZswZbPD7_4XeaLaD3D6cQ.png" /><figcaption>Spring Boot, Kafka, and WebSocket</figcaption></figure><p>In the world of application development, real-time communication has become an essential feature. Whether it’s a social media app, a collaborative tool, or a live event streaming platform, the ability to exchange information in real-time enhances the user experience significantly. In this article, we will delve into the process of building a real-time chat application using Spring Boot, Kafka, and WebSocket.</p><p>Spring Boot, a project built on top of the Spring Framework, simplifies the bootstrapping and development of new Spring applications. Kafka, a distributed streaming platform, allows us to build real-time data pipelines and streaming apps with ease. WebSocket, on the other hand, provide a full-duplex communication channel over a single socket, making it ideal for real-time data transfer.</p><p>We will guide you through the process of setting up a Spring Boot application, integrating it with Kafka for message queuing, and using WebSocket for real-time communication. By the end of this article, you will have a solid understanding of how these technologies work together to create a real-time chat application.</p><p>If you have not prepared the Kafka environment, read this <a href="https://umar-fajar14.medium.com/locomotive-iot-simulation-with-nodejs-kafka-mongo-postgresql-logging-and-telegram-notification-e8fea351168b">article</a>. As for the Kafdrop, it’s optional; you can use the Kafka extension if you are using a JetBrains IDE. The repositories will be at the end of this article.</p><p>Let’s get started!</p><p>In the first section of our article, we will focus on setting up our Spring Boot application and integrating it with Kafka.</p><p>Spring Boot is a powerful framework that simplifies the setup and development of Spring applications. It provides a range of features such as auto-configuration, standalone-code, and embedded servers, which make it easier to create production-grade, stand-alone Spring applications.</p><p>To start, we need to set up our Spring Boot application. We can do this by using <strong><em>Spring Initializr</em></strong>, a tool provided by Spring to quickly bootstrap a Spring Boot application. For our chat application, we will need to include the `<strong>Web</strong>`, `<strong>Kafka</strong>`, `<strong>WebSocket</strong>`, and `<strong>Lombok</strong>` dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*LzTUGE0z4v87qu-8V8jwTA.png" /><figcaption>Spring Initializr</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*NLktFKGjfmbveit4v-8UFQ.png" /><figcaption>dependencies</figcaption></figure><p>Once our Spring Boot application is set up, we can start integrating it with Kafka. Kafka is a distributed streaming platform that is used for building real-time data pipelines and streaming apps. It is horizontally scalable, fault-tolerant, and incredibly fast, which makes it ideal for our real-time chat application.</p><p>First, let’s create `<strong>Message` </strong>class<strong> </strong>and `<strong>MessageType` </strong>class: These classes represent the message object and the types of messages that can be sent.</p><pre>@Getter<br>@Setter<br>@AllArgsConstructor<br>@NoArgsConstructor<br>@Builder<br>public class Message {<br>    private MessageType type;<br>    private String content;<br>    private String sender;<br>    private String sessionId;<br>}</pre><pre>public enum MessageType {<br>    CHAT,<br>    CONNECT,<br>    DISCONNECT<br>}</pre><p>After that, create `<strong>KafkaConsumerConfig</strong>` class:</p><pre>@Configuration<br>public class KafkaConsumerConfig {<br><br>    @Bean<br>    public ConsumerFactory&lt;String, Message&gt; consumerFactory() {<br>        Map&lt;String, Object&gt; configProps = new HashMap&lt;&gt;();<br>        configProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, &quot;localhost:9094&quot;);<br>        configProps.put(ConsumerConfig.GROUP_ID_CONFIG, &quot;chat&quot;);<br>        configProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);<br>        configProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class);<br>        return new DefaultKafkaConsumerFactory&lt;&gt;(configProps, new StringDeserializer(),<br>                new JsonDeserializer&lt;&gt;(Message.class));<br>    }<br><br>    @Bean<br>    public ConcurrentKafkaListenerContainerFactory&lt;String, Message&gt; kafkaListenerContainerFactory() {<br>        ConcurrentKafkaListenerContainerFactory&lt;String, Message&gt; factory = new ConcurrentKafkaListenerContainerFactory&lt;&gt;();<br>        factory.setConsumerFactory(consumerFactory());<br>        return factory;<br>    }<br>}</pre><p>Next, in our `<strong>KafkaProducerConfig</strong>` class, we configure our Kafka producer. The producer is responsible for sending messages to Kafka. We use the `<strong>KafkaTemplate</strong>` provided by Spring Kafka to send messages to Kafka. Here’s what the `<strong>KafkaProducerConfig</strong>` class looks like:</p><pre>@Configuration<br>public class KafkaProducerConfig {<br>    @Value(value = &quot;${kafka.bootstrapAddress}&quot;)<br>    private String bootstrapAddress;<br><br>    @Bean<br>    public ProducerFactory&lt;String, Message&gt; producerFactory() {<br>        Map&lt;String, Object&gt; configProps = new HashMap&lt;&gt;();<br>        configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress);<br>        configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);<br>        configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);<br>        return new DefaultKafkaProducerFactory&lt;&gt;(configProps);<br>    }<br><br>    @Bean<br>    public KafkaTemplate&lt;String, Message&gt; kafkaTemplate() {<br>        return new KafkaTemplate&lt;&gt;(producerFactory());<br>    }<br>}</pre><p>In the next section, we will discuss how to use WebSocket for real-time communication between the server and the clients.</p><p>In this section, we will focus on the WebSocket configuration. WebSocket provide a full-duplex communication channel over a single socket, which is ideal for real-time data transfer between the client and the server.</p><p>In our `<strong>WebSocketConfig</strong>` class, we configure our WebSocket message broker. The message broker handles messages that are sent to and from the WebSocket clients. Here’s what the `<strong>WebSocketConfig</strong>` class looks like:</p><pre>@Configuration<br>@EnableWebSocketMessageBroker<br>public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {<br><br>    @Override<br>    public void configureMessageBroker(MessageBrokerRegistry config) {<br>        config.enableSimpleBroker(&quot;/topic&quot;);<br>        config.setApplicationDestinationPrefixes(&quot;/app&quot;);<br>    }<br><br>    @Override<br>    public void registerStompEndpoints(StompEndpointRegistry registry) {<br>        registry.addEndpoint(&quot;/ws&quot;).setAllowedOrigins(&quot;http://localhost:5173/&quot;).withSockJS();<br>    }<br>}</pre><p>In this class:</p><p>- `<strong>configureMessageBroker</strong>` method configures the message broker. It enables a simple in-memory message broker and sets the prefix for messages that are bound for @MessageMapping-annotated methods.<br>- `<strong>registerStompEndpoints</strong>` method registers the “/ws” endpoint, enabling SockJS fallback options so that alternate transports can be used if WebSocket is not available.</p><p>Now that we have our WebSocket configured, we can create a `<strong>MessageController</strong>` to handle sending and receiving messages. The `<strong>MessageController</strong>` uses the `<strong>@MessageMapping</strong>` annotation to map the destination of incoming messages to specific methods.</p><p>First, let’s create Sender class:</p><pre>@Service<br>public class Sender {<br><br>    private final KafkaTemplate&lt;String, Message&gt; kafkaTemplate;<br><br>    public Sender(KafkaTemplate&lt;String, Message&gt; kafkaTemplate) {<br>        this.kafkaTemplate = kafkaTemplate;<br>    }<br><br>    public void send(String topic, Message message) {<br>        kafkaTemplate.send(topic, message);<br>    }<br>}</pre><p>And here’s what the `<strong>MessageController</strong>` class looks like:</p><pre>@Controller<br>public class MessageController {<br><br>    private final Sender sender;<br>    private final SimpMessageSendingOperations messagingTemplate;<br>    private static final Logger logger = LoggerFactory.getLogger(MessageController.class);<br><br>    public MessageController(Sender sender, SimpMessageSendingOperations messagingTemplate) {<br>        this.sender = sender;<br>        this.messagingTemplate = messagingTemplate;<br>    }<br><br>    @MessageMapping(&quot;/chat.send-message&quot;)<br>    public void sendMessage(@Payload Message chatMessage, SimpMessageHeaderAccessor headerAccessor) {<br>        chatMessage.setSessionId(headerAccessor.getSessionId());<br>        sender.send(&quot;messaging&quot;, chatMessage);<br>        logger.info(&quot;Sending message to /topic/public: &quot; + chatMessage);<br>        messagingTemplate.convertAndSend(&quot;/topic/public&quot;, chatMessage);<br>        logger.info(&quot;Message sent to /topic/public: &quot; + chatMessage);<br>    }<br><br>    @MessageMapping(&quot;/chat.add-user&quot;)<br>    @SendTo(&quot;/topic/public&quot;)<br>    public Message addUser(<br>            @Payload Message chatMessage,<br>            SimpMessageHeaderAccessor headerAccessor<br>    ) {<br>        if (headerAccessor.getSessionAttributes() != null) {<br>            headerAccessor.getSessionAttributes().put(&quot;username&quot;, chatMessage.getSender());<br>        }<br><br>        return chatMessage;<br>    }<br>}</pre><p>In this class:</p><p>- `<strong>sendMessage</strong>` method is mapped to handle messages sent to the “/chat.send-message” destination. It sends the received `Message` to the “/topic/public” destination, broadcasting it to all connected WebSocket clients.</p><p>In the next section of our article, we will discuss how to handle WebSocket events and how to consume messages from Kafka.</p><p>In the final section of our article, we will discuss how to handle WebSocket events and how to consume messages from Kafka.</p><p>Handling WebSocket events is crucial for maintaining the state of our application. For instance, when a user connects or disconnects, we might want to broadcast a message to all other users to notify them of this event. In Spring, we can handle these events by creating an event listener class.</p><p>In our `<strong>WebSocketEventListener</strong>` class, we have methods that are annotated with `<strong>@EventListener</strong>`. These methods are automatically called when the corresponding event occurs. Here’s what the `<strong>WebSocketEventListener</strong>` class looks like:</p><pre>@Component<br>public class WebSocketEventListener {<br><br>    private static final Logger logger = LoggerFactory.getLogger(WebSocketEventListener.class);<br>    private final SimpMessageSendingOperations messagingTemplate;<br><br>    public WebSocketEventListener(SimpMessageSendingOperations messagingTemplate) {<br>        this.messagingTemplate = messagingTemplate;<br>    }<br><br>    @EventListener<br>    public void handleWebSocketConnectListener(SessionConnectedEvent event) {<br>        logger.info(&quot;Received a new web socket connection&quot;);<br>    }<br><br>    @EventListener<br>    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {<br>        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());<br>        String username = (String) headerAccessor.getSessionAttributes().get(&quot;username&quot;);<br><br>        if (username != null) {<br>            logger.info(&quot;User Disconnected: &quot; + username);<br>            Message chatMessage = new Message();<br>            chatMessage.setType(MessageType.DISCONNECT);<br>            chatMessage.setSender(username);<br>            messagingTemplate.convertAndSend(&quot;/topic/public&quot;, chatMessage);<br>        }<br>    }<br>}</pre><p>In this class:</p><p>- `<strong>handleWebSocketConnectListener</strong>` method is called when a new WebSocket connection is established.<br>- `<strong>handleWebSocketDisconnectListener</strong>` method is called when a WebSocket connection is closed. It sends a ‘<strong>DISCONNECT</strong>’ message to all other connected WebSocket clients.</p><p>Finally, we need to consume the messages from Kafka. In our `Receiver` class, we have a method that is annotated with `<strong>@KafkaListener</strong>`. This method is automatically called when a message is received from the Kafka topic. Here’s what the `<strong>Receiver</strong>` class looks like:</p><pre>@Service<br>public class Receiver {<br><br>    private static final Logger logger = LoggerFactory.getLogger(Receiver.class);<br>    private final SimpMessageSendingOperations messagingTemplate;<br>    private final SimpUserRegistry userRegistry;<br><br>    public Receiver(SimpMessageSendingOperations messagingTemplate, SimpUserRegistry userRegistry) {<br>        this.messagingTemplate = messagingTemplate;<br>        this.userRegistry = userRegistry;<br>    }<br><br>    @KafkaListener(topics = &quot;messaging&quot;, groupId = &quot;chat&quot;)<br>    public void consume(Message chatMessage) {<br>        logger.info(&quot;Received message from Kafka: &quot; + chatMessage);<br>        for (SimpUser user : userRegistry.getUsers()) {<br>            for (SimpSession session : user.getSessions()) {<br>                if (!session.getId().equals(chatMessage.getSessionId())) {<br>                    messagingTemplate.convertAndSendToUser(session.getId(), &quot;/topic/public&quot;, chatMessage);<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>In this class, the `consume` method is called when a message is received from the “messaging” Kafka topic. It sends the received `Message` to the “/topic/public” WebSocket topic, broadcasting it to all connected WebSocket clients.</p><h3>Frontend: Real-Time Messaging with React and STOMP over WebSocket</h3><p>In this section, we’ll create a frontend application using React to interact with our backend service. We’ll use the <strong>@stomp/stompjs</strong> library to establish a <strong>STOMP</strong> protocol over <strong>WebSocket</strong> connection.</p><p>First, let’s create the project. For this project I’m using WebStorm IDE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*n9Qhz5YGN89U2xLStoS0nw.png" /></figure><p>Next, we’ll install the necessary libraries:</p><pre>npm install @stomp/stompjs sockjs-client @mui/material react-avatar</pre><p>Here, <strong>@stomp/stompjs</strong> is used for the STOMP client, sockjs-client is used for the WebSocket connection, <strong>@mui/material</strong> is used for the UI components, and react-avatar is used to display user avatars.</p><h4>Creating the Username Page</h4><p>In `<strong>UsernamePage.jsx`</strong>, we would typically create a form that allows users to enter their username. Once the username is submitted, it can be stored in a state and passed to the `<strong>ChatPage`</strong> component as a prop. This username will then be used as the sender of the messages.</p><pre>import { useState } from &#39;react&#39;;<br>import { Button, TextField, Container, Box } from &#39;@mui/material&#39;;<br>import PropTypes from &#39;prop-types&#39;;<br><br>function UsernamePage({ setUsername }) {<br>  UsernamePage.propTypes = {<br>    setUsername: PropTypes.func.isRequired,<br>  };<br><br>  const [inputUsername, setInputUsername] = useState(&#39;&#39;);<br><br>  const handleUsernameSubmit = (event) =&gt; {<br>    event.preventDefault();<br>    if (inputUsername) {<br>      setUsername(inputUsername);<br>    }<br>  };<br><br>  return (<br>    &lt;Container&gt;<br>      &lt;Box display=&quot;flex&quot; flexDirection=&quot;column&quot; justifyContent=&quot;center&quot; alignItems=&quot;center&quot; mt={2}&gt;<br>        &lt;h1&gt;Type your username&lt;/h1&gt;<br>        &lt;form onSubmit={handleUsernameSubmit}&gt;<br>          &lt;Box display=&quot;flex&quot; alignItems=&quot;stretch&quot;&gt;<br>            &lt;TextField<br>              sx={{<br>                color: &#39;white&#39;, &#39;&amp; .MuiOutlinedInput-notchedOutline&#39;: { borderColor: &#39;gray&#39; },<br>                width: &#39;300px&#39;,<br>                &#39;&amp; .MuiOutlinedInput-root&#39;: {<br>                  borderRadius: &#39;36px&#39;,<br>                  &#39;&amp; fieldset&#39;: {<br>                    borderColor: &#39;gray&#39;,<br>                  },<br>                  &#39;&amp; input&#39;: {<br>                    height: &#39;8px&#39;,<br>                  },<br>                },<br>              }}<br>              inputProps={{ style: { color: &#39;white&#39; } }}<br>              variant=&quot;outlined&quot;<br>              placeholder=&quot;Username&quot;<br>              value={inputUsername}<br>              onChange={(e) =&gt; setInputUsername(e.target.value)}<br>            /&gt;<br>            &lt;Box marginLeft={2}&gt;<br>              &lt;Button<br>                variant=&quot;contained&quot;<br>                sx={{<br>                  width: &#39;94px&#39;,<br>                  height: &#39;42px&#39;,<br>                  borderRadius: &#39;36px&#39;,<br>                }}<br>                color=&quot;primary&quot;<br>                type=&quot;submit&quot;&gt;<br>                Enter<br>              &lt;/Button&gt;<br>            &lt;/Box&gt;<br>          &lt;/Box&gt;<br>        &lt;/form&gt;<br>      &lt;/Box&gt;<br>    &lt;/Container&gt;<br>  );<br>}<br><br>export default UsernamePage;</pre><p>In this code, UsernamePage takes a setUsername prop, which is a function to update the username in the parent component (App.jsx). It contains a form with a text field for the username and a submit button. When the form is submitted, it calls the `<strong>setUsername`</strong> function with the entered username.</p><p>In `<strong>App.jsx`</strong>, we would typically maintain the username state and conditionally render either the `<strong>UsernamePage`</strong> or the `<strong>ChatPage`</strong> based on whether a username has been set.</p><pre>import { useState } from &#39;react&#39;;<br>import UsernamePage from &#39;./component/UsernamePage.jsx&#39;;<br>import ChatPage from &#39;./component/ChatPage.jsx&#39;;<br><br>function App() {<br>  const [username, setUsername] = useState(null);<br><br>  return (<br>    &lt;div&gt;<br>      {username ? &lt;ChatPage username={username} /&gt; : &lt;UsernamePage setUsername={setUsername} /&gt;}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>In this code, App maintains a username state. If username is null, it renders `<strong>UsernamePage`</strong> and passes the `<strong>setUsername`</strong> function as a prop. If username is not null, it renders `<strong>ChatPage`</strong> and passes username as a prop.</p><h4>Creating the Chat Page</h4><p>In the `<strong>ChatPage.jsx`</strong> file, we’ll create a `<strong>ChatPage`</strong> component. This component will handle the WebSocket connection, send and receive messages, and render the chat interface.</p><pre>import { useState, useEffect, useRef } from &#39;react&#39;;<br>import { Client } from &#39;@stomp/stompjs&#39;;<br>import SockJS from &#39;sockjs-client/dist/sockjs&#39;;<br>import ChatMessage from &quot;./ChatMessage.jsx&quot;;<br>import { Button, TextField, Container, Box } from &#39;@mui/material&#39;;<br><br>function ChatPage({ username }) {<br>  const [messages, setMessages] = useState([]);<br>  const [client, setClient] = useState(null);<br>  const messageInputRef = useRef();<br><br>  useEffect(() =&gt; {<br>    const newClient = new Client({<br>      webSocketFactory: () =&gt; new SockJS(&#39;http://localhost:8080/ws&#39;),<br>      onConnect: () =&gt; {<br>        const joinMessage = {<br>          sender: username,<br>          type: &#39;CONNECT&#39;,<br>        };<br>        newClient.publish({ destination: &#39;/app/chat.addUser&#39;, body: JSON.stringify(joinMessage) });<br>        newClient.subscribe(&#39;/topic/public&#39;, message =&gt; {<br>          const newMessage = JSON.parse(message.body);<br>          setMessages(prevMessages =&gt; [...prevMessages, newMessage]);<br>        });<br>      },<br>      onDisconnect: () =&gt; {<br>        if (newClient.connected) {<br>          const leaveMessage = {<br>            sender: username,<br>            type: &#39;DISCONNECT&#39;,<br>          };<br>          newClient.publish({ destination: &#39;/app/chat.addUser&#39;, body: JSON.stringify(leaveMessage) });<br>        }<br>      },<br>    });<br><br>    newClient.activate();<br>    setClient(newClient);<br><br>    return () =&gt; {<br>      newClient.deactivate();<br>    };<br>  }, [username]);<br><br>  const sendMessage = () =&gt; {<br>    if (messageInputRef.current.value &amp;&amp; client) {<br>      const chatMessage = {<br>        sender: username,<br>        content: messageInputRef.current.value,<br>        type: &#39;CHAT&#39;,<br>      };<br>      client.publish({ destination: &#39;/app/chat.sendMessage&#39;, body: JSON.stringify(chatMessage) });<br>      messageInputRef.current.value = &#39;&#39;;<br>    }<br>  };<br><br>  return (<br>    &lt;Container&gt;<br>      &lt;Box&gt;<br>        {messages.map((message, index) =&gt; (<br>          &lt;ChatMessage key={index} message={message} username={username} /&gt;<br>        ))}<br>      &lt;/Box&gt;<br>      &lt;form onSubmit={sendMessage}&gt;<br>        &lt;TextField inputRef={messageInputRef} placeholder=&quot;Type a message...&quot; /&gt;<br>        &lt;Button type=&quot;submit&quot;&gt;Send&lt;/Button&gt;<br>      &lt;/form&gt;<br>    &lt;/Container&gt;<br>  );<br>}<br><br>export default ChatPage;</pre><p>In this code, we’re using the useState and useEffect hooks from React to manage the state and side effects of the component. We’re using the Client class from <strong>@stomp/stompjs</strong> to create a <strong>STOMP</strong> client over a WebSocket connection. We’re using the publish method to send messages to the server and the subscribe method to receive messages from the server.</p><h4>Creating the Chat Message Component</h4><p>In the `<strong>ChatMessage.jsx</strong>` file, we’ll create a <strong>ChatMessage</strong> component. This component will display a single chat message.</p><pre>import Avatar from &#39;react-avatar&#39;;<br>import { Box } from &#39;@mui/material&#39;;<br><br>function ChatMessage({ message, username }) {<br>  return (<br>    &lt;Box sx={{ display: &#39;flex&#39;, flexDirection: &#39;column&#39;, alignItems: message.sender === username ? &#39;flex-end&#39; : &#39;flex-start&#39;, margin: &#39;10px 0&#39; }}&gt;<br>      &lt;Box sx={{ display: &#39;flex&#39;, flexDirection: message.sender === username ? &#39;row-reverse&#39; : &#39;row&#39;, alignItems: &#39;center&#39;, gap: 1 }}&gt;<br>        &lt;Avatar name={message.sender} size=&quot;35&quot; round={true} /&gt;<br>        &lt;h4&gt;{message.sender}&lt;/h4&gt;<br>      &lt;/Box&gt;<br>      &lt;Box sx={{<br>        backgroundColor: message.sender === username ? &#39;primary.main&#39; : &#39;secondary.main&#39;,<br>        color: &#39;white&#39;,<br>        borderRadius: &#39;12px&#39;,<br>        padding: &#39;10px&#39;,<br>        maxWidth: &#39;80%&#39;,<br>      }}&gt;<br>        &lt;p&gt;{message.content}&lt;/p&gt;<br>      &lt;/Box&gt;<br>    &lt;/Box&gt;<br>  );<br>}<br><br>export default ChatMessage;</pre><p>In this code, we’re using the Box component from <strong>@mui/material</strong> to create a flexible layout, and the Avatar component from react-avatar to display the user avatar. We’re using the <strong>sx</strong> prop to apply styles to the components.</p><p>In this section, we’ve created a frontend application using React that interacts with our backend service over a WebSocket connection. We’ve used the <strong>@stomp/stompjs</strong> library to establish a <strong>STOMP</strong> protocol over WebSocket connection, and the <strong>@mui/material</strong> library to create the UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*mUspnAzb9g2VWtt1_l9-tw.png" /></figure><p>Let’s also try it out with the command line by creating the `<strong>CommandController</strong>` class:</p><pre>@RestController<br>public class CommandController {<br><br>    private final KafkaTemplate&lt;String, Message&gt; kafkaTemplate;<br>    private final SimpMessageSendingOperations messagingTemplate;<br><br>    public CommandController(KafkaTemplate&lt;String, Message&gt; kafkaTemplate, SimpMessageSendingOperations messagingTemplate) {<br>        this.kafkaTemplate = kafkaTemplate;<br>        this.messagingTemplate = messagingTemplate;<br>    }<br><br>    @PostMapping(&quot;/send&quot;)<br>    public void send(@RequestBody Message message) {<br>        kafkaTemplate.send(&quot;messaging&quot;, message);<br>        messagingTemplate.convertAndSend(&quot;/topic/public&quot;, message);<br>    }<br>}</pre><p>After that, by executing these command in the terminal:</p><pre>curl -X POST -H &quot;Content-Type: application/json&quot; -d &quot;{\&quot;type\&quot;:\&quot;CONNECT\&quot;,\&quot;content\&quot;:\&quot;Hello, World!\&quot;,\&quot;sender\&quot;:\&quot;Command Line\&quot;}&quot; http://localhost:8080/send<br><br>curl -X POST -H &quot;Content-Type: application/json&quot; -d &quot;{\&quot;type\&quot;:\&quot;CHAT\&quot;,\&quot;content\&quot;:\&quot;Hello, World!\&quot;,\&quot;sender\&quot;:\&quot;Command Line\&quot;}&quot; http://localhost:8080/send</pre><p>We will also be able to see like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*TdIjtbn5RaoI4BIL7paTvg.png" /></figure><p>By combining <strong>Spring Boot</strong>, <strong>Kafka</strong>, and <strong>WebSocket</strong>, we have built a real-time chat application that is scalable and efficient. We hope this article has provided you with a solid understanding of how these technologies can be used together to build real-time applications. Happy coding!</p><p>GitHub repositories:</p><p><a href="https://github.com/mumaralfajar/messaging-app">server-side</a></p><p><a href="https://github.com/mumaralfajar/messaging-app-client">client-side</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6169f5995fe1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time Data Transfer Using Socket.io]]></title>
            <link>https://umar-fajar14.medium.com/real-time-data-transfer-using-socket-io-5210981bfe5e?source=rss-3e59dd4ecc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5210981bfe5e</guid>
            <dc:creator><![CDATA[Muhammad Umar Al Fajar]]></dc:creator>
            <pubDate>Fri, 08 Dec 2023 09:50:38 GMT</pubDate>
            <atom:updated>2023-12-08T09:50:38.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KNNH4ZmIFSJZ98-M5X49hw.png" /></figure><p>Hello, on this occasion I want to share my learning journey of transfer data in real-time using Socket.io by building a Real-time Chat app. First, I want to explain a few things like why we need a real-time application, what is WebSocket, and why using Socket.io. In this article, the main focus is how to implement Socket.io and not to build the Chat App. But don’t worry, I’ll provide the link of the project repository. So, let&#39;s get started.</p><h4>Why Real-time?</h4><p>Real-time communication is a must-have for business because it enables faster, smoother, and more effective collaboration and communication among employees, customers, and partners. Real-time communication can improve the productivity, efficiency, and satisfaction of the business by providing the following benefits:</p><ul><li>Seamless communication</li><li>Optimized business operations</li><li>Higher productivity and efficiency</li><li>Improved participation and knowledge sharing</li><li>Competitive advantage and innovation</li></ul><p>But the question is, how to make it happen? the answer is:</p><h4>WebSocket</h4><p>WebSocket is a computer communications protocol that allows simultaneous two-way communication between a client and a server over a single TCP connection. WebSocket is different from the HTTP protocol, which is usually used for webpages, because it enables the server to send data to the client without waiting for a request and allows messages to be passed back and forth while keeping the connection open. <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket">This makes WebSocket suitable for real-time data transfer, such as chat applications, online games, or live streaming</a>.</p><p>Socket.IO is a JavaScript library that I chose for building a real-time chat app using React, Context API, and Node.js. <a href="https://socket.io/">Socket.IO is based on WebSocket, but it provides additional features and benefits, such as:</a></p><ul><li>HTTP long-polling fallback: Socket.IO can automatically switch to HTTP long-polling in case the WebSocket connection is not possible or blocked by some network or browser limitations. <a href="https://socket.io/docs/v4">This ensures reliability and compatibility for the chat app</a>.</li><li>Reconnection and buffering: Socket.IO can handle connection loss and reconnection, and also buffer the messages that are sent while offline until the connection is restored. <a href="https://socket.io/docs/v4">This improves the user experience and prevents data loss for the chat app</a>.</li><li>Multiplexing and namespaces: Socket.IO can create multiple logical connections over a single physical connection, and also group them into namespaces for easier management and broadcasting. <a href="https://socket.io/docs/v4">This allows the chat app to have different rooms or topics for the users to join and communicate</a>.</li><li>Custom events and binary support: Socket.IO can emit and listen to custom events with any data type, including binary data such as images or videos. <a href="https://socket.io/docs/v4">This enables the chat app to have rich and interactive features for the users</a>.</li></ul><h4>Setting Up Socket.IO in the Project</h4><p>First, create a socket directory in your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*gQN_6DzbEHecg-9FNlm_ww.png" /></figure><p>change directory to socket, and then do:</p><pre>npm init --yes<br><br>npm install socket.io</pre><p>After that, create the index.js file:</p><pre>import { Server } from &quot;socket.io&quot;;<br><br>const io = new Server({<br>  cors: {<br>    origin: &quot;http://localhost:5173&quot;, //your client url<br>  },<br>});<br><br>let onlineUsers = [];<br><br>io.on(&quot;connection&quot;, (socket) =&gt; {<br>  // add user<br><br>  socket.on(&quot;addNewUser&quot;, (userId) =&gt; {<br>    !onlineUsers.some((user) =&gt; user.userId === userId) &amp;&amp;<br>      onlineUsers.push({<br>        userId,<br>        socketId: socket.id,<br>      });<br><br>    console.log(&quot;Connected Users:&quot;, onlineUsers);<br><br>    // send active users<br>    io.emit(&quot;getUsers&quot;, onlineUsers);<br>  });<br><br>  // add message<br>  socket.on(&quot;sendMessage&quot;, (message) =&gt; {<br>    const user = onlineUsers.find(<br>      (user) =&gt; user.userId === message.recipientId<br>    );<br><br>    if (user) {<br>      console.log(&quot;sending message and notification&quot;);<br>      io.to(user.socketId).emit(&quot;getMessage&quot;, message);<br>      io.to(user.socketId).emit(&quot;getNotification&quot;, {<br>        senderId: message.senderId,<br>        isRead: false,<br>        date: new Date(),<br>      });<br>    }<br>  });<br><br>  socket.on(&quot;disconnect&quot;, () =&gt; {<br>    onlineUsers = onlineUsers.filter((user) =&gt; user.socketId !== socket.id);<br>    console.log(&quot;User Disconnected:&quot;, onlineUsers);<br><br>    // send active users<br>    io.emit(&quot;getUsers&quot;, onlineUsers);<br>  });<br>});<br><br>io.listen(3000);</pre><h4>Set Up the Client</h4><p>in client directory, do:</p><pre>npm install socket.io-client</pre><p>then, modify the chat context start by importing the Socket.IO for client:</p><pre>import { io } from &quot;socket.io-client&quot;;</pre><p>initialize the Socket.IO:</p><pre>const [socket, setSocket] = useState(null);<br><br>useEffect(() =&gt; {<br>    const newSocket = io(&quot;http://localhost:3000&quot;); //your socket url<br>    setSocket(newSocket);<br><br>    return () =&gt; {<br>      newSocket.disconnect();<br>    };<br>  }, [user]);</pre><p>handle the real-time functionality:</p><pre>// send message<br>  useEffect(() =&gt; {<br>    if (socket === null) return;<br><br>    const recipientId = currentChat?.members.find((id) =&gt; id !== user?._id);<br><br>    socket.emit(&quot;sendMessage&quot;, { ...newMessage, recipientId });<br>  }, [newMessage]);<br><br>  // receive message and notifications<br>  useEffect(() =&gt; {<br>    if (socket === null) return;<br><br>    socket.on(&quot;getMessage&quot;, (res) =&gt; {<br>      if (currentChat?._id !== res.chatId) return;<br><br>      setMessages((prev) =&gt; [...prev, res]);<br>    });<br><br>    socket.on(&quot;getNotification&quot;, (res) =&gt; {<br>      const isChatOpen = currentChat?.members.some((Id) =&gt; Id === res.senderId);<br><br>      if (isChatOpen) {<br>        setNotifications((prev) =&gt; [{ ...res, isRead: true }, ...prev]);<br>      } else {<br>        setNotifications((prev) =&gt; [res, ...prev]);<br>      }<br>    });<br><br>    return () =&gt; {<br>      socket.off(&quot;getMessage&quot;);<br>      socket.off(&quot;getNotification&quot;);<br>    };<br>  }, [socket, currentChat]);</pre><p>That way, we can now send and receive message in real-time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YJ31I753ZFVlFR-wB7OkzQ.gif" /></figure><p>Here’s the <a href="https://github.com/mumaralfajar/chat-app">source code</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5210981bfe5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integration Jenkins — Telegram Bot]]></title>
            <link>https://umar-fajar14.medium.com/integration-jenkins-telegram-bot-23181a83a2fb?source=rss-3e59dd4ecc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/23181a83a2fb</guid>
            <dc:creator><![CDATA[Muhammad Umar Al Fajar]]></dc:creator>
            <pubDate>Fri, 01 Dec 2023 09:59:48 GMT</pubDate>
            <atom:updated>2023-12-01T10:08:24.384Z</atom:updated>
            <content:encoded><![CDATA[<h3>Integration Jenkins — Telegram Bot</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BlIJYn8fznWfizdy.png" /></figure><p>Hello, on this occasion I wanna share how to integrate Jenkins and Telegram Bot to send notification. Without wasting more time, let’s get straight to the point. (I used this <a href="https://umar-fajar14.medium.com/implementing-continuous-integration-continuous-deployment-with-jenkins-and-sonarqube-d0fac87a42c6">project</a>)</p><h4>Create The Bot</h4><p>First, go to telegram and search for <em>botfather.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XSbhUAnPLBG_Ox90LFSFJg.png" /></figure><p>Enter then enter the commands:</p><pre>/start<br><br>/newbot</pre><p>And then you will be asked to give it a name and username.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s-ru6hNYqDsmatohDBdeWg.png" /></figure><p>After that, back to botfather to disable the privacy mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*TzUh98AmJm3K3V7I9NouLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*n_GZ1r-iWjAKuW-cMD9cUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*hAoVnijgnH9pkXpTE8PMvg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*48S7tKFmulfq7DJroAufzw.png" /></figure><p>After all those, go search your bot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*jj94ySNhZekHv2gOuN07yw.png" /></figure><p>Choose yours, and then click the START button, it will send a /start command to your bot.</p><p>Now you can use:</p><pre>https://api.telegram.org/bot&lt;YOUR:BOT_TOKEN&gt;/getUpdates</pre><p>To get the chat id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*7ov42LZo5HzvQvENAraFuQ.png" /></figure><h4>Manage Jenkins</h4><p>Now, go to Jenkins and choose Manage Jenkins menu on the left navigation.</p><p>Go to Credentials — System — Global credentials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*RwJSPCcic15oWlELzPSRIw.png" /></figure><p>Add secret text credentials for the telegram bot token and chat id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*UOzOsnIq8NBDgN98TEf9-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*hkGJwgoW10A7ey-oppEgwg.png" /></figure><p>After that, back to our project’s Jenkinsfile to add post action.</p><pre>pipeline {<br>    agent any<br>    tools {<br>        maven &#39;jenkins-maven&#39;<br>    }<br>    environment {<br>        BUILD_NUMBER_ENV = &quot;${env.BUILD_NUMBER}&quot;<br>        TEXT_SUCCESS_BUILD = &quot;[#${env.BUILD_NUMBER}] Project: ${JOB_NAME} build Success&quot;<br>        TEXT_FAILURE_BUILD = &quot;[#${env.BUILD_NUMBER}] Project: ${JOB_NAME} build Failure&quot;<br>    }<br>    <br>    stages {<br>        stage(&#39;SonarQube Analysis&#39;) {<br>            steps {<br>                withSonarQubeEnv(&#39;SonarQube&#39;) {<br>                    sh &#39;mvn clean install&#39;<br>                    sh &#39;mvn clean package verify sonar:sonar&#39;<br>                    echo &#39;SonarQube Analysis Completed&#39;<br>                }<br>            }<br>        }<br>        stage(&quot;Quality Gate&quot;) {<br>            steps {<br>                waitForQualityGate abortPipeline: true<br>                echo &#39;Quality Gate Completed&#39;<br>            }<br>        }<br>    }<br><br>    post {<br>        success {<br>            script{<br>                 withCredentials([string(credentialsId: &#39;tele-token&#39;, variable: &#39;TOKEN&#39;), string(credentialsId: &#39;tele-chat-id&#39;, variable: &#39;CHAT_ID&#39;)]) {<br>                    sh &#39; curl -s -X POST https://api.telegram.org/bot&quot;$TOKEN&quot;/sendMessage -d chat_id=&quot;$CHAT_ID&quot; -d text=&quot;$TEXT_SUCCESS_BUILD&quot; &#39;<br>                 }<br>            }<br>        }<br>        failure {<br>            script{<br>                withCredentials([string(credentialsId: &#39;tele-token&#39;, variable: &#39;TOKEN&#39;), string(credentialsId: &#39;tele-chat-id&#39;, variable: &#39;CHAT_ID&#39;)]) {<br>                    sh &#39; curl -s -X POST https://api.telegram.org/bot&quot;$TOKEN&quot;/sendMessage -d chat_id=&quot;$CHAT_ID&quot; -d text=&quot;$TEXT_FAILURE_BUILD&quot; &#39;<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Finally, build the job in Jenkins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*QCD1ruEXzDfd4c8r9QlhdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*ZKhCQTlmonHh3cICqupgiA.png" /></figure><p>That’s all guys, have a good day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23181a83a2fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Continuous Integration/Continuous Deployment with Jenkins and SonarQube]]></title>
            <link>https://umar-fajar14.medium.com/implementing-continuous-integration-continuous-deployment-with-jenkins-and-sonarqube-d0fac87a42c6?source=rss-3e59dd4ecc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0fac87a42c6</guid>
            <dc:creator><![CDATA[Muhammad Umar Al Fajar]]></dc:creator>
            <pubDate>Mon, 27 Nov 2023 08:07:13 GMT</pubDate>
            <atom:updated>2023-11-27T08:07:13.350Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mNryA28JSgO81FSd.jpg" /></figure><p>In the world of software development, Continuous Integration/Continuous Deployment (CI/CD) has become an essential practice for teams looking to deliver high-quality code quickly and efficiently. In this article, we’ll explore how to set up a CI/CD pipeline using Jenkins and SonarQube in a project.</p><h4>Create Spring Boot Project</h4><p>For this project we only need a simple project that installed SonarQube and JaCoCo plugin and implemented unit test. You can create your own project or just simply clone mine (Don’t forget to configure the database connection in application properties):</p><p><a href="https://github.com/mumaralfajar/task-management-system">mumaralfajar/task-management-system (github.com)</a></p><p>In that project I’ve provided APIs and some unit tests using Junit.</p><h4>Create Container for SonarQube and Jenkins</h4><p>docker-compose.yaml</p><pre>version: &#39;3&#39;<br>services:<br>  sonarqube:<br>    image: sonarqube:latest<br>    ports:<br>      - 9000:9000<br>    volumes:<br>      - sonarqube_data:/opt/sonarqube/data<br>      - sonarqube_extensions:/opt/sonarqube/extensions<br>      - sonarqube_logs:/opt/sonarqube/logs<br><br>  jenkins:<br>    image: jenkins/jenkins:lts<br>    ports:<br>      - 8080:8080<br>      - 50000:50000<br>    volumes:<br>      - jenkins_home:/var/jenkins_home<br><br>volumes:<br>  sonarqube_data:<br>  sonarqube_extensions:<br>  sonarqube_logs:<br>  jenkins_home:</pre><p>After the container is running, access the SonarQube through browser (<a href="http://localhost:9000/"><strong>http://localhost:9000</strong></a><strong>).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Fv9_81JL3M332MCL3p4m0g.png" /></figure><p>If the login page shows up, then it means the SonarQube runs perfectly. For the first time login with username: <strong>admin</strong> and password: <strong>admin.</strong></p><p>After that the SonarQube will tell you to change the password, remember that or keep that in somewhere safe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*DW2yltnskKJT4IoUP37iJQ.png" /></figure><p>After changing your password, you will be redirected to the main page, choose to manually create a local project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Mcs1FAiXb6pN0q6sWbjZsA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*aws3dK4jIpeu6G3YkYmhIg.png" /></figure><p>For the project setu up, just keep it simple by choosing to use the global setting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*0r7cO2sHqfhN4LpFsroJ7w.png" /></figure><p>After the project was created, choose Locally for how the project will be analyzed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H6jgFI7ULyQA1CbHl05oIw.png" /></figure><p>Name the token, and then generate the token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-RGcFD-C0js6a3RxfKNMag.png" /></figure><p>save the generated token in somewhere save.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GrSvbrNmWw6H51YF-GJDvg.png" /></figure><p>After that click Continue and then you will be given a build configuration, I choose maven since I’m using maven for the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Db_S4e6XxcLJQBAABwxwQQ.png" /></figure><p>Add it to pom.xml in &lt;properties/&gt;</p><pre>&lt;!-- SonarQube properties --&gt;<br>&lt;sonar.projectKey&gt;task-management-system&lt;/sonar.projectKey&gt;<br>&lt;sonar.projectName&gt;task-management-system&lt;/sonar.projectName&gt;<br>&lt;sonar.host.url&gt;http://localhost:9000&lt;/sonar.host.url&gt;<br>&lt;sonar.login&gt;sqp_1d331e503727c363d9e8606eb37aea1a17236d6c&lt;/sonar.login&gt;</pre><p>If it’s done, then run:</p><pre>mvn clean verify sonar:sonar</pre><p>Now go to the project overview in SonarQube to see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LYWqQCVTtZ9L8tkoa1aoBg.png" /></figure><h4>Setup Jenkins</h4><p>For the first time, you will need to enter a password. You can find it in the Jenkins container’s log.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*vMseD3vAzGgJU2WTQ_CumA.png" /></figure><p>Next, just install suggested plugins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*_mnBz3DUQqxWs29DvxxHww.png" /></figure><p>After creating the admin user, you will be redirected to dashboard. While in the dashboard, choose manage Jenkins and choose plugins.</p><p>Install the SonarQube Scanner plugin, and then just restart the Jenkins container in Docker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_vORGltOGkjLRyKNWVm7Ng.png" /></figure><p>Next, go to Manage Jenkins — System, add SonarQube installations. Then add an authentication token by clicking add and then Jenkins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tpi-bWMcT1zGc52mTiFHvw.png" /></figure><p>Choose secret text. Then enter the token in the Secret form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UV1RDM7hhwxY65G4-hOWBA.png" /></figure><p>If done, then save.</p><p>Go to Manage Jenkins — Tools. Add the Java home.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aAxZsNoTkg11m6QotCirAQ.png" /></figure><p>Don’t forget the SonarQube Scanner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xODna4L8tFij5jqjC9RZlA.png" /></figure><p>Also add the maven. Then click save.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7YvFi1lGQCoWa1BEztEe8Q.png" /></figure><p>Then go to the dashboard and click new item to create a job. Give it a name and choose Pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kV5rOI9dVcZQdauZ7XdYTg.png" /></figure><p>Next, in the General section, check the GitHub project and fill in the project URL with our GitHub project URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*02ll9kFicb1X76Os-gTaWQ.png" /></figure><p>Go to the Pipeline section and provide your Git repo URL. After that we will create new credentials by clicking Add and then Jenkins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ndUYY3QWrE68RPY3QMyHpg.png" /></figure><p>Before that, we have to add the ssh key of the Jenkins container to our GitHub. Enter the Jenkins container and generate the ssh key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GCwZnQmhVcyWDz7-o7BOrg.png" /></figure><p>Now, copy the private key with:</p><pre>cat .&lt;your/directory&gt;id_rsa</pre><p>in my case:</p><pre>cat ./var/jenkins_home/.ssh/id_rsa</pre><p>Copy from the word “begin” to “end”. Then go back to the web Jenkins, choose SSH Username with private key. For ID and Description, it is optional, but for Username, please fill in your friends’ GitHub Username. Enter the private key that you have copied earlier and enter the passphrase that you created when generating the ssh key. If done, click add.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mW6LW66MJyoFnazoYbTiVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9_Au2fjRWoqBdtTv7lbCZg.png" /></figure><p>Go to the Jenkins container and copy the public ssh key by using:</p><pre>cat .&lt;your/directory&gt;id_rsa.pub</pre><p>Or, in my case:</p><pre>cat ./var/jenkins_home/.ssh/id_rsa.pub</pre><p>Then, add it to your GitHub account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8xga17pMU6wnyvkYSnDsDw.png" /></figure><p>After that, back to Jenkins and click save.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mlIlw8648Hf6FU-pES2_-Q.png" /></figure><p>Go to the Jenkins container and do this command to install maven:</p><pre>apt-get update<br>apt-get install maven</pre><p>And then, click build now in Jenkins.</p><p>Finally, go to SonarQube to see the result.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0fac87a42c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Locomotive IoT Simulation with NodeJS, Kafka, Mongo, PostgreSQL, Logging, and Telegram Notification]]></title>
            <link>https://umar-fajar14.medium.com/locomotive-iot-simulation-with-nodejs-kafka-mongo-postgresql-logging-and-telegram-notification-e8fea351168b?source=rss-3e59dd4ecc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8fea351168b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[express]]></category>
            <dc:creator><![CDATA[Muhammad Umar Al Fajar]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 01:44:22 GMT</pubDate>
            <atom:updated>2023-11-21T01:44:22.969Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NGIccDJDjcaPWMrBFXrqJA.png" /></figure><p>Hello everyone. My name is Umar, and I am currently a software developer at PT. Padepokan 79. On this occasion, I will share how locomotive IoT simulation was made with Spring Scheduler which also implementing message broker and Telegram notification.</p><p>For this project, we need several tools such as:</p><ul><li><a href="https://nodejs.org/en">NodeJS</a></li><li><a href="https://www.postgresql.org/download/">PostgreSQL</a></li><li><a href="https://docs.docker.com/get-docker/">Docker</a></li></ul><p>I assume that you have installed all the necessary tools (if not, then you can look up to the link I provided above). After that, let’s proceed to the next step.</p><h4><strong>Environment Preparation</strong></h4><p>First of all, we need to create a container for Kafka:</p><pre>version: &quot;3.8&quot;<br>services:<br>  zookeeper:<br>    container_name: zookeeper<br>    restart: always<br>    image: bitnami/zookeeper<br>    ports:<br>      - &quot;2181:2181&quot;<br>    environment:<br>      - ALLOW_ANONYMOUS_LOGIN=yes<br>  kafka:<br>    container_name: kafka<br>    restart: always<br>    image: bitnami/kafka<br>    ports:<br>      - &quot;9094:9094&quot;<br>    environment:<br>      KAFKA_CFG_NODE_ID: 0<br>      KAFKA_CFG_PROCESS_ROLES: controller,broker<br>      KAFKA_CFG_CONTROLLER_QUORUM_VOTERS: 0@localhost:9093<br>      KAFKA_CFG_LISTENERS: PLAINTEXT://:9092,CONTROLLER://:9093,EXTERNAL://:9094<br>      KAFKA_CFG_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,EXTERNAL://localhost:9094<br>      KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,EXTERNAL:PLAINTEXT,PLAINTEXT:PLAINTEXT<br>      KAFKA_CFG_CONTROLLER_LISTENER_NAMES: CONTROLLER<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br>    depends_on:<br>      - zookeeper<br>  kafdrop:<br>    container_name: kafdrop<br>    image: obsidiandynamics/kafdrop<br>    ports:<br>      - &quot;9000:9000&quot;<br>    environment:<br>      KAFKA_BROKERCONNECT: kafka:9092<br>    depends_on:<br>      - kafka</pre><p>As we can see there are 3 containers, first is Zookeeper, Kafka, and Kafdrop.</p><p>Zookeeper is necessary for Kafka because it performs several important functions, such as <strong>controller election, cluster membership, topic configuration, quotas, and consumer offsets. </strong>For the details, we can refer to the following sources:<br><em>1. </em><a href="https://www.cloudkarafka.com/blog/cloudkarafka-what-is-zookeeper.html"><em>cloudkafka</em></a><br><em>2. </em><a href="https://stackoverflow.com/questions/23751708/is-zookeeper-a-must-for-kafka"><em>stackoverflow</em></a><br><em>3. </em><a href="https://www.scaler.com/topics/kafka-tutorial/the-role-of-zookeeper-in-the-kafka-cluster/"><em>scaler</em></a></p><p>As for the <a href="https://github.com/obsidiandynamics/kafdrop"><strong>Kafdrop</strong>,</a> it can help you monitor and manage your Kafka cluster, as well as debug and test your applications that use Kafka as a data source.</p><p><strong>MongoDB</strong></p><p>Next, create container for MongoDB:</p><pre>docker container create --name mongodb --publish 27017:27017 mongo</pre><p>After running the container, run the following command:</p><pre>docker exec -it mongodb bash</pre><p>That command allows you to run command in a running container. Then enter the MongoDB:</p><pre>mongosh</pre><p>After that, create the database and the collection:</p><pre>use locomotivedb<br><br>db.createCollection(&quot;locomotive&quot;)</pre><p><strong>PostgreSQL</strong></p><p>For PostgreSQL I&#39;ve already installed it on my machine. I used <a href="https://www.pgadmin.org/download/">pgAdmin</a> as the graphical management tool for PostgreSQL.</p><p>Create database named <strong>locomotive.</strong></p><p>Then, create a table to store the locomotive summary:</p><pre>CREATE TABLE locomotive_summary (<br>  id uuid not null,<br>  total_locomotive int4 not null,<br>  total_locomotive_poor int4 not null,<br>  total_locomotive_good int4 not null,<br>  total_locomotive_excellent int4 not null,<br>  last_modified_time timestamp null,<br>  constraint pk_locomotive_summary primary key (id)<br>);</pre><p>Next, we can start to create the scheduler App.</p><h4>Creating The Scheduler</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*wiHAOUl8XsNVoMk67Ger-A.png" /></figure><p>For the creation of Scheduler project, I used IntelliJ IDEA, or you can use <a href="http://start.spring.io/">start.spring.io</a> to generate the Java Spring Boot project.</p><p>As for the dependencies, we need Lombok and WebFlux.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*3vo7L36yFgoL5AP1Nq4MLQ.png" /></figure><p>First, we will create the required bean. Here, I create a WebClient bean that will be used to call the NodeJS application’s API:</p><pre>@Configuration<br>public class UtilObjects {<br><br>    @Bean<br>    WebClient webClient() {<br>        return WebClient.builder().baseUrl(&quot;http://localhost:3050/v1/&quot;).build();<br>    }<br>}</pre><p>Next, create the model:</p><pre>@Data<br>@Builder<br>public class Locomotive {<br>    private String code;<br>    private String name;<br>    private String dimension;<br>    private String status;<br>    private String time;<br>}</pre><p>Then, we create the scheduler:</p><pre>@Component<br>public class LocomotiveScheduler {<br><br>    @Autowired<br>    private WebClient webClient;<br><br>    @Scheduled(fixedDelay = 10000)<br>    public void scheduler() throws JsonProcessingException {<br>        String[] status = { &quot;Poor&quot;, &quot;Good&quot;, &quot;Excellent&quot;};<br>        Random random = new Random();<br><br>        Locomotive locomotive = Locomotive.builder()<br>                .code(UUID.randomUUID().toString().substring(0, 13))<br>                .name(&quot;Loco&quot; + UUID.randomUUID().toString().substring(0, 4))<br>                .dimension(&quot;10 x 10&quot;)<br>                .status(status[random.nextInt(status.length)])<br>                .time(LocalDateTime.now().toString())<br>                .build();<br><br>        webClient.post().uri(&quot;/forward&quot;).body(Mono.just(locomotive), Locomotive.class).retrieve().bodyToMono(Void.class).block();<br>    }<br>}</pre><p>Now configure the main class:</p><pre>@EnableScheduling<br>@SpringBootApplication(scanBasePackages = {&quot;com.main.locomotive.app&quot;, &quot;com.main.locomotive.util&quot;}) //adjust to your project<br>public class LocomotiveApplication {<br><br> public static void main(String[] args) {<br>  SpringApplication.run(LocomotiveApplication.class, args);<br> }<br><br>}</pre><h4>Create NodeJS API</h4><p>First of all, create the project:</p><pre>npm init -y</pre><p>After that, install the necessary dependencies:</p><pre>npm i kafkajs mongodb</pre><p>Then, create connection to MongoDB:</p><pre>class Database {<br><br>  static connection = null;<br><br>  static getConnection() {<br>    if (!this.connection) {<br>      this.connection = new MongoClient(&quot;mongodb://localhost&quot;).db(<br>        &quot;locomotivedb&quot;<br>      );<br>    }<br>    return this.connection;<br>  }<br>}<br><br>export { Database };</pre><p>Next, create a topic before we can configure the Kafka. Make sure the containers are running, run the Kafdrop with visiting: <a href="http://localhost:9000/">http://localhost:9000.</a><br>And then create a new topic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*Rlxd81hYe9HUK4lTDleHdg.png" /></figure><p>Now, we can create a configuration for the Kafka:</p><pre>class KafkaConfig {<br>  constructor() {<br>    this.kafka = new Kafka({<br>      clientId: &quot;nodejs-kafka&quot;,<br>      brokers: [&quot;localhost:9094&quot;],<br>    });<br>    this.producer = this.kafka.producer({<br>      createPartitioner: Partitioners.LegacyPartitioner,<br>    });<br>    this.consumer = this.kafka.consumer({ groupId: &quot;a&quot; });<br>  }<br><br>  async produce(topic, messages) {<br>    try {<br>      await this.producer.connect();<br>      await this.producer.send({<br>        topic: topic,<br>        messages: messages,<br>      });<br>    } catch (error) {<br>      console.error(error);<br>    } finally {<br>      await this.producer.disconnect();<br>    }<br>  }<br><br>  async consume(topic, callback) {<br>    try {<br>      await this.consumer.connect();<br>      await this.consumer.subscribe({ topic: topic, fromBeginning: true });<br>      await this.consumer.run({<br>        eachMessage: async ({ topic, partition, message }) =&gt; {<br>          const value = message.value.toString();<br>          callback(value);<br>        },<br>      });<br>    } catch (error) {<br>      console.error(error);<br>    }<br>  }<br>}<br><br>export default KafkaConfig;</pre><p>After that, create the necessary service:</p><pre>const forward = async (req, res) =&gt; {<br>  try {<br>    const data = req.body;<br>    const kafkaConfig = new KafkaConfig();<br>    const messages = [{ value: JSON.stringify(data) }];<br>    kafkaConfig.produce(&quot;locomotive&quot;, messages);<br><br>    res.status(200).json({<br>      message: &quot;Message successfully send!&quot;,<br>    });<br>  } catch (error) {<br>    console.log(error);<br>  }<br>};<br><br>export { forward };</pre><p>Next, create the controller:</p><pre>const router = express.Router();<br><br>router.route(&quot;/forward&quot;).post(forward);<br><br>export default router;</pre><p>And then, create the server:</p><pre>const connection = Database.getConnection().collection(&quot;locomotive&quot;);<br><br>const PORT = 3050;<br>const app = express();<br><br>app.use(express.json());<br><br>app.use(&quot;/v1&quot;, forwardController);<br><br>const kafkaConfig = new KafkaConfig();<br>kafkaConfig.consume(&quot;locomotive&quot;, (value) =&gt; {<br>  const obj = JSON.parse(value);<br><br>  connection.insertOne({<br>    _id: obj.code,<br>    locoName: obj.came,<br>    locoDimension: obj.dimension,<br>    status: obj.status,<br>    time: obj.time,<br>  });<br>});<br><br>app.listen(PORT, () =&gt; console.log(`Server running on port ${PORT}`));</pre><h3>Create Scheduler Report</h3><p>First of all, generate the project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*OOQ9ckJxbhWpuLuhbGnfqg.png" /></figure><p>I used IntelliJ IDEA to generate the project (or you can visit <a href="https://start.spring.io/">start.spring.io</a>).<br>For the dependencies, we need:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/130/1*BuXU9_GeiNm69SpwJkfuew.png" /></figure><p>As for the telegram dependencies, we need to add it manually:</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.telegram&lt;/groupId&gt;<br>   &lt;artifactId&gt;telegrambots-spring-boot-starter&lt;/artifactId&gt;<br>   &lt;version&gt;6.7.0&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>   &lt;groupId&gt;org.telegram&lt;/groupId&gt;<br>   &lt;artifactId&gt;telegrambots-abilities&lt;/artifactId&gt;<br>   &lt;version&gt;6.7.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>After that, go to application.properties to configure the database:</p><pre>spring.data.mongodb.host=localhost<br>spring.data.mongodb.port=27017<br>spring.data.mongodb.database=locomotivedb<br>spring.data.mongodb.authentication-database=admin<br><br>spring.datasource.url= jdbc:postgresql://localhost:5432/locomotive<br>spring.datasource.username= postgres<br>spring.datasource.password= YOUR_PASSWORD<br><br>spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation= true<br>spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.PostgreSQLDialect<br>spring.datasource.driverClassName=org.postgresql.Driver<br><br># Hibernate ddl auto (create, create-drop, validate, update)<br>spring.jpa.hibernate.ddl-auto=update</pre><p>Now, let’s create the model for MongoDB and PostgreSQL:</p><pre>@Data<br>@Builder<br>@Document(collection = &quot;locomotive&quot;)<br>public class Locomotive {<br>    @Id<br>    private String code;<br>    private String name;<br>    private String dimension;<br>    private String status;<br>    private String time;<br>}</pre><pre>@Data<br>@NoArgsConstructor<br>@AllArgsConstructor<br>@Entity<br>@Builder<br>@Table(name = &quot;locomotive_summary&quot;)<br>@EntityListeners(AuditingEntityListener.class)<br>public class LocomotiveSummary {<br>    @Id<br>    @GeneratedValue(generator = &quot;uuid2&quot;)<br>    @GenericGenerator(name = &quot;uuid2&quot;, strategy = &quot;org.hibernate.id.UUIDGenerator&quot;)<br>    @Column(name = &quot;id&quot;)<br>    private UUID id;<br><br>    @Column(name = &quot;total_locomotive&quot;)<br>    private int totalLocomotive;<br><br>    @Column(name = &quot;total_locomotive_poor&quot;)<br>    private int totalLocomotivePoor;<br><br>    @Column(name = &quot;total_locomotive_good&quot;)<br>    private int totalLocomotiveGood;<br><br>    @Column(name = &quot;total_locomotive_excellent&quot;)<br>    private int totalLocomotiveExcellent;<br><br>    @LastModifiedDate<br>    @Column(name = &quot;last_modified_time&quot;)<br>    private LocalDateTime lastModifiedTime;<br>}</pre><p>After that, create the repositories:</p><pre>public interface LocomotiveRepository extends MongoRepository&lt;Locomotive, String&gt; {<br>    long countByStatus(String status);<br>}</pre><pre>public interface LocomotiveSummaryRepository extends JpaRepository&lt;LocomotiveSummary, UUID&gt; {<br><br>}</pre><p>Before we configure the Telegram bot, we need to create the bot first to get the token:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*a4BH-AMS5jsxlvYf05V7hw.png" /></figure><p>And then create the TelegramBot bean object:</p><pre>@Component<br>public class TelegramBot extends AbilityBot {<br><br>    public TelegramBot() {<br>        super(YOUR_BOT_TOKEN, &quot;loco_summary_bot&quot;);<br>    }<br><br>    @Override<br>    public long creatorId() {<br>        return 1L;<br>    }<br><br>    public void sendTextMessage(String chatId, String text) {<br>        SendMessage message = new SendMessage();<br>        message.setChatId(chatId);<br>        message.setText(text);<br><br>        try {<br>            execute(message);<br>        } catch (TelegramApiException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}</pre><p>After that, we need our account’s chat ID by visiting IDBot and then do some commands below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*OlnrLtN6YCc3tz2RLysxew.png" /></figure><p>Copy the ID and then create the Scheduler:</p><pre>@Component<br>@Slf4j<br>public class Schedular {<br><br>    @Autowired<br>    private LocomotiveRepository locomotiveRepository;<br><br>    @Autowired<br>    private LocomotiveSummaryRepository locomotiveSummaryRepository;<br><br>    @Autowired<br>    private TelegramBot telegramBot;<br><br>    @Scheduled(fixedDelay = 10000)<br>    public void scheduler() {<br>        locomotvefSummaryRepository.deleteAll();<br><br>        int totalLocomotive = (int) locomotiveRepository.count();<br>        int totalPoorLocomotive = (int) locomotiveRepository.countByStatus(&quot;Poor&quot;);<br>        int totalGoodLocomotive = (int) locomotiveRepository.countByStatus(&quot;Good&quot;);<br>        int totalExcellentLocomotive = (int) locomotiveRepository.countByStatus(&quot;Excellent&quot;);<br><br>        LocomotiveSummary locomotiveSummary = LocomotiveSummary.builder()<br>                .totalLocomotive(totalLocomotive)<br>                .totalLocomotivePoor(totalPoorLocomotive)<br>                .totalLocomotiveGood(totalGoodLocomotive)<br>                .totalLocomotiveExcellent(totalExcellentLocomotive)<br>                .build();<br><br>        locomotiveSummaryRepository.save(locomotiveSummary);<br><br>        log.info(&quot;Summary Update&quot;);<br>        telegramBot.sendTextMessage(YOUR_CHAT_ID,<br>                String.format(&quot;&quot;&quot;<br>                        &lt;====== Locomotive Summary ======&gt;<br><br>                        Total Locomotive = %d<br>                        Total Poor Locomotive = %d<br>                        Total Good Locomotive = %d<br>                        Total Excellent Locomotive = %d<br>                        &quot;&quot;&quot;, totalLocomotive, totalPoorLocomotive, totalGoodLocomotive,<br>                        totalExcellentLocomotive));<br>    }<br>}</pre><ul><li>The code above demonstrates how I generated a data summary from mongodb and logged it. We input the ID when we want to use the bot to send a message. After that, we have to adjust the logging to keep the log in a file (logback.xml) in the resources folder (where the application.properties file also exists):</li></ul><pre>&lt;configuration&gt;<br><br>  &lt;appender name=&quot;FILE&quot; class=&quot;ch.qos.logback.core.rolling.RollingFileAppender&quot;&gt;<br>    &lt;file&gt;application.log&lt;/file&gt;<br>    &lt;rollingPolicy class=&quot;ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy&quot;&gt;<br>      &lt;fileNamePattern&gt;application-%d{yyyy-MM-dd}.%i.log&lt;/fileNamePattern&gt;<br>      &lt;maxFileSize&gt;100MB&lt;/maxFileSize&gt;<br>      &lt;maxHistory&gt;60&lt;/maxHistory&gt;<br>      &lt;totalSizeCap&gt;20GB&lt;/totalSizeCap&gt;<br>    &lt;/rollingPolicy&gt;<br>    &lt;encoder&gt;<br>      &lt;pattern&gt;%-4relative %d{HH:mm:ss} %d{yyyy-MM-dd} [%thread] %-5level %logger{35} - %msg%n&lt;/pattern&gt;<br>    &lt;/encoder&gt;<br>  &lt;/appender&gt;<br><br>  &lt;root level=&quot;info&quot;&gt;TimeBasedRollingPolicy<br>    &lt;appender-ref ref=&quot;FILE&quot;/&gt;<br>  &lt;/root&gt;<br><br>&lt;/configuration&gt;</pre><p>I implemented a rolling file appender so that when it reaches a certain criteria, the logging application will create a new file. <br>After that, we will create an api for the web monitoring application. First, we will create the service:</p><pre>@Service<br>public class AdminService {<br><br>    @Autowired<br>    private LocomotiveSummaryRepository locomotiveSummaryRepository;<br><br>    public LocomotiveSummary getLocomotiveSummary() {<br>        return locomotiveSummaryRepository.findAll().get(0);<br>    }<br>}</pre><p>And then create the controller:</p><pre>@RestController<br>@RequestMapping(&quot;/v1/admin&quot;)<br>@CrossOrigin<br>public class AdminController {<br><br>    @Autowired<br>    private AdminService adminService;<br><br>    @GetMapping(&quot;/summary&quot;)<br>    public ResponseEntity&lt;LocomotiveSummary&gt; geLocomotiveSummary() {<br>        return ResponseEntity.ok(adminService.getLocomotiveSummary());<br>    }<br>}</pre><p>When you are done, don’t forget to create an auditing bean:</p><pre>@Configuration<br>@EnableJpaAuditing(dateTimeProviderRef = &quot;auditingDateTimeProvider&quot;)<br>public class JpaAuditingConfiguration {<br><br>    @Bean(name = &quot;auditingDateTimeProvider&quot;)<br>    DateTimeProvider dateTimeProvider() {<br>        return () -&gt; Optional.of(LocalDateTime.now());<br>    }<br>}</pre><p>The bean is used to generate the content of the property automatically when saving data if there is a property that uses annotations such as @CreatedDate, @LastModifiedDate, etc.</p><p>Now, we can start to configure the main class:</p><pre>@EnableScheduling<br>@SpringBootApplication(scanBasePackages = &quot;com.project&quot;) //adjust to your project<br>@EnableMongoRepositories(basePackages = &quot;com.project.repository.mongodb&quot;) //adjust to your project<br>@EnableJpaRepositories(basePackages = &quot;com.project.repository.postgre&quot;) //adjust to your project<br>@EntityScan(basePackages = { &quot;com.project.model&quot; }) //adjust to your projectF<br>public class ReportApplication implements ApplicationContextAware {<br>	private static ApplicationContext ctx;<br><br>	public static void main(String[] args) throws BeansException, TelegramApiException {<br>		SpringApplication.run(ReportApplication.class, args);<br><br>		TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class);<br>		botsApi.registerBot(ctx.getBean(&quot;telegramBot&quot;, AbilityBot.class));<br>	}<br><br>	@Override<br>	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {<br>		ctx = applicationContext;<br>	}<br>}</pre><p>In the code above, we performed a scan on the repository and model that we created. Then, we registered the bot that we created.</p><h4>Create Dashboard</h4><p>I used WebStorm to generate the React + Vite project for the dashboard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*4q1UWJ75GkfTUtlpCbUyYQ.png" /></figure><p>Next, install all the necessary dependencies:</p><pre>&quot;dependencies&quot;: {<br>  &quot;@emotion/react&quot;: &quot;^11.11.1&quot;,<br>  &quot;@emotion/styled&quot;: &quot;^11.11.0&quot;,<br>  &quot;@fontsource/inter&quot;: &quot;^5.0.15&quot;,<br>  &quot;@fontsource/poppins&quot;: &quot;^5.0.8&quot;,<br>  &quot;@fontsource/roboto&quot;: &quot;^5.0.8&quot;,<br>  &quot;@mui/icons-material&quot;: &quot;^5.14.16&quot;,<br>  &quot;@mui/material&quot;: &quot;^5.14.17&quot;,<br>  &quot;@reduxjs/toolkit&quot;: &quot;^1.9.7&quot;,<br>  &quot;react&quot;: &quot;^18.2.0&quot;,<br>  &quot;react-dom&quot;: &quot;^18.2.0&quot;,<br>  &quot;react-google-charts&quot;: &quot;^4.0.1&quot;,<br>  &quot;react-redux&quot;: &quot;^8.1.3&quot;,<br>  &quot;react-router-dom&quot;: &quot;^6.18.0&quot;<br>},</pre><p>After that, configure the Redux:</p><pre>const baseQuery = fetchBaseQuery({<br>  baseUrl: &quot;http://localhost:8080/v1&quot;,<br>});<br><br>export const apiSlice = createApi({<br>  baseQuery,<br>  tagTypes: [],<br>  endpoints: (builder) =&gt; ({}),<br>  onError: () =&gt; {},<br>});</pre><p>Next, create the endpoint:</p><pre>export const adminApiSlice = apiSlice.injectEndpoints({<br>  endpoints: (builder) =&gt; ({<br>    locomotiveSummary: builder.query({<br>      query: () =&gt; ({<br>        url: &quot;/admin/summary&quot;,<br>      }),<br>    }),<br>  }),<br>});<br><br>export const { useLocomotiveSummaryQuery } = adminApiSlice;</pre><p>Then, create the store:</p><pre>export const store = configureStore({<br>  reducer: {<br>    [apiSlice.reducerPath]: apiSlice.reducer,<br>  },<br>  middleware: (getDefaultMiddleware) =&gt;<br>    getDefaultMiddleware().concat(apiSlice.middleware),<br>  devTools: true,<br>});</pre><p>After that, go to main.jsx and wrap the App with the store:</p><pre>ReactDOM.createRoot(document.getElementById(&quot;root&quot;)).render(<br>  &lt;React.StrictMode&gt;<br>    &lt;Provider store={store}&gt;<br>      &lt;App /&gt;<br>    &lt;/Provider&gt;<br>  &lt;/React.StrictMode&gt;<br>);</pre><p>Finally, create the user interface:</p><h4>SummaryBox.jsx</h4><pre>const SummaryBox = ({ title, value, backgroundColor, Logo, size, color }) =&gt; {<br>  return (<br>    &lt;Box<br>      display=&quot;flex&quot;<br>      sx={{<br>        backgroundColor,<br>        width: &quot;300px&quot;,<br>        height: &quot;150px&quot;,<br>        borderRadius: &quot;12px&quot;,<br>      }}<br>    &gt;<br>      &lt;Box<br>        flex={1.6}<br>        display=&quot;flex&quot;<br>        flexDirection=&quot;column&quot;<br>        justifyContent=&quot;center&quot;<br>        rowGap=&quot;25px&quot;<br>        pl=&quot;10px&quot;<br>        pb=&quot;7px&quot;<br>        boxSizing=&quot;border-box&quot;<br>        sx={{ height: &quot;100%&quot; }}<br>      &gt;<br>        &lt;Typography<br>          style={{<br>            fontFamily: &quot;Poppins&quot;,<br>            fontSize: &quot;17px&quot;,<br>            fontWeight: 500,<br>            color: &quot;#fff&quot;,<br>            textShadow: &quot;1px 1px 2px rgba(0, 0, 0, 0.45)&quot;,<br>          }}<br>        &gt;<br>          {title}<br>        &lt;/Typography&gt;<br>        &lt;Typography<br>          style={{<br>            fontFamily: &quot;Inter&quot;,<br>            fontSize: &quot;20px&quot;,<br>            fontWeight: 500,<br>            color: &quot;#fff&quot;,<br>            textShadow: &quot;1px 1px 2px rgba(0, 0, 0, 0.45)&quot;,<br>          }}<br>        &gt;<br>          {value}<br>        &lt;/Typography&gt;<br>      &lt;/Box&gt;<br>      &lt;Box flex={1} display=&quot;flex&quot; alignItems=&quot;center&quot; height=&quot;100%&quot;&gt;<br>        &lt;Logo sx={{ fontSize: size, color }} /&gt;<br>      &lt;/Box&gt;<br>    &lt;/Box&gt;<br>  );<br>};<br><br>export default SummaryBox;</pre><h4>App.jsx</h4><pre>function App() {<br>  const { data } = useLocomotiveSummaryQuery(&quot;&quot;, { pollingInterval: 10000 });<br><br>  const chartData = [<br>    [&quot;Status&quot;, &quot;Total&quot;],<br>    [&quot;Excellent&quot;, data?.totalLocomotiveExcellent],<br>    [&quot;Poor&quot;, data?.totalLocomotivePoor],<br>    [&quot;Good&quot;, data?.totalLocomotiveGood],<br>  ];<br><br>  const options = {<br>    titleTextStyle: {<br>      color: &quot;#ffffff&quot;, // Set the font color for the title<br>    },<br>    legend: {<br>      textStyle: {<br>        color: &quot;#ffffff&quot;, // Set the font color for the legend text<br>      },<br>    },<br>    pieHole: 0.4,<br>    is3D: false,<br>    backgroundColor: &#39;#3d3b3b&#39;,<br>    chartArea: {<br>      width: &quot;100%&quot;,<br>      height: &quot;85%&quot;,<br>    },<br>    slices: {<br>      0: { color: &quot;#7aff52&quot; },<br>      1: { color: &quot;#ff7878&quot; },<br>      2: { color: &quot;#ffe53b&quot; },<br>    },<br>    pieSliceBorderColor: &quot;#4d4d4d&quot;,<br>    pieSliceTextStyle: {<br>      color: &quot;#4d4d4d&quot;,<br>    },<br>  };<br><br>  return (<br>    &lt;Box display=&quot;flex&quot; sx={{ width: &quot;100vw&quot;, height: &quot;100vh&quot;, flexDirection: &quot;column&quot; }}&gt;<br>      &lt;Appbar flexSize={0.8} /&gt;<br>      &lt;Box flex={6} p={2} sx={{ backgroundColor: &quot;#565656&quot;, flexDirection: &quot;row&quot; }}&gt;<br>        &lt;Box display=&quot;flex&quot; columnGap=&quot;18px&quot;&gt;<br>          &lt;SummaryBox<br>            title=&quot;Total Locomotive&quot;<br>            value={data?.totalLocomotive}<br>            backgroundColor=&quot;#91dffa&quot;<br>            Logo={CircleIcon}<br>            size={100}<br>            color=&quot;#a1e7ff&quot;<br>          /&gt;<br>          &lt;SummaryBox<br>            title=&quot;Total Locomotive Poor&quot;<br>            value={data?.totalLocomotivePoor}<br>            backgroundColor=&quot;#ff7878&quot;<br>            Logo={ClearIcon}<br>            size={100}<br>            color=&quot;#fc9797&quot;<br>          /&gt;<br>          &lt;SummaryBox<br>            title=&quot;Total Locomotive Good&quot;<br>            value={data?.totalLocomotiveGood}<br>            backgroundColor=&quot;#ffe53b&quot;<br>            Logo={CheckIcon}<br>            size={100}<br>            color=&quot;#fff4a3&quot;<br>          /&gt;<br>          &lt;SummaryBox<br>            title=&quot;Total Locomotive Excellent&quot;<br>            value={data?.totalLocomotiveExcellent}<br>            backgroundColor=&quot;#7aff52&quot;<br>            Logo={DoneAllIcon}<br>            size={100}<br>            color=&quot;#a3ff87&quot;<br>          /&gt;<br>        &lt;/Box&gt;<br>        &lt;Box display=&quot;flex&quot; width=&quot;35%&quot; height=&quot;35%&quot; borderRadius={6} sx={{ overflow: &#39;hidden&#39;, marginTop: &#39;12px&#39; }}&gt;<br>          &lt;Chart<br>            chartType=&quot;PieChart&quot;<br>            data={chartData}<br>            options={options}<br>            width={&quot;100%&quot;}<br>            height={&quot;100%&quot;}<br>          /&gt;<br>        &lt;/Box&gt;<br>      &lt;/Box&gt;<br>    &lt;/Box&gt;<br>  );<br>}<br><br>export default App;</pre><p>That’s all from this mini project. I hope you can gain something from this.</p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8fea351168b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UX Case Study: Krealogi’s Feature — Simple CRM]]></title>
            <link>https://umar-fajar14.medium.com/ux-case-study-krealogis-feature-simple-crm-3bb284968346?source=rss-3e59dd4ecc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bb284968346</guid>
            <category><![CDATA[krealogi]]></category>
            <category><![CDATA[ux-case-study]]></category>
            <category><![CDATA[crm]]></category>
            <category><![CDATA[design-thinking]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Muhammad Umar Al Fajar]]></dc:creator>
            <pubDate>Sun, 28 Nov 2021 16:50:26 GMT</pubDate>
            <atom:updated>2021-11-28T23:17:46.612Z</atom:updated>
            <content:encoded><![CDATA[<h3>UX Case Study: Krealogi’s Feature — Simple CRM</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xy6BwIrEN5CPLeMoEALpWA.png" /><figcaption>Image by Author</figcaption></figure><blockquote>This project is part of the <a href="https://skilvul.com/courses/uiux-design-mastery">UI/UX training program</a> implemented by Skilvul, for Kampus Merdeka program held by Ministry of Education, Culture, Research, and Technology of the Republic of Indonesia. I am not working under a professional contract by Krealogi.</blockquote><p>In the middle of this year, I attended a UI/UX design class which was held by Skilvul X Kampus Merdeka. The participants were divided into several groups based on the challenge they had chosen, I chose UX Challenge to create a design for one of Krealogi’s features: CRM. This project is a team project and my team consists of three people including me, the other two are <a href="https://medium.com/@sabrianasista28">Nevia Sabriana Sista</a> and <a href="https://medium.com/@thamrinoct99">Ridwan Thamrin</a>.</p><h3>About Krealogi</h3><p>The Krealogi application is a mobile application to help MSMEs Craft and Fashion to plan, monitor, and analyze businesses to continue growing. However, the users are having problems managing and contacting their customers. Therefore, Krealogi needs a simple CRM feature with a user-friendly application design for its target users.</p><h3>Problems</h3><p>The main problem that the users encounter is, the incoming order record feature only provides incoming order records, but the client database cannot yet be stored so this is an opportunity for additional features that support the ease of selling products by users.</p><h3>Solutions</h3><p>We created a simple CRM feature to make it easier for the users managing their customers and record order that integrated with the contact database. We also created an integration with WhatsApp to make it easier to contact customers. Last but not least, we also created a name card feature for the users that can be shared on social media such as WhatsApp to introduce their store to the customer.</p><h3>End-User</h3><p>For the end-user, we aim for the MSME owners and there are several categories for MSME owners that use Krealogi App such as:</p><ul><li>Tech Anxious</li><li>Tech Novice</li><li>Tech Apprentice</li><li>Tech Practitioner</li></ul><p>We focused on creating an application for tech novices and tech apprentices because they are trying to learn new things and are willing to spend more time in the learning process.</p><h3>Team Role</h3><p>Our team consists of 3 people including me, the other 2 are <a href="https://medium.com/@sabrianasista28">Nevia Sabriana Sista</a> and <a href="https://medium.com/@thamrinoct99">Ridwan Thamrin</a>. We are responsible for:</p><ol><li>Empathize</li><li>Define</li><li>Ideate</li><li>Prototype</li><li>Test</li></ol><h3>Design Process</h3><p>For this project, we used Design Thinking as our design process approach. The reason is because of this approach is useful to break down problems in any complex system. There are several stages that need to be done as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QPsf_YSwU5adrruiyuVfsw.png" /><figcaption>Image by Author</figcaption></figure><h4>1 — Empathize</h4><p>For the empathize stage, we used secondary research to find out the user’s problems. The method that we used in this stage is collecting research that has been done by Krealogi and we also did a competitor analysis from similar apps. The result is we discover some findings related to CRM such as:</p><ul><li>User experience problem with order recording which is inputting the customer’s information manually.</li><li>User experience problem when contacting customer who has orders because there is no contact list and integration with social media such as WhatsApp in the Krealogi App yet.</li></ul><h4>2 — Define</h4><p>In this stage, we try to think like the user and try to define the problems that the user encounter or the user’s pain points, and then we also define the “How-Might We” and the result is to make the users easier to manage contacts and orders.</p><p>As for the pain points and How-Might are shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XwvzrR9Dhe1YjPpq23a4IQ.png" /><figcaption>Pain Points</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*Zm21c9Y3l12JsAVveQ1Yww.png" /><figcaption>How-Might We</figcaption></figure><h4>3 — Ideate</h4><p>In this stage, we start by providing solution ideas for the “How-Might We” and then group those ideas into several parts. After that, we decide which part will be prioritized first, do next, do last, and later. The last but not least, we do the crazy 8’s for the feature ideas that we prioritized. The details of this stage are shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*yyiQkRThPWVsKhrUqg4mow.png" /><figcaption>Solution Idea</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*L_C6byqq7Sandre49vx7cA.png" /><figcaption>Affinity Diagram</figcaption></figure><p><strong>Prioritization Idea</strong></p><p>As for the prioritization idea, we decide the CRM and Communication features as the most prioritized feature and for the tutorial feature, we decide to do it after the most prioritized feature is completed. Then for the most prioritized idea, we made the Crazy 8’s as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IJosnS1ot9J6oSasbT3hyA.png" /><figcaption>Crazy 8&#39;s</figcaption></figure><h4>4 — Prototype</h4><p>In this stage, we started to make a user flow for the features that we prioritized. We breakdown those features into several flows as shown below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.figma.com%2Fembed%3Fembed_host%3Doembed%26url%3Dhttps%3A%2F%2Fwww.figma.com%2Ffile%2FjEnnYMeqWgreJA5ZTrXoCf%2FKrealogi---CRM-Feature%3Fnode-id%3D51%253A7560&amp;display_name=Figma&amp;url=https%3A%2F%2Fwww.figma.com%2Ffile%2FjEnnYMeqWgreJA5ZTrXoCf%2FKrealogi---CRM-Feature%3Fnode-id%3D51%253A7560&amp;image=https%3A%2F%2Fapi-cdn.figma.com%2Fresize%2Fthumbnails%2Fe0c0e952-e1fd-4d84-a358-93a4cf7d366e%3Fheight%3D409%26bucket%3Dfigma-alpha&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=figma" width="800" height="450" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd37779d5c255e1b5370105cb3b10c58/href">https://medium.com/media/fd37779d5c255e1b5370105cb3b10c58/href</a></iframe><p>After the user flows were created we moved on to start creating wireframes for several pages based on the Crazy 8’s that were made. The purpose of wireframing is as a reference for making the UI Design. And for the wireframes and UI Designs themselves are shown below:</p><p><strong>Wireframes</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.figma.com%2Fembed%3Fembed_host%3Doembed%26url%3Dhttps%3A%2F%2Fwww.figma.com%2Ffile%2FjEnnYMeqWgreJA5ZTrXoCf%2FKrealogi---CRM-Feature%3Fnode-id%3D837%253A24465&amp;display_name=Figma&amp;url=https%3A%2F%2Fwww.figma.com%2Ffile%2FjEnnYMeqWgreJA5ZTrXoCf%2FKrealogi---CRM-Feature%3Fnode-id%3D837%253A24465&amp;image=https%3A%2F%2Fapi-cdn.figma.com%2Fresize%2Fthumbnails%2Fce679d9e-2d09-411c-89ee-5279619aac39%3Fheight%3D409%26bucket%3Dfigma-alpha&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=figma" width="800" height="450" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0d1e67a5217c0923c515729b5812f37/href">https://medium.com/media/d0d1e67a5217c0923c515729b5812f37/href</a></iframe><p><strong>UI Kit</strong></p><p>We also created a UI Kit to make us easier to create a UI Design or a frame that uses the same or similar component as shown below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.figma.com%2Fembed%3Fembed_host%3Doembed%26url%3Dhttps%3A%2F%2Fwww.figma.com%2Ffile%2FjEnnYMeqWgreJA5ZTrXoCf%2FKrealogi---CRM-Feature%3Fnode-id%3D2%253A2&amp;display_name=Figma&amp;url=https%3A%2F%2Fwww.figma.com%2Ffile%2FjEnnYMeqWgreJA5ZTrXoCf%2FKrealogi---CRM-Feature%3Fnode-id%3D2%253A2&amp;image=https%3A%2F%2Fapi-cdn.figma.com%2Fresize%2Fthumbnails%2Fde9be6e0-6007-4f72-8fc2-d2c129d62bb5%3Fheight%3D409%26bucket%3Dfigma-alpha&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=figma" width="800" height="450" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0b5ea0276c1a308344570c1e5254a87/href">https://medium.com/media/a0b5ea0276c1a308344570c1e5254a87/href</a></iframe><p><strong>UI Designs</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lS_RiPQGCEXvZeW-LlZiaA.png" /><figcaption>Image by Author</figcaption></figure><p>After we finished making the UI Designs, we started to connect each of those frames according to the user flows that we made to form a prototype based on the user flows. As for the prototype itself is shown below:</p><p><strong>Prototype</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.figma.com%2Fembed%3Fembed_host%3Doembed%26url%3Dhttps%3A%2F%2Fwww.figma.com%2Fproto%2FjEnnYMeqWgreJA5ZTrXoCf%2FKELOMPOK-2---SVI---UIX-20%3Fnode-id%3D259%253A9603%26scaling%3Dscale-down%26page-id%3D111%253A7693%26starting-point-node-id%3D259%253A9603%26show-proto-sidebar%3D1&amp;display_name=Figma&amp;url=https%3A%2F%2Fwww.figma.com%2Fproto%2FjEnnYMeqWgreJA5ZTrXoCf%2FKELOMPOK-2---SVI---UIX-20%3Fnode-id%3D259%253A9603%26scaling%3Dscale-down%26page-id%3D111%253A7693%26starting-point-node-id%3D259%253A9603%26show-proto-sidebar%3D1&amp;image=https%3A%2F%2Fapi-cdn.figma.com%2Fresize%2Fthumbnails%2F0628353c-ea3c-4875-99f4-04f6634e1ecf%3Fheight%3D409%26bucket%3Dfigma-alpha&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=figma" width="800" height="450" frameborder="0" scrolling="no"><a href="https://medium.com/media/723d9aab9ef5f72f19a4b73f0a18559a/href">https://medium.com/media/723d9aab9ef5f72f19a4b73f0a18559a/href</a></iframe><h4>5 — Test</h4><p>In this stage, we were doing user research with an In-Depth Interview and Usability Testing method that started with searching for a participant who are willing to do an interview and try out the prototype that we made. After searching for days, we finally found a participant who meets our criteria and was willing to do the user research with us. In short, after we did user research, we discovered some findings of our design such as:</p><ul><li>The information that showed on the name card does not meet the user’s needs, the user wants more information on the name card.</li><li>The user needs an input field on the customer form to put a little detail that is currently not available in our designs.</li><li>The user wants a calendar that has integration with the customer’s order which is that feature is currently not available in our designs.</li></ul><h3>Iteration Design</h3><p>Based on the result of user research, we must do an iteration design so we go back to the prototype stage to fix the UI Designs and also the prototype. Which is the latest version is already shown above in the prototype section. And for the iteration design details are shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZveutCnuD6aWmUcg7pYZrw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ck1PripS8ISOWa2AiXYk1A.png" /></figure><h3>Conclusion</h3><p>After the long journey, we finally finished all of the design processes that were well executed at the end with all the task flow completed and got some feedback from the participant of user research.</p><h3>Recommendation</h3><p>As the recommendations for the next design that’s based on the user research, we suggest adding a calendar feature that integrated with the customer’s orders to improve the user experience in managing their order in just one app.</p><h3>Thank you for your time!</h3><p>Feel free to connect with me on <a href="https://www.linkedin.com/in/muhammad-umar-al-fajar-0639bb212">LinkedIn</a> and I would also love to know your feedback!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bb284968346" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coursekai Case Study]]></title>
            <link>https://umar-fajar14.medium.com/coursekai-case-study-af01bd8b639f?source=rss-3e59dd4ecc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/af01bd8b639f</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[case-study]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[ux]]></category>
            <dc:creator><![CDATA[Muhammad Umar Al Fajar]]></dc:creator>
            <pubDate>Sun, 24 Oct 2021 16:30:46 GMT</pubDate>
            <atom:updated>2021-11-27T15:52:34.794Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*DZyrM3Ii9jGDaS8p0QsD1A.png" /><figcaption>Image by Author</figcaption></figure><blockquote>This project is part of the <a href="https://skilvul.com/courses/uiux-design-mastery">UI/UX training program</a> implemented by Skilvul, for Kampus Merdeka program held by Ministry of Education, Culture, Research, and Technology of the Republic of Indonesia.</blockquote><h3>About</h3><p>Coursekai is an online education app that provides course-based learning with several main categories such as data science, computer science, and information technology. This application is currently making a major overhaul that includes the UI and the structure of the system due to revenue drop since 1 year ago.</p><h3>Problems</h3><p>There are several major problems that users encounter such as:</p><ul><li>Users are not satisfied with the UI</li><li>The platform is too complicated for the user</li><li>Long loading time</li><li>Lacks in motivation to finish the course</li></ul><h3>The Solution</h3><p>To resolve the problem we tried to make the UI more minimalist to make it less complicated for the user, also for the loading time we tried to display less information that is not important to make it straightforward for the user and reduce animation used to make the page load faster, and the last but not least we added interaction features for participants such as forum and chat with each participant.</p><h3>End-User</h3><p>The target user for this App is an employee with mid-end financial status or college students who wants to develop their skills outside of what they got from their universities such as industry skills and knowledge.</p><h3>Team Role</h3><p>Our team consists of 3 people including me, the other 2 are <a href="https://medium.com/@ilammm">Muhammad Ilham</a> and <a href="https://medium.com/@leosihombing_27492">Leonard Halomoan Sihombing</a> we are responsible for defining, ideating, prioritizing ideas, and crazy 8’s which are become references in the designing process. And for the rest are my responsibility such as:</p><ul><li>UI Kit</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*In8l_7_f6rzmumqKcAiKLw.jpeg" /></figure><ul><li>User Flow</li><li>Wireframing</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*clUE4P9d-doPCiaGWll2UA.jpeg" /><figcaption>Image by Author</figcaption></figure><ul><li>UI Design</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iB8FTZxfZvCa3BBLuPfAzQ.jpeg" /><figcaption>Image by Author</figcaption></figure><ul><li>Prototyping</li><li>Testing</li></ul><h3>Design Process</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rmn3JHKOl1DThA1svrflDg.jpeg" /><figcaption>Image by Author</figcaption></figure><p>In this case, we choose to use design thinking as our design process approach, because the application needs a major overhaul so we have to think about the brand new idea as well as the features that will solve the user&#39;s problems. The stages include:</p><h4>Empathize</h4><p>We skipped this stage and received a project brief instead as I mentioned in the About, Problems, and End-user sections.</p><h4>Define</h4><p>In this stage, we tried to think like the user and try to define the problems that the user encounter or the user’s pain points, and then we also define the “How-Might We” and the result is making an application that more interactive with the users.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.figma.com%2Fembed%3Fembed_host%3Doembed%26url%3Dhttps%3A%2F%2Fwww.figma.com%2Ffile%2FeWo8A2Klz6Xl3UPCZYkIRH%2FDefine-Stage&amp;display_name=Figma&amp;url=https%3A%2F%2Fwww.figma.com%2Ffile%2FeWo8A2Klz6Xl3UPCZYkIRH%2FDefine-Stage&amp;image=https%3A%2F%2Fapi-cdn.figma.com%2Fresize%2Fthumbnails%2FeWo8A2Klz6Xl3UPCZYkIRH%2Fdefault%3Fheight%3D450%26bucket%3Dfigma-alpha&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=figma" width="800" height="450" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1a4da9e0892938055e3f4d2b88d4ff3/href">https://medium.com/media/c1a4da9e0892938055e3f4d2b88d4ff3/href</a></iframe><h4>Ideate</h4><p>In this stage, we start by providing solution ideas for the “How-Might We” and then group those ideas into several parts. After that, we decide which part will be prioritized first, do next, do last, and later. The last but not least, we do the crazy 8’s for the feature ideas that we prioritized such as a forum, chat, profile, and also the other basic pages in this application such as home, lecture content, and course page, after that we are voting for the same page to determine which one will be the reference for designing the UI.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.figma.com%2Fembed%3Fembed_host%3Doembed%26url%3Dhttps%3A%2F%2Fwww.figma.com%2Ffile%2F3WsXgvvzomofUDxN0nxSDX%2FIdeate-Stage&amp;display_name=Figma&amp;url=https%3A%2F%2Fwww.figma.com%2Ffile%2F3WsXgvvzomofUDxN0nxSDX%2FIdeate-Stage&amp;image=https%3A%2F%2Fapi-cdn.figma.com%2Fresize%2Fthumbnails%2F3WsXgvvzomofUDxN0nxSDX%2Fdefault%3Fheight%3D450%26bucket%3Dfigma-alpha&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=figma" width="800" height="450" frameborder="0" scrolling="no"><a href="https://medium.com/media/ceb13ac45f9c9faad4b2543d621e6706/href">https://medium.com/media/ceb13ac45f9c9faad4b2543d621e6706/href</a></iframe><h4>Prototyping</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.figma.com%2Fembed%3Fembed_host%3Doembed%26url%3Dhttps%3A%2F%2Fwww.figma.com%2Fproto%2FC5lz7lU5lZOBuUvNj8rxGZ%2FMuhammad-Umar-Al-Fajar---SVI---UIX-20%3Fpage-id%3D102%253A79%26node-id%3D243%253A1528%26viewport%3D305%252C48%252C0.24%26scaling%3Dscale-down%26starting-point-node-id%3D208%253A435%26show-proto-sidebar%3D1&amp;display_name=Figma&amp;url=https%3A%2F%2Fwww.figma.com%2Fproto%2FC5lz7lU5lZOBuUvNj8rxGZ%2FMuhammad-Umar-Al-Fajar---SVI---UIX-20%3Fpage-id%3D102%253A79%26node-id%3D243%253A1528%26viewport%3D305%252C48%252C0.24%26scaling%3Dscale-down%26starting-point-node-id%3D208%253A435%26show-proto-sidebar%3D1&amp;image=https%3A%2F%2Fapi-cdn.figma.com%2Fresize%2Fthumbnails%2FC5lz7lU5lZOBuUvNj8rxGZ%2Fdefault%3Fheight%3D450%26bucket%3Dfigma-alpha&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=figma" width="800" height="450" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7dc13754eb808257ce61749349acb4e/href">https://medium.com/media/d7dc13754eb808257ce61749349acb4e/href</a></iframe><h4>Testing</h4><p>In this stage, I did an interview with a college student who match the criteria as I mentioned in the End-User section, his name is Enrico Anderson and he is 21 years old who interested in game development and art such as visual design. During the prototype testing, the respondent flawlessly completed every single task that I ask, but he’s not very satisfied with the placement of the chat feature which is can only be accessed in the friend list. At the end of the test, he gave 6 out of 7 points for the prototype in terms of convenience.</p><h3>Conclusion</h3><p>As for the result, all of the task flows are successfully executed such as registering &amp; log in, looking for class detail &amp; making transactions, learning, and interacting with other participants. But there is some feedback for the interaction feature and page navigation.</p><h3>Recommendation</h3><p>For the next design solution, we recommend a special privilege for students with an academy email domain to enroll in several courses with discounts or even free. Then for the interaction feature that needs improvement in the accessibility aspect, the chat feature needs to be placed on the social page as well in order for easier access. Then last but not least, put a description on the navigation icon to make the interface less complicated for the users so they will know where they will be going.</p><h3>Thank you for your time!</h3><p>Feel free to comment and I would also love to know your feedback!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af01bd8b639f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fizz, Buzz, dan Fizz Buzz!]]></title>
            <link>https://umar-fajar14.medium.com/fizz-buzz-dan-fizz-buzz-6eeaf89c61de?source=rss-3e59dd4ecc8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6eeaf89c61de</guid>
            <category><![CDATA[unikom]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[teknik-informatika]]></category>
            <category><![CDATA[fizzbuzz]]></category>
            <dc:creator><![CDATA[Muhammad Umar Al Fajar]]></dc:creator>
            <pubDate>Tue, 01 Jun 2021 08:01:52 GMT</pubDate>
            <atom:updated>2021-06-02T01:41:25.051Z</atom:updated>
            <content:encoded><![CDATA[<h3>Perkenalan</h3><p>Halo teman-teman bagaimana kabarnya? semoga baik-baik saja yaaa, kali ini saya akan membahas mengenai “Fizz Buzz”. Sebelumnya saya ingin memperkenalkan diri dulu, saat ini saya adalah seorang mahasiswa semester enam yang berkuliah di salah satu Universitas Swasta di Bandung yaitu <a href="https://unikom.ac.id/">Universitas Komputer Indonesia</a>, saya berasal dari <a href="https://if.unikom.ac.id/">Program Studi Teknik Informatika</a> yang berada pada <a href="https://ftik.unikom.ac.id/">Fakultas Teknik dan Ilmu Komputer</a>. Baik itu saja mungkin perkenalan diri dari saya, kita akan langsung lanjutkan ke pembahasan.</p><h3>Definisi</h3><blockquote>The “Fizz-Buzz test” is an interview question designed to help filter out the 99.5% of programming job candidates who can’t seem to program their way out of a wet paper bag.</blockquote><p>Jadi “Fizz Buzz” merupakan pertanyaan interview yang dirancang untuk menyaring calon programmer yang tidak tau bagaimana caranya memprogram, hmmmm.</p><h3>Mari kita bahas</h3><p>“Fizz Buzz” adalah suatu masalah yang hampir ditanyakan pada setiap <em>coding interview</em>, masalah ini digunakan pada tahap awal untuk menyeleksi mana yang <em>programmer</em> dan mana yang bukan, masalah ini terbilang sangat mudah bagi <em>programmer</em> karena kita hanya cukup mengerti tentang perulangan dan matematika dasar yang dimana dua hal tersebut termasuk dalam modal yang harus dimiliki oleh seorang <em>programmer</em>, jika seorang <em>programmer</em> tidak memiliki salah satu atau bahkan dua modal tersebut, tentu saja akan kesulitan dalam memecahkan masalah “Fizz Buzz” ini, dan pada kenyataannya pun banyak yang tidak bisa memecahkan masalah yang terbilang sederhana dan mudah ini.</p><p>Jadi, seperti apa sih sebenarnya masalah “Fizz Buzz” itu?</p><p>Masalahnya adalah kita akan diminta membuat sebuah <em>function</em> dengan <em>integer</em> atau angka sebagai <em>parameter</em>, nantinya <em>function</em> tersebut akan melakukan iterasi dari angka pertama sampai angka yang sudah ditentukan di parameter, dimana jika angka tersebut bisa dibagi oleh angka tiga maka akan menjadi “Fizz” dan apabila angka tersebut bisa dibagi oleh angka lima maka akan diganti menjadi “Buzz”, bagaimana dengan angka yang bisa dibagi oleh angka tiga dan angka lima? angka yang bisa dibagi oleh angka tiga dan angka lima nantinya akan diganti menjadi “Fizz Buzz”.</p><p>Kelihatannya cukup sederhana bukan? tapi anehnya banyak yang tidak bisa dalam memecahkan masalah tersebut.</p><p>Hal tersebut terjadi mungkin karena selama kuliah dan mengerjakan tugas-tugas pola pengerjaannya berbeda dengan masalah yang diajukan pada saat interview, masalah pada tugas-tugas yang diberikan pada saat kuliah tentu saja berbeda dengan masalah yang diajukan pada saat proses interview, sebetulnya masalah yang diajukan pada saat proses interview terbilang sederhana dan mudah, namun pada kenyataannya masalah tersebut cukup untuk membuat sedikit kebingungan atau bahkan tidak bisa sama sekali untuk memecahkan masalah tersebut, untuk itu perlu pemahaman yang baik soal bahasa pemrograman yang kita gunakan agar kita bisa merubah hasil pemikiran kita ke dalam sebuah kode, karena yang menjadi masalah adalah bagaimana menerapkan pemecahan suatu masalah pada sebuah bahasa pemrograman.</p><h3>Coding Interview?</h3><p>Tapi sebelum itu kita akan membahas sedikit tentang <em>coding interview</em>, sebelum coding interview alangkah baiknya teman-teman menyiapkan segala hal yang diperlukan untuk coding, tapi bukan menyiapkan kopi dan cemilan juga yah xixixi, yang harus teman-teman persiapkan dalam <em>coding interview</em> adalah IDE nya tentu saja dan siapkan juga berupa <em>project</em> kosong, kemudian teman-teman juga harus tau bagaimana cara menjalankan sebuah <em>unit test</em>, karena itu akan menjadi nilai tambah tersendiri buat teman-teman saat <em>coding interview</em>.</p><p>Namun jangan lupa juga bahwa <em>coding interview</em> bukan hanya tentang memecahkan masalah seperti “Fizz Buzz”, berikut adalah tips untuk <em>coding interview</em>:</p><ol><li>siapkan mental agar teman-teman bisa menjawab pertanyaan yang seharusnya teman-teman bisa menjawabnya, jangan sampai nanti teman-teman menyesal karena hal tersebut.</li><li>siapkan dokumen-dokumen yang teman-teman butuhkan seperti CV, surat lamaran, sertifikat penghargaan, dan lainnya.</li><li>tunjukkan portofolio program apa saja yang pernah teman-teman buat.</li></ol><p>Selain pertanyaan teknis <em>interview programmer</em>, pertanyaan yang bersifat non-teknis juga sangat penting untuk dipelajari.</p><p>Sebagai contoh, teman-teman harus bisa meyakinkan ke pihak perekrut bagaimana bisa menghadapi tekanan dalam pekerjaan, bagaimana cara berkomunikasi dengan mitra dalam satu proyek hingga pandangan Anda tentang tren dunia pemrograman saat ini.</p><p>Dengan kata lain, asah kemampuan Anda berbicara agar pihak perekrut meyakini teman-teman adalah kandidat yang selalu ingin belajar hal baru dan berbagi perkembangan proyek terkini dengan sesama mitra proyek.</p><h3>Contoh Pertanyaan-pertanyaan Non-Teknis</h3><ol><li>Apa tugas umum seorang programmer?<br>Meskipun terdengar sepele, pertanyaan ini mungkin saja ditanyakan oleh perekrut untuk menguji seberapa paham kamu tentang deskripsi kerja yang kamu lamar. Jawablah dengan singkat, padat, dan jelas sesuai pemahamanmu.</li><li>Apa saja bahasa pemrograman yang kamu kuasai?<br>Pastikan kamu menjawab dengan percaya diri dan sesuai dengan yang tertera di CV agar perekrut lebih yakin atas kredibilitasmu. Menguasai bahasa pemrograman yang sedang naik daun seperti C++, Go, atau Java dapat menjadi nilai plus dalam penilaian.</li><li>Apa saja bahasa pemrograman yang kamu kuasai?<br>Pastikan kamu menjawab dengan percaya diri dan sesuai dengan yang tertera di CV agar perekrut lebih yakin atas kredibilitasmu. Menguasai bahasa pemrograman yang sedang naik daun seperti C++, Go, atau Java dapat menjadi nilai plus dalam penilaian.</li><li>Apakah kamu lebih nyaman mengerjakan pemrograman secara tandem atau personal?<br>Tidak ada jawaban yang benar atau salah untuk pertanyaan ini. Perekrut hanya ingin tahu tipe kerja sama yang kamu miliki. Jawablah dengan jujur berdasarkan pengalamanmu selama ini agar pengalaman kerjamu nantinya juga sesuai dengan yang kamu harapkan.</li><li>Apakah contoh tantangan terberat yang pernah kamu selesaikan dalam pemrograman?<br>Kamu pernah membangun aplikasi sederhana dengan tools seadanya? Atau, pernah ikut proyek sukarela untuk misi tertentu? Jabarkan pengalaman yang berharga bagimu dan tunjukkan bahwa kamu mampu bekerja di bawah berbagai tantangan.</li><li>Pentingkah sertifikasi dan pelatihan bagimu sebagai seorang programmer?<br>Ada programmer yang menempuh jalur otodidak. Ada juga yang memilih menimba ilmu di pelatihan. Manapun jalur yang kamu pilih, ceritakan preferensimu pada perekrut agar mereka mengerti dari jalur mana kamu berasal dan ke mana orientasimu di masa depan.</li><li>Adakah ilmu pemrograman yang ingin kamu pelajari dalam waktu dekat?Jawabanmu atas pertanyaan ini akan mencerminkan semangat untuk belajar. Memiliki profesi di dunia IT, apalagi sebagai programmer, kamu dituntut untuk terus belajar dan menambah pengalaman. Semangat atau tidaknya kamu untuk beradaptasi bisa jadi pertimbangan oleh perekrut.</li></ol><h3>Kembali ke Masalah Fizz Buzz</h3><p>Oke sekarang kita lanjut ke coding dan pembahasanyaaa…</p><pre>import org.testng.annotations.Test;<br><br>public class FizzBuzz {<br>    public void fizzBuzz(int total) {<br>        for (int i = 1; i &lt;= total; i++) {<br>            if (i % 3 == 0 &amp;&amp; i % 5 == 0) {<br>                System.<em>out</em>.println(&quot;Fizz Buzz&quot;);<br>            }else if (i % 3 == 0) {<br>                System.<em>out</em>.println(&quot;Fizz&quot;);<br>            }else if (i % 5 == 0) {<br>                System.<em>out</em>.println(&quot;Buzz&quot;);<br>            }else {<br>                System.<em>out</em>.println(i);<br>            }<br>        }<br>    }<br>    @Test<br>    void testFizzBuzz() {<br>        fizzBuzz(100);<br>    }<br>}</pre><p>Di sini saya menggunakan bahasa pemrograman Java, bebas sebenarnya untuk masalah “Fizz Buzz” ini teman-teman bisa menggunakan bahasa pemrograman apa saja.</p><pre>public void fizzBuzz(int total) {<br>        for (int i = 1; i &lt;= total; i++) {</pre><pre>        }<br>}</pre><p>Untuk penjelasan kode di atas pertama-tama kita membuat sebuah <em>function</em> dengan <em>parameter</em> yang diberi nama “total” dengan tipe <em>integer</em>, untuk penamaan bebas teman-teman bisa menggunakan apa saja. Selanjutnya di dalam <em>function</em> tersebut kita melakukan iterasi untuk <em>integer</em> i sampai kurang atau sama dengan nilai total, yang dimana nilai totalnya akan kita tentukan saat kita memanggil <em>function</em> tersebut.</p><pre>            if (i % 3 == 0 &amp;&amp; i % 5 == 0) {<br>                System.<em>out</em>.println(&quot;Fizz Buzz&quot;);<br>            }else if (i % 3 == 0) {<br>                System.<em>out</em>.println(&quot;Fizz&quot;);<br>            }else if (i % 5 == 0) {<br>                System.<em>out</em>.println(&quot;Buzz&quot;);<br>            }else {<br>                System.<em>out</em>.println(i);<br>            }</pre><p>Selanjutnya dalam iterasi tersebut kita buat percabangan dimana jika nilainya bisa dibagi oleh angka tiga maka akan diganti dengan “Fizz” dan jika bisa dibagi dengan angka lima maka akan kita ganti dengan “Buzz” sedangkan jika bisa dibagi dengan angka tiga dan lima maka akan diganti menjadi “Fizz Buzz”.</p><p>Yang perlu teman-teman perhatikan dalam membuat percabangan ini adalah urutannya, seperti yang teman-teman liat pada kode di atas, untuk pengecekan “Fizz Buzz” diletakan paling awal karena jika kita memulai pengecekan dengan “Fizz” atau “Buzz” terlebih dahulu maka saat ada angka yang bisa dibagi angka tiga atau angka lima maka angka tersebut tidak akan menjadi “Fizz Buzz”, oleh karena itu kita lakukan pengecekan “Fizz Buzz” terlebih dahulu.</p><p>Untuk pengecekannya teman-teman bisa menggunakan operasi matematika yaitu modulo, modulo sendiri merupakan sisa bagi yang artinya jika angka tersebut dibagi maka sisanya itu adalah modulo nya, jadi ini bisa kita gunakan untuk memecahkan masalah “Fizz Buzz” ini dimana jika ada angka dimodulo tiga sama dengan nol maka akan kita ganti dengan “Fizz” dan jika ada angka dimodulo dengan angka lima maka akan kita ganti dengan “Buzz” sedangkan jika dimodulo oleh angka tiga dan angka lima sama dengan nol maka akan diganti dengan “Fizz Buzz”.</p><pre>    @Test<br>    void testFizzBuzz() {<br>        fizzBuzz(100);<br>    }</pre><p>Selanjutnya kita coba menjalankan <em>unit test</em> dan memanggil <em>function</em> yang telah kita buat tadi dan kita akan lakukan iterasi sampai angka seratus. Maka hasilnya adalah sebagai berikut:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*GEKyiMc18B5B1X0tVft8Sw.png" /></figure><p>Bagaimana? sangat sederhana dan mudah bukan? kode di atas hanya salah satu cara dalam memecahkan masalah “Fizz Buzz” ini mungkin saja teman-teman nanti akan diajukan pertanyaan mengenai “Fizz Buzz” ini namun dengan kondisi yang berbeda, untuk itu pastikan teman-teman benar-benar menguasai bahasa pemrograman yang akan teman-teman gunakan saat <em>coding interview</em>, baik mungkin itu saja pembahasan kita kali. Terimakasih.</p><p>10118340-Muhammad Umar Al Fajar<br><a href="https://if.unikom.ac.id/">Program Studi Teknik Informatika</a><br><a href="https://ftik.unikom.ac.id/">Fakultas Teknik dan Ilmu Komputer</a><br><a href="https://unikom.ac.id/">Universitas Komputer Indonesia</a></p><h3>Referensi</h3><p><a href="https://wiki.c2.com/?FizzBuzzTest">Definisi FizzBuzz</a></p><p><a href="https://www.jobstreet.co.id/career-resources/pertanyaan-yang-sering-diberikan-dalam-wawancara-programmer/">Pertanyaan-pertanyaan non-Teknis</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6eeaf89c61de" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>