<?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 Nawress RAFRAFI on Medium]]></title>
        <description><![CDATA[Stories by Nawress RAFRAFI on Medium]]></description>
        <link>https://medium.com/@nawress-rafrafi?source=rss-9d054e8c100e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*46VjdyXNQgxNtfVQ</url>
            <title>Stories by Nawress RAFRAFI on Medium</title>
            <link>https://medium.com/@nawress-rafrafi?source=rss-9d054e8c100e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 17:15:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nawress-rafrafi/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[The Future of Backend Engineering: From Infrastructure to Intelligence ]]></title>
            <link>https://nawress-rafrafi.medium.com/the-future-of-backend-engineering-from-infrastructure-to-intelligence-50d9e2514e70?source=rss-9d054e8c100e------2</link>
            <guid isPermaLink="false">https://medium.com/p/50d9e2514e70</guid>
            <dc:creator><![CDATA[Nawress RAFRAFI]]></dc:creator>
            <pubDate>Wed, 24 Sep 2025 09:48:30 GMT</pubDate>
            <atom:updated>2025-09-24T09:48:30.300Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4cvX2TI3ONt4mgZqrMVqbg.png" /></figure><p>Backend engineering has long been the backbone of software development, ensuring systems are reliable, scalable, and performant. For decades, backend engineers focused on server management, database optimization, and API design — critical tasks, yet largely invisible to end users. Today, however, the role of the backend engineer is undergoing a profound transformation. Cloud-native architectures, automation, and AI-driven systems are shifting backend engineering from traditional infrastructure management to the domain of intelligent, predictive systems.</p><p>Understanding this evolution is no longer optional; it is essential for engineers, leaders, and organizations striving to remain competitive in a digital-first world. The future belongs to those who can combine technical mastery with strategic thinking, adaptability, and the ability to harness intelligent systems effectively.</p><h3>From Monoliths to Modern Backends: A Historical Perspective</h3><p>Traditionally, backend systems revolved around monolithic architectures. Engineers manually managed servers, optimized SQL databases, and focused on CRUD operations. The work was technically challenging, but the scope was relatively contained. Skills like database design, server administration, and performance tuning defined success in the backend realm.</p><p>Over time, as systems grew in complexity and scale, the limitations of monoliths became clear: updates were slow, scaling was cumbersome, and collaboration across teams was often difficult. This paved the way for modern backend approaches.</p><h3>The Current Landscape: Cloud, Microservices, and Collaboration</h3><p>Today’s backend engineers operate in a landscape dominated by microservices, containerization, and cloud-native systems. Infrastructure-as-Code (IaC), DevOps practices, and CI/CD pipelines have become standard, emphasizing collaboration with frontend developers, product managers, and data teams.</p><p>Key skills now include designing scalable APIs, implementing observability solutions, managing distributed systems, and leveraging cloud platforms like AWS, GCP, or Azure. Backend engineers are no longer just coders — they are architects, orchestrators, and problem-solvers within complex, multi-layered systems.</p><h3>The Future: Intelligence at the Core</h3><p>The next evolution of backend engineering will place intelligence at the heart of system design. AI-powered monitoring, predictive scaling, self-healing architectures, and event-driven systems are no longer hypothetical — they are emerging realities.</p><p>In this new paradigm, backend systems can anticipate failures, optimize performance in real-time, and adapt dynamically to changing workloads. Engineers will increasingly integrate AI and ML into infrastructure, moving beyond automation to predictive, intelligent operations.</p><h3>Skills for the Intelligent Backend</h3><ul><li><strong>AI/ML Integration:</strong> Embedding machine learning into backend workflows for predictive analytics and system optimization.</li><li><strong>System Thinking:</strong> Designing end-to-end solutions that anticipate bottlenecks and adapt proactively.</li><li><strong>Automation &amp; Orchestration:</strong> Building pipelines and systems that manage themselves at scale.</li><li><strong>Cross-Disciplinary Collaboration:</strong> Working closely with product, DevOps, and data teams to align technical solutions with business outcomes.</li></ul><p>Backend engineers will be valued not only for coding skills but for their ability to contribute strategically to product decisions, operational efficiency, and organizational intelligence.</p><h3>Actionable Takeaways for Backend Engineers</h3><ol><li><strong>Embrace Continuous Learning:</strong> The pace of technological change demands constant upskilling, particularly in AI, cloud platforms, and distributed systems.</li><li><strong>Think Beyond Code:</strong> Focus on solving complex problems, understanding system-wide impacts, and anticipating future challenges.</li><li><strong>Collaborate Across Disciplines:</strong> Engage with DevOps, data teams, and product managers to ensure that intelligent systems align with business goals.</li><li><strong>Adopt a Strategic Mindset:</strong> Become a proactive contributor to decision-making processes, not just a technical executor.</li></ol><h3>Conclusion</h3><p>Backend engineering is evolving rapidly — from managing infrastructure to engineering intelligence. The engineers who thrive in this new era will combine technical expertise with strategic thinking, adaptability, and a commitment to innovation.</p><p>The future of backend engineering is not just about handling servers or databases; it is about designing systems that are intelligent, resilient, and forward-thinking. Those who embrace this shift will not only survive but will define the next generation of digital systems.</p><p><strong>How are you preparing to lead in this new era of backend engineering?</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50d9e2514e70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using FeignClient: A Smarter Approach to REST Clients]]></title>
            <link>https://nawress-rafrafi.medium.com/using-feignclient-a-smarter-approach-to-rest-clients-685663c5a04c?source=rss-9d054e8c100e------2</link>
            <guid isPermaLink="false">https://medium.com/p/685663c5a04c</guid>
            <dc:creator><![CDATA[Nawress RAFRAFI]]></dc:creator>
            <pubDate>Sun, 02 Mar 2025 12:36:43 GMT</pubDate>
            <atom:updated>2025-03-02T12:36:43.036Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ch1JWvfWC90k8uAr.png" /></figure><h3>Introduction</h3><p>When building microservices in Spring Boot, making HTTP calls to other services is a common requirement. Three popular options for this are <strong>OkHttp</strong>, <strong>RestTemplate</strong>, <strong>WebClient</strong>, and <strong>FeignClient</strong>. While OkHttp is a powerful HTTP client, RestTemplate has been the traditional approach, WebClient offers reactive capabilities, and Feign provides a more declarative and developer-friendly approach to making API calls.</p><p>This article explores why <strong>FeignClient</strong> is often a better choice over <strong>OkHttp</strong>, <strong>RestTemplate</strong>, and <strong>WebClient</strong>, providing a comparative table and examples to illustrate the differences.</p><h3>What is OkHttp?</h3><p><a href="https://square.github.io/okhttp/">OkHttp</a> is a widely-used HTTP client for Java and Kotlin. It offers features such as connection pooling, automatic retries, and WebSocket support. Spring developers often use it with <strong>RestTemplate</strong> or <strong>WebClient</strong> to make HTTP requests.</p><h3>Example: Making a Request with OkHttp</h3><pre>import okhttp3.*;<br>import java.io.IOException;<br><br>public class OkHttpExample {<br>    private static final OkHttpClient client = new OkHttpClient();<br>    public static void main(String[] args) throws IOException {<br>        Request request = new Request.Builder()<br>                .url(https://medium.com/&quot;https://api.example.com/data&quot;)<br>                .get()<br>                .build();<br>        <br>        try (Response response = client.newCall(request).execute()) {<br>            System.out.println(response.body().string());<br>        }<br>    }<br>}</pre><p>While OkHttp is efficient, handling responses, retries, and exceptions requires additional boilerplate code.</p><h3>What is RestTemplate?</h3><p><a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html">RestTemplate</a> is a synchronous HTTP client included in Spring Boot. Although widely used, it has been deprecated in favor of WebClient.</p><h3>Example: Making a Request with RestTemplate</h3><pre>import org.springframework.web.client.RestTemplate;<br><br>public class RestTemplateExample {<br>    public static void main(String[] args) {<br>        RestTemplate restTemplate = new RestTemplate();<br>        String response = restTemplate.getForObject(&quot;https://api.example.com/data&quot;, String.class);<br>        System.out.println(response);<br>    }<br>}</pre><p>RestTemplate is easier to use than OkHttp but does not support reactive programming or built-in resilience mechanisms.</p><h3>What is WebClient?</h3><p><a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/reactive/function/client/WebClient.html">WebClient</a> is the reactive successor to RestTemplate, offering non-blocking and asynchronous HTTP requests.</p><h3>Example: Making a Request with WebClient</h3><pre>import org.springframework.web.reactive.function.client.WebClient;<br>import reactor.core.publisher.Mono;<br><br>public class WebClientExample {<br>    public static void main(String[] args) {<br>        WebClient webClient = WebClient.create(&quot;https://api.example.com&quot;);<br>        Mono&lt;String&gt; response = webClient.get()<br>                .uri(&quot;/data&quot;)<br>                .retrieve()<br>                .bodyToMono(String.class);<br>        <br>        response.subscribe(System.out::println);<br>    }<br>}</pre><p>WebClient is highly efficient for reactive applications but requires familiarity with reactive programming paradigms.</p><h3>What is FeignClient?</h3><p><a href="https://spring.io/projects/spring-cloud-openfeign">Feign</a> is a declarative web service client developed by Netflix and integrated into Spring Boot through <strong>Spring Cloud OpenFeign</strong>. It simplifies HTTP calls by eliminating the need for manual request handling and serialization.</p><h3>Example: Making a Request with FeignClient</h3><p>To use Feign in a Spring Boot project, first, add the dependency:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-starter-openfeign&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Enable Feign in the main application class:</p><pre>@SpringBootApplication<br>@EnableFeignClients<br>public class FeignExampleApplication {<br>    public static void main(String[] args) {<br>        SpringApplication.run(FeignExampleApplication.class, args);<br>    }<br>}</pre><p>Define a FeignClient interface:</p><pre>@FeignClient(name = &quot;exampleClient&quot;, url = &quot;https://api.example.com&quot;)<br>public interface ExampleClient {<br>    @GetMapping(&quot;/data&quot;)<br>    String getData();<br>}</pre><p>Now, simply inject and use the client:</p><pre>@Service<br>public class DataService {<br>    private final ExampleClient exampleClient;<br><br>public DataService(ExampleClient exampleClient) {<br>        this.exampleClient = exampleClient;<br>    }<br><br>public String fetchData() {<br>        return exampleClient.getData();<br>    }<br>}</pre><h3>Why FeignClient is the Best Choice</h3><h3>1. Separation of Concerns</h3><p>Feign helps maintain a <strong>clean architecture</strong> by separating HTTP communication logic from business logic. Developers only need to define interfaces, while Feign handles request execution behind the scenes.</p><h3>2. Reduced Boilerplate Code</h3><p>Unlike OkHttp and RestTemplate, Feign eliminates repetitive code, making it easier to maintain and scale applications.</p><h3>3. Easy Integration with Spring Boot</h3><p>Feign works seamlessly with <strong>Spring Cloud</strong>, supporting automatic dependency injection and service discovery with <strong>Eureka</strong>.</p><h3>4. Built-in Error Handling &amp; Resilience</h3><p>Feign supports <strong>retries, error decoders, and circuit breakers</strong>, making microservices more resilient compared to using OkHttp or RestTemplate manually.</p><h3>Comparative Table: FeignClient vs. OkHttp vs. RestTemplate vs. WebClient</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*bPqzGUYyrbpGpiZJ7egpfw.png" /></figure><h3>Conclusion</h3><p>While <strong>OkHttp</strong>, <strong>RestTemplate</strong>, and <strong>WebClient</strong> each have their advantages, <strong>FeignClient</strong> offers a more intuitive and declarative approach for REST communication in <strong>Spring Boot</strong> applications. By using Feign, developers can eliminate repetitive boilerplate code, simplify error handling, and leverage Spring Cloud’s ecosystem efficiently.</p><p>If you’re building microservices with <strong>Spring Boot</strong>, consider replacing OkHttp and RestTemplate with FeignClient to enhance productivity and maintainability!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=685663c5a04c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[**Hexagonal Architecture : A Comprehensive Guide**]]></title>
            <link>https://nawress-rafrafi.medium.com/hexagonal-architecture-a-comprehensive-guide-ee35f15af88f?source=rss-9d054e8c100e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee35f15af88f</guid>
            <dc:creator><![CDATA[Nawress RAFRAFI]]></dc:creator>
            <pubDate>Fri, 23 Aug 2024 21:25:21 GMT</pubDate>
            <atom:updated>2024-08-23T21:41:53.250Z</atom:updated>
            <content:encoded><![CDATA[<h3>**Hexagonal Architecture : A Comprehensive Guide**</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7xCN8MIiiVQew7mFBlMHHA.jpeg" /></figure><h4>Introduction to Hexagonal Architecture</h4><p>If you’re a developer who’s faced the challenge of maintaining or refactoring a monolithic application, you’ve likely experienced the tight coupling of logic to frameworks. Hexagonal Architecture offers a remedy to this by organizing software around the business domain. This blog explains the Hexagonal Architecture pattern and how to implement it in a Spring Boot application.</p><h4>What is Hexagonal Architecture?</h4><blockquote>Hexagonal Architecture, also referred to as the Ports and Adapters pattern, is a design approach where the core business logic (domain) is kept independent from external dependencies, such as databases or third-party services. The idea is to allow the domain layer to stay agnostic of any technical details, fostering greater flexibility and maintainability.</blockquote><p>In traditional architectures, there is a tendency to intertwine business logic with frameworks and technologies. This makes it harder to adapt when frameworks evolve or new external integrations are required.</p><p><strong>Key Principles of Hexagonal Architecture</strong></p><ul><li><strong>Separation of Concerns</strong></li></ul><p>In Hexagonal Architecture, the code is cleanly separated into three layers: Domain, Application, and Adapters. This ensures that the business logic is kept separate from infrastructure details, such as user interfaces or databases.</p><ul><li><strong>Independence from Frameworks</strong></li></ul><p>The business logic should not depend on any framework or external system. Frameworks can come and go, but the domain logic remains stable and independent.</p><ul><li><strong>Portability and Flexibility</strong></li></ul><p>With Hexagonal Architecture, you can easily change external dependencies — such as replacing a database or a third-party API — without impacting your core business logic.</p><h4><strong>Structure of Hexagonal Architecture</strong></h4><ul><li><strong>Domain Layer: The Core of Business Logic</strong></li></ul><p>The domain layer is the heart of your application. It contains entities, value objects, and the core business logic without any external dependencies.</p><ul><li><strong>Application Layer: Handling Business Operations</strong></li></ul><p>The application layer acts as a mediator between the domain and external systems. It defines use cases and coordinates the execution of business rules.</p><ul><li><strong>Adapters Layer: Connecting to External Systems</strong></li></ul><p>Adapters act as the bridges between your application and the outside world, whether it’s a database, an external API, or a user interface.</p><h4><strong>Benefits of Using Hexagonal Architecture</strong></h4><ul><li><strong>Flexibility in Testing</strong></li></ul><p>By decoupling your business logic from external systems, Hexagonal Architecture makes it easier to write unit tests. You can test your core logic without the need for a database or network calls.</p><ul><li><strong>Future-Proofing Your Application</strong></li></ul><p>With the increasing pace of technology change, it’s essential to build software that can adapt. Hexagonal Architecture enables you to easily swap frameworks or external services without touching your core logic.</p><h4>Hexagonal Architecture in Spring Boot (<strong>Payment System )</strong></h4><ul><li><strong>Domain Layer: Defining Payment and Invoice Entities</strong></li></ul><p>In a payment system, the domain layer would define entities like `Payment` and `Invoice`, representing the core data models.</p><ul><li><strong>Application Layer: Implementing Payment Use Cases</strong></li></ul><p>The application layer would handle use cases like `ProcessPayment`, which coordinates the flow of information between the domain layer and the adapters.</p><ul><li><strong>Adapters Layer: Integrating Payment Gateways</strong></li></ul><p>An outbound adapter could handle communication with external payment gateways, ensuring the core business logic stays unaffected by the specifics of each gateway’s API.</p><p><strong>Below is an example project structure:</strong></p><pre>/src<br>  /main<br>    /java<br>      /com/yourcompany/paymentsystem<br>        /domain<br>          /models<br>            - Payment.java<br>            - Invoice.java<br>           /ports<br>              - PaymentRepository.java<br>              - InvoiceRepository.java<br>              - PaymentService.java<br>          <br>        /application<br>          - ProcessPaymentUseCase.java<br>          - PaymentCommand.java<br>          - PaymentQuery.java<br><br>        /adapters<br>          /inbound<br>            /rest<br>              - PaymentController.java<br>          /outbound<br>            /gateway<br>              - PaymentGateway.java<br>              - PaymentGatewayImpl.java<br>            /repository<br>              - PaymentRepositoryAdapter.java<br>              - InvoiceRepositoryAdapter.java<br>              <br>  /resources<br>    - application.yml</pre><p>Below is a schema illustrating how Hexagonal Architecture is structured with Spring Boot. This diagram provides a visual representation of how ports (interfaces) connect the core domain with external adapters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8my5KdxK9WmWj_YZ3JWj8Q.png" /></figure><p>As seen in the diagram, the domain is completely isolated from the external world, with only ports acting as intermediaries.</p><h4><strong>Conclusion</strong></h4><p>Hexagonal Architecture allows you to build scalable, adaptable, and well-structured applications. By decoupling the core business logic from frameworks, you ensure long-term maintainability and flexibility. Whether you’re building a simple CRUD application or a complex system with multiple integrations, Hexagonal Architecture can make your application more robust.</p><h4><strong>FAQs</strong></h4><p><strong>1. What is Hexagonal Architecture in simple terms?</strong></p><p>Hexagonal Architecture organizes your application so the core business logic is independent of external systems like databases or user interfaces. It achieves this by using ports and adapters as bridges.</p><p><strong>2. Why should I use Hexagonal Architecture ?</strong></p><p>Hexagonal Architecture improves the maintainability, scalability, and flexibility of your application by decoupling business logic from external systems.</p><p><strong>3. Can Hexagonal Architecture work with Spring Boot?</strong></p><p>Yes, Spring Boot is an excellent fit for Hexagonal Architecture due to its clear structure and support for creating layered applications.</p><p><strong>4. What are ports and adapters in Hexagonal Architecture?</strong></p><p>Ports are interfaces that expose the business logic, while adapters are implementations that handle communication between the business logic and external systems.</p><p><strong>5. How does Hexagonal Architecture improve testing?</strong></p><p>By decoupling business logic from external dependencies, Hexagonal Architecture makes it easier to test the core logic without relying on databases or external APIs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee35f15af88f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring Your Spring Boot App with Prometheus and Grafana: A Step-by-Step Guide]]></title>
            <link>https://nawress-rafrafi.medium.com/monitoring-your-spring-boot-app-with-prometheus-and-grafana-a-step-by-step-guide-6b93b50070d1?source=rss-9d054e8c100e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b93b50070d1</guid>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Nawress RAFRAFI]]></dc:creator>
            <pubDate>Mon, 30 Oct 2023 00:19:39 GMT</pubDate>
            <atom:updated>2023-10-30T00:19:39.579Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ScFhV2H_kZLIEjQT.png" /></figure><p>Monitoring the performance of your Spring Boot application is crucial for ensuring its optimal functionality. In this comprehensive guide, we’ll walk you through the process of setting up Prometheus and Grafana to monitor your Spring Boot app. Buckle up as we dive into each step with clear instructions and insightful screenshots.</p><h3>Why Prometheus and Grafana?</h3><h4>Prometheus: Your Robust Monitoring Solution</h4><p>Prometheus is an open-source monitoring and alerting toolkit designed for reliability and scalability. It excels at collecting and processing metrics, offering a powerful querying language and flexible alerting mechanisms. With Prometheus, you gain real-time visibility into the performance and health of your Spring Boot application.</p><h4>Grafana: Visualization at Its Finest</h4><p>Grafana complements Prometheus by providing stunning visualizations and interactive dashboards. Its user-friendly interface allows you to create custom dashboards, making it easy to interpret complex metrics. Grafana turns raw data into actionable insights, empowering you to make informed decisions about your application’s performance.</p><p>Now, let’s embark on the journey of integrating these powerful tools into your Spring Boot application.</p><h3>Step 1: Update Your pom.xml</h3><p>Before delving into the configurations, ensure that you’ve added the necessary dependencies to your pom.xml file. Include the Spring Boot Actuator and Prometheus dependencies:</p><pre>&lt;dependencies&gt;<br>    &lt;!-- Other dependencies --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;io.micrometer&lt;/groupId&gt;<br>        &lt;artifactId&gt;micrometer-registry-prometheus&lt;/artifactId&gt;<br>        &lt;version&gt;x.x.x&lt;/version&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><h3>Step 2: Customize Your Spring Boot Application</h3><p>To kick off our monitoring journey, start by customizing your application.properties file. Open it and add the following lines:</p><pre>management.endpoint.metrics.enabled=true<br>management.endpoints.web.exposure.include=*</pre><p>These configurations expose the necessary metrics for Prometheus to scrape.</p><h4>Metrics Overview</h4><p>After making these changes, your Spring Boot app will expose various metrics, providing a comprehensive overview of its internal workings. These metrics are vital for understanding your application’s performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0jdfnUD_J0s00TppFAEOmQ.png" /></figure><h3>Step 3: Set Up Prometheus Container</h3><p>Next, let’s run a Prometheus container. Execute the following command:</p><pre>docker run --name=prometheus -p 9090:9090 prometheus</pre><p>Now, configure Prometheus by editing the prometheus.yml file. Use the following content:</p><pre>scrape_configs:<br>  - job_name: &#39;prometheus&#39;<br>    scrape_interval: 5s<br>    static_configs:<br>      - targets: [&#39;192.168.33.10:9090&#39;]<br><br>  - job_name: &#39;spring-actuator&#39;<br>    metrics_path: &#39;/actuator/prometheus&#39;<br>    scrape_interval: 2s<br>    static_configs:<br>      - targets: [&#39;192.168.33.10:8082&#39;]<br>        labels:<br>          group: &#39;production&#39;</pre><p>This setup tells Prometheus to scrape metrics from both its own instance and your Spring Boot app.</p><h4>Metrics on Prometheus</h4><p>After configuring Prometheus, you can view the scraped metrics directly on Prometheus. This provides a detailed look at the raw metrics data before any visualization or interpretation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lKx51lv2Uj9yCpXYVdgtLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VBQ8CbofRwBhoKsTmVyDqA.png" /></figure><h3>Step 4: Configure Grafana</h3><p>Now, let’s configure Grafana for visualizing our metrics. Start by running a Grafana container:</p><pre>docker run -d --name grafana -p 3000:3000 grafana/grafana</pre><p>Access Grafana at http://network:3000 (default credentials are admin/admin).</p><p>Create a new Prometheus data source and use the URL <a href="http://192.168.33.10:9090.">http://192.168.33.10:9090.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*fbnOY6eohJliS39RjwEZwA.gif" /></figure><p>Now, import a dashboard or create your own to visualize the metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PPv-4mTTyHWkQWrMR3v6jA.png" /></figure><h3>Conclusion: Monitoring Excellence Achieved</h3><p>Congratulations! You’ve successfully configured Prometheus and Grafana to monitor your Spring Boot application. With clear metrics and insightful dashboards, you have a powerful toolset for optimizing performance and ensuring the smooth operation of your application.</p><p>Whether you’re keeping an eye on resource usage, tracking response times, or identifying potential bottlenecks, this monitoring setup empowers you with valuable insights. Keep monitoring, keep optimizing, and keep your Spring Boot app running at its best.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b93b50070d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Kafka : A Step-by-Step Guide]]></title>
            <link>https://nawress-rafrafi.medium.com/getting-started-with-kafka-a-step-by-step-guide-a80ebc0e6435?source=rss-9d054e8c100e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a80ebc0e6435</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[kafka-streams]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Nawress RAFRAFI]]></dc:creator>
            <pubDate>Tue, 28 Mar 2023 23:15:07 GMT</pubDate>
            <atom:updated>2023-03-29T03:11:39.983Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WK22345edom5aVHw5saJUw.png" /></figure><h3>Introduction</h3><p>In today’s age of data-driven applications, handling large volumes of data in real-time has become a necessity. Apache Kafka, a distributed streaming platform, has emerged as the go-to solution for real-time data streaming. It is fast, scalable, fault-tolerant, and easily integrates with various microservices frameworks. In this blog, we will discuss how to set up Kafka step by step.</p><h3>Prerequisites</h3><p>Before you get started, you’ll need to make sure you have the following installed:</p><ul><li>Java Development Kit (JDK) version 8 or later</li><li>Spring Boot 2.5.0 or later</li><li>Apache Kafka version 2.8.0 or later</li></ul><h3>Step 1: Download Apache Kafka</h3><p>you’ll need to download Apache Kafka. You can download the latest version from the <a href="https://kafka.apache.org/downloads">Apache Kafka website</a>. Make sure to download the binary version for your operating system and architecture.</p><p>Once you’ve downloaded the binary, extract the files to a directory of your choice.</p><h3>Step 2: Start ZooKeeper</h3><p>Apache Kafka requires a ZooKeeper instance to manage the cluster configuration. To start ZooKeeper, open a new command prompt and navigate to the directory where you extracted the Kafka binary.</p><p>Then, run the following command:</p><pre>.\bin\windows\zookeeper-server-start.bat .\config\zookeeper.properties</pre><p>This will start ZooKeeper on your machine.</p><h3>Step 3: Start Kafka</h3><p>With ZooKeeper running, you can now start Kafka itself. Open a new command prompt and navigate to the directory where you extracted the Kafka binary.</p><p>Then, run the following command:</p><pre>.\bin\windows\kafka-server-start.bat .\config\server.properties</pre><p>This will start the Kafka broker on your machine.</p><h3>Step 4: Create a Kafka Topic</h3><p>To test that Kafka is working correctly, you’ll need to create a topic. A topic is a category or feed name to which messages are published.</p><p>Open a new command prompt and navigate to the directory where you extracted the Kafka binary. Then, run the following command:</p><pre>.\bin\windows\kafka-topics.bat --create --bootstrap-server localhost:9092 --replication-factor 1 --partitions 1 --topic my-topic</pre><p>This will create a topic named “my-topic”.</p><h3>Step 5: Publish Messages to the Kafka Topic</h3><p>To publish messages to the Kafka topic, you’ll need to create a producer. Open a new command prompt and navigate to the directory where you extracted the Kafka binary.</p><p>Then, run the following command to start the producer:</p><pre>.\bin\windows\kafka-console-producer.bat --broker-list localhost:9092 --topic my-topic</pre><p>This will start the producer and allow you to enter messages to be published to the “my-topic” topic.</p><h3>Step 6: Consume Messages from the Kafka Topic</h3><p>To consume messages from the Kafka topic, you’ll need to create a consumer. Open a new command prompt and navigate tothe directory where you extracted the Kafka binary.</p><p>Then, run the following command to start the consumer:</p><pre>.\bin\windows\kafka-console-consumer.bat --bootstrap-server localhost:9092 --topic my-topic --from-beginning</pre><p>This will start the consumer and display any messages that have been published to the “my-topic” topic.</p><p>Congratulations! You have successfully set up Kafka on your machine and tested that it is working correctly. Now, you can integrate Kafka into your application and begin processing real-time data feeds.</p><h3>Integrating Kafka with Spring Boot</h3><p>To start with, we need to set up Kafka configuration in our Spring Boot application. This configuration can be defined in the application.properties file or the application.yml file, depending on your preference.</p><p>Here’s an example of how to set up Kafka configuration in the application.properties file:</p><pre>spring.kafka.bootstrap-servers=localhost:9092<br>spring.kafka.consumer.group-id=my-group</pre><p>In this example, we define the Kafka bootstrap servers that our application will connect to. We also specify the consumer group ID that our Kafka listener will belong to.</p><h3>Creating a Kafka Listener</h3><p>To create a Kafka listener in our Spring Boot application, we need to annotate a method with the @KafkaListener annotation. Here&#39;s an example of how to create a Kafka listener that will listen for messages published to the &quot;my-topic&quot; topic:</p><pre>@Service<br>public class KafkaConsumer {<br>    <br>    @KafkaListener(topics = &quot;my-topic&quot;, groupId = &quot;my-group&quot;)<br>    public void consume(String message) {<br>        System.out.println(&quot;Consumed message: &quot; + message);<br>    }<br>}</pre><p>In this example, we define a KafkaConsumer service class and annotate the consume method with @KafkaListener. This method will receive a String parameter that represents the message that was published to the &quot;my-topic&quot; topic.</p><h3>Creating a Kafka Producer</h3><p>To create a Kafka producer in our Spring Boot application, we need to use the KafkaTemplate class provided by the Spring Kafka library. Here&#39;s an example of how to create a Kafka producer that will publish a message to the &quot;my-topic&quot; topic:</p><pre>@RestController<br>public class KafkaProducer {<br>    <br>    @Autowired<br>    private KafkaTemplate&lt;String, String&gt; kafkaTemplate;<br>    <br>    @PostMapping(&quot;/publish&quot;)<br>    public String sendMessage(@RequestParam(&quot;message&quot;) String message) {<br>        kafkaTemplate.send(&quot;my-topic&quot;, message);<br>        return &quot;Message published successfully!&quot;;<br>    }<br>}</pre><p>In this example, we define a KafkaProducer REST controller class that is responsible for publishing messages to the &quot;my-topic&quot; topic. We inject a KafkaTemplate bean into the class using the @Autowired annotation, and use the send method to publish a message to the topic.</p><h3>Testing the Kafka Listener and Producer</h3><p>To test that our Kafka listener and producer are working correctly, we can start our Spring Boot application and use the Kafka console producer to publish a message to the “my-topic” topic. Then, we should see the message “Consumed message: [your message]” printed to the console by the KafkaConsumer class.</p><p>We can also test our Kafka producer by sending a POST request to the /publish endpoint of our application with a message in the message parameter. If everything is set up correctly, we should see the message &quot;Message published successfully!&quot; returned by the endpoint, and the message should be visible in the Kafka console consumer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hy3yp1GBCafvvZXs78CBfw.jpeg" /></figure><h3>Conclusion</h3><p>In this blog, we went over how to set up Kafka configuration, create a Kafka listener, and create a Kafka producer in a Spring Boot application. By following these steps, you can integrate Kafka with your Spring Boot application and begin processing real-time data feeds in a scalable and fault-tolerant manner.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a80ebc0e6435" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ML Ops with Docker & Jenkins]]></title>
            <link>https://nawress-rafrafi.medium.com/ml-ops-with-docker-jenkins-fbabbe6969a2?source=rss-9d054e8c100e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbabbe6969a2</guid>
            <category><![CDATA[jenkins-pipeline]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Nawress RAFRAFI]]></dc:creator>
            <pubDate>Sun, 24 Apr 2022 13:33:25 GMT</pubDate>
            <atom:updated>2022-04-25T11:44:15.453Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qoEFWKEKX6LHDcWCWi5ZmA.png" /></figure><h3>Introduction</h3><p>The goal of this post is to provide an example of how we can use DevOps tools like Docker and Jenkins to automate a machine learning pipeline.</p><p>So, we will create a step-by-step machine learning pipeline in which we will predict heart disease using the logistic regression algorithm and returns test accuracy whenever we make a change to our <a href="https://github.com/RafrafiNawress/MLOps-Docker-Jenkins.git">repository in GitHub</a>.</p><p><strong>According to Google documentation</strong></p><blockquote>MLOps stands for Machine Learning Operations. MLOps is a core function of Machine Learning engineering, focused on streamlining the process of taking machine learning models to production, and then maintaining and monitoring them. MLOps is a collaborative function, often comprising data scientists, devops engineers, and IT.</blockquote><blockquote>MLOps is a useful approach for the creation and quality of machine learning and AI solutions. By adopting an MLOps approach, data scientists and machine learning engineers can collaborate and increase the pace of model development and production, by implementing continuous integration and deployment (CI/CD) practices with proper monitoring, validation, and governance of ML models.</blockquote><p>📌NOTE: Since the purpose of this article is to automate a machine learning pipeline, the explanation of data analysis is out of scope. So there is no requirement to understand what is being done here.</p><p><strong>Alright, so let’s begin!</strong></p><h3>Setting the strategy</h3><p>Now, before start coding, there is no doubt that it is important to figure out exactly the right plan. In our project there are three python scripts: it’ s obvious from their names what they do :) Also, we have the raw data set: Heart.csv, and a Dockerfile.</p><p>The first thing we should try to do is to figure out the inputs and outputs of our Python scripts are, so that you can understand the workflow of this project is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*_qaGv5Q_azBu457fcwFAVg.png" /></figure><p>There are 3 concepts on which Docker is based: Containers, Images and Dockerfiles. Is indispensable to understand what they do in order to work with Docker. If you are not familiar with them, here is an intuitive definition:</p><ul><li>Containers: A standard unit of software that packages everything you need to run your application (dependencies, environment variables…)</li><li>Dockerfile: This is a file in which you define everything you want to be inside of a container.</li><li>Image: This is the blueprint needed for running a container. You build an image by executing a Dockerfile.</li></ul><p>So, in order to use Docker, you will follow this steps:</p><ol><li>Define a Dockerfile</li><li>Build the image</li><li>Run a container</li><li>Run commands inside the container</li></ol><p><strong>Let’s go step by step:</strong></p><h4>Defining the Dockerfile</h4><p>Here we have to define everything we need to run the pipeline. You can have a look at the Dockerfile in the repository, but if you are not familiar with the syntax it may be overwhelming at first. So what we are going to do here is talk about what we want to specify in it and have a look at the syntax step by step.</p><ol><li>First, we need to specify where we want to run our pipeline. For our pipeline we will just use an image of jupyter called jupyter/scipy-notebook.</li><li>Then, we have to install some packages. For this purpose we use the command RUN</li></ol><p>📌NOTE: It may not make much sense now, but we will need jq in order to access values inside json files, and joblib in order to serialize and deserialize the model.</p><p>3. Create the folders (model, raw_data, processed_data and results).</p><p>4. Specify the order in which the scripts and raw data from our repository are copied. These will be copied into our container once we have created it.</p><p>We end up with a docker file such as this :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e13ca2764ed20d1ed0bac182c6feb4c/href">https://medium.com/media/6e13ca2764ed20d1ed0bac182c6feb4c/href</a></iframe><h4>Building the image</h4><p>Once we have our Dockerfile specified, we can build the image. The command to do this is:</p><pre>docker build -t heartDisease-model .</pre><p>We specify the name of the image with -t heartDisease-model (-t stands for tag) and the path of the Dockerfile with .</p><p>👉 Docker automatically picks the file named &quot;Dockerfile&quot;.</p><h4>Running a container</h4><p>Now that we have an image (a blueprint for a container), we can build a container with the following command :</p><pre>docker run -d --name model heartDisease-model</pre><h4>Running commands inside the container</h4><p>Now that we have our container running, we can run commands inside it by using docker exec. In this project, we need to execute the scripts in order and then show the results. We can do that by the following commands:</p><ul><li>Run preprocessing.py</li></ul><pre>docker container exec model python3 preprocessing.py</pre><ul><li>Run train.py</li></ul><pre>docker container exec model python3 train.py</pre><ul><li>Run test.py</li></ul><pre>docker container exec model python3 test.py</pre><ul><li>Show validation accuracy and test accuracy</li></ul><pre>docker container exec model cat /home/jovyan/results/train_metadata.json /home/jovyan/results/test_metadata.json</pre><h3>Automating a ML pipeline with Jenkins</h3><p>For this step we will use Jenkins, a widely famous open source automation server that provides an endless list of plugins to support building, deploying and automating any project.</p><p>For this time, we will build the steps of the pipeline using a pipeline script.</p><p>In Jenkins, go to New Item,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*oYlhsDpJ-DuVxfnJoSchkQ.png" /></figure><p>then give it a name and choose pipeline project, then click OK.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*IcNxFuChjDvIZBonSjgK5w.png" /></figure><p>The first step in the pipeline is to get the project from our GitHub repository.</p><p>In the pipeline script we will define the same steps we talked about (from building the image to show the validation and test accuracy) :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2477f4cb565c3aa333d6e2dc0180b2fb/href">https://medium.com/media/2477f4cb565c3aa333d6e2dc0180b2fb/href</a></iframe><p>Click save and there we have it! Our pipeline is now fully automated!</p><p>📌NOTE: In order to see the output of the pipeline , click on the first number in the Build section at the bottom left and select Console Output. For the last step, you should see the validation and test accuracy.</p><h4>Question for Docker beginners: What is the point of what we have done?</h4><p>If you are not familiar with Docker, now you might be asking: Ok, This is all good stuff, but at the end I just have my model and my predictions. I can also get them by running my python code and with no need to learn Docker so, what’s the point of all this?</p><p>I’m glad you asked 😎 .</p><p>First, having your Machine Learning models in a Docker container is really useful in order to deploy that model into a production environment. As an example, How many times have you seen code on a tutorial or in a repository that you have tried to replicate, and when running the same code in your machine your screen has filled with red? If we don’t like to pass through that, imagine what our customers might feel. With Docker containers, this problem is solved.</p><p>Another reason why Docker is really useful is probably the same reason why you are reading this: to help automating an entire pipeline.</p><h3>Conclusion</h3><p>You can now play with it: try making a commit in GitHub and see how every step goes automatically. The project is available on <a href="https://github.com/RafrafiNawress/MLOps-Docker-Jenkins.git">my GitHub repository</a>.</p><p>I hope you have learned a lot! Thanks for reading!</p><h3>References</h3><p>databricks : <a href="https://databricks.com/glossary/mlops">https://databricks.com/glossary/mlops</a></p><p>Medium : <a href="https://towardsdatascience.com/mlops-with-docker-and-jenkins-automating-machine-learning-pipelines-a3a4026c4487">https://towardsdatascience.com/mlops-with-docker-and-jenkins-automating-machine-learning-pipelines-a3a4026c4487</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbabbe6969a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular — Spring Simple CRUD Application]]></title>
            <link>https://nawress-rafrafi.medium.com/angular-spring-simple-crud-application-1f62f6ebb1a6?source=rss-9d054e8c100e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f62f6ebb1a6</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Nawress RAFRAFI]]></dc:creator>
            <pubDate>Fri, 11 Jun 2021 21:17:38 GMT</pubDate>
            <atom:updated>2023-04-03T12:45:22.058Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular — Spring Simple CRUD Application</h3><p>In this tutorial, we will build a CRUD (create-read-update-delete) web application.</p><p>We will use Spring Boot to handle the back-end part and Angular to handle the front-end part, and they will communicate with each other using a REST API. Then on the back end, we will have a database and we will have full CRUD support for the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/0*69C4SWVvcLAc4xYm.png" /></figure><h4>Working of Application</h4><ul><li>Once we deployed our application on the server, a product form generates at the web browser.</li><li>The form facilitates to add and view products.</li><li>On clicking, add product button, the page display a form where we can add a product by filling the required details and submit them.</li><li>Using view product link, we can fetch the details of the products list. Here, each product also contains update and delete link.</li><li>Therefore, we can update the details of the product and delete them from the database.</li><li>Once completed, provide the URL http://localhost:4200/ at the web browser.</li></ul><h4>Tools to be used</h4><ul><li>Use any IDE to develop the Spring Boot project. It may be STS/IntelliJ/Eclipse… Here, we are using STS (Spring Tool Suite).</li><li>MySQL for the database.</li><li>Use any IDE to develop the Angular project. It may be Visual Studio Code/Sublime. Here, we are using Visual Studio Code.</li><li>Server: Tomcat.</li></ul><h4>Create Database</h4><p>Let’s create a database “crud-tuto”. There is no need to create a table as Hibernate automatically created it.</p><h3>Spring Boot Application</h3><p>First, we need to create a new Spring Starter project with the following structure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*2VtUsZEClVw79zYknUI5QA.png" /></figure><p>We have to add these dependencies to our pom.xml file, then execute <strong><em>maven update</em></strong> :</p><pre>&lt;parent&gt;<br>  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;<br>  &lt;version&gt;2.7.9&lt;/version&gt;<br>  &lt;relativePath /&gt; &lt;!-- lookup parent from repository --&gt;<br> &lt;/parent&gt;<br> &lt;groupId&gt;tn.spring&lt;/groupId&gt;<br> &lt;artifactId&gt;crud-tuto&lt;/artifactId&gt;<br> &lt;version&gt;1.0&lt;/version&gt;<br> &lt;name&gt;crud-tuto&lt;/name&gt;<br> &lt;description&gt;Spring Boot&lt;/description&gt;<br> &lt;properties&gt;<br>  &lt;java.version&gt;8&lt;/java.version&gt;<br> &lt;/properties&gt;<br> &lt;dependencies&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;mysql&lt;/groupId&gt;<br>   &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;<br>   &lt;scope&gt;runtime&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-devtools&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>   &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br> &lt;/dependencies&gt;</pre><p>Next step, we have to develop the entity for the product.</p><pre>@Entity<br>@Getter<br>@Setter<br>@AllArgsConstructor<br>@NoArgsConstructor<br>@ToString<br>@Builder<br>public class Product implements Serializable {<br><br> private static final long serialVersionUID = 1L;<br> @Id<br> @GeneratedValue(strategy = GenerationType.IDENTITY)<br> private Long id_product;<br> private String title;<br> private String price;<br> private String quantity;<br> <br>}</pre><p>Since we will require basic CRUD functionality on Product entity, we should define a ProductRepository interface as well:</p><pre>public interface ProductRepository extends JpaRepository&lt;Product, Long&gt; {}</pre><p>Next, we will create the service layer using the annotation @Service.</p><pre>@Service<br>@AllArgsConstructor<br>@Slf4j<br>public class ProductServiceImpl implements IProductService {<br><br> private final ProductRepository productRepository;<br> <br> @Override<br> public Product addProduct(Product p) {<br>  if (p.getTitle() == null || p.getTitle().isEmpty()) {<br>   throw new IllegalArgumentException(&quot;Product title cannot be empty&quot;);<br>  }<br>  try {<br>   return productRepository.save(p);<br>  } catch (Exception e) {<br>   throw new RuntimeException(&quot;Failed to add product&quot;, e);<br>  }<br> }<br><br> @Override<br> public Product editProduct(Product p)  throws RuntimeException {<br><br>  if (p.getId_product() == null) {<br>   throw new IllegalArgumentException(&quot;Product ID cannot be null&quot;);<br>  }<br>  if (p.getTitle() == null || p.getTitle().isEmpty()) {<br>   throw new IllegalArgumentException(&quot;Product title cannot be empty&quot;);<br>  }<br>  try {<br>   return productRepository.save(p);<br>  } catch (Exception e) {<br>   throw new RuntimeException(&quot;Failed to update product&quot;, e);<br>  }<br> }<br> @Override<br> public void deleteProduct(Long idProduct) {<br>  Optional&lt;Product&gt; product = productRepository.findById(idProduct);<br><br>  product.ifPresent(p -&gt; {<br>   productRepository.delete(p);<br>   log.info(&quot;Product with id &quot; + idProduct + &quot; has been deleted&quot;);<br>  });<br><br> }<br> @Override<br> public List&lt;Product&gt; retrieveAll() {<br>  return productRepository.findAll();<br> }<br><br>}</pre><p>@AllArgsConstructor inject the repository in the service.<br>These methods we implemented will call methods already existing in the repository layer.</p><p>Now, let’s implement the REST API. In this case, it’s just a simple REST controller.</p><pre>@CrossOrigin(origins = &quot;http://localhost:4200&quot;)<br>@RestController<br>@AllArgsConstructor<br>public class ProductRestController {<br> private  final IProductService productService;<br><br> // http://localhost:8081/all-products<br> @GetMapping(&quot;/all-products&quot;)<br> public List&lt;Product&gt; getProducts() {<br>  return productService.retrieveAll();<br> }<br><br> // http://localhost:8081/add-product<br> @PostMapping(&quot;/add-product&quot;)<br> public Product addProduct(@RequestBody Product p) {<br>  return productService.addProduct(p);<br> }<br> <br> // http://localhost:8081/edit-product<br> @PutMapping(&quot;/edit-product&quot;)<br> public Product editProduct(@RequestBody Product p) {<br>  return productService.editProduct(p);<br> }<br><br> // http://localhost:8081/delet-product/id<br>  @DeleteMapping(&quot;/delete-product/{idProduct}&quot;)<br>  public void deleteProduct(@PathVariable(&quot;idProduct&quot;) Long id) {<br>    productService.deleteProduct(id);<br>  }<br>}</pre><p>Nothing is complex in the definition of the ProductRestController class.</p><p>The only implementation detail worth noting here, of course, is the use of the @CrossOrigin annotation. As the name implies, this annotation allows cross-origin resource sharing (CORS) on the server.</p><p>This annotation is necessary here, because we deploy our Angular frontend to <a href="http://localhost:4200/">http://localhost:420</a>0 and our backend to <a href="http://localhost:8080/">http://localhost:808</a>9, the browser would otherwise deny requests from one to the other.</p><h3>The Angular Application</h3><p>In this tutorial, we are using the following versions :</p><ul><li>Angular CLI : 12.0.1</li><li>Node : 14.17.0</li><li>npm : 6.14.13</li></ul><p>First we create our front project using the command : ng new ProjectName.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*d6NWkerzgJYiah7mhLh6wA.png" /></figure><p>In order to use bootstrap in our project :</p><ul><li>We use the following command : npm install bootstrap</li><li>Then we have to add “node_modules/bootstrap/dist/css/bootstrap.css” in angular.json file for styles.</li></ul><p>Since our Angular application will fetch from and persist <em>Product </em>entity in the database, let’s implement a simple model with TypeScript using :</p><ul><li>ng generate class product</li></ul><pre>export class Product {<br>    id_product : any;<br>    title : any;<br>    price : any;<br>    quantity : any;<br>    <br>}</pre><p>The aim of this class is to mapping the specified fields to the fields of the Spring entity class.</p><p>Now that our client-side domain Product class is already defined, let’s implement a service class that executes the defined requests to the <a href="http://localhost:8080/users">http://localhost:808</a>9 endpoint.</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class ProductService {<br>  readonly API_URL = &#39;http://localhost:8089&#39;;<br>  <br>  constructor(private httpClient: HttpClient) { }<br><br>  getAllProducts() {<br>    return this.httpClient.get(`${this.API_URL}/all-products`)<br>  }<br>  addProduct(product : any) {<br>    return this.httpClient.post(`${this.API_URL}/add-product`, product)<br>  }<br>  editProduct(product : any){<br>    return this.httpClient.put(`${this.API_URL}/edit-product`, product)<br>  }<br>  deleteProduct(idProduct : any){<br>    return  this.httpClient.delete(`${this.API_URL}/delete-product/${idProduct}`)<br>  }<br><br>}</pre><blockquote><strong>This will allow us to encapsulate access to the REST controller in a single class, which we can reuse throughout the entire application</strong>.</blockquote><p>In this case, the <em>ProductService</em> class is the thin middle-tier between the REST service and the application’s presentation layer. Therefore, we need to define a component responsible for rendering the list of <em>Product </em>entity persisted in the database.</p><p>Let’s open a terminal console, then generate a product component:</p><ul><li>ng generate component product</li></ul><p>Angular CLI will generate an empty component class that implements the <a href="https://angular.io/api/core/OnInit"><em>ngOnInit</em></a> interface. The interface declares a hook <em>ngOnInit()</em> method, which Angular calls after it has finished instantiating the implementing class, and after calling its constructor, too.</p><p>Let’s refactor the class so that it can take a <em>ProductService</em> instance in the constructor :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b82a33f2607e5a767055d92ad9d82e80/href">https://medium.com/media/b82a33f2607e5a767055d92ad9d82e80/href</a></iframe><p>Additionally, we need to edit the component’s HTML file, product.component.html<em>,</em> to create the table that displays the list of entity :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*tDWhjDcb8PHXAcAahtRFKA.png" /></figure><p><strong>Notice the use of the *ngFor directive. </strong>The directive is called a repeater, and we can use it for iterating over the contents of a variable and iteratively rendering HTML elements. In this case, we used it for dynamically rendering the table’s rows.</p><p>In addition, we used variable interpolation for showing the title, price and quantity of each product.</p><p>In order to persist a new product in the database, we need to to edit product.component.html file and create HTML form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*H5CIFpf83ZJzPz3YOdKBOw.png" /></figure><p><strong>The ngModel directive gives us two-way data binding functionality between the form controls and the client-side domain model — the User class</strong>.</p><p>This means that data entered in the form input fields will flow to the model — and the other way around. Changes in both elements will be reflected immediately via DOM manipulation.</p><p>Next, we need to edit the <em>app.module.ts</em> file, so Angular can import all the required modules, components, and services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*l1UF8cacmy0DYxkeWs3AIw.png" /></figure><h3>Running the Application</h3><p>Finally, we’re ready to run our application.</p><p>To accomplish this, let’s first run the Spring Boot application, so the REST service is alive and listening for requests.</p><p>Once the Spring Boot application has been started, let’s open a command console and type the following command:</p><ul><li>ng serve — open</li></ul><p>This will start Angular’s live development server and also open the browser at <a href="http://localhost:4200.">http://localhost:4200.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8oJ4zoWnUiNQG-ylEUNVQ.png" /></figure><p>By clicking on “Add product” the following form displayed to add a new product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EtKHChX-7b4bI_oTdqAYgA.png" /></figure><h3>Conclusion</h3><p>In this tutorial, <strong>we learned how to build a basic web application with Spring Boot and Angular</strong>.</p><p>All the code samples shown in this tutorial are available <a href="https://github.com/RafrafiNawress/Simple-CRUD-Angular-Spring">over on GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f62f6ebb1a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>