<?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 Habtamu Tesfie on Medium]]></title>
        <description><![CDATA[Stories by Habtamu Tesfie on Medium]]></description>
        <link>https://medium.com/@habtamutesfie?source=rss-f42f01f8cee8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mLni7tLtF8LKs2n-5ft3VA.jpeg</url>
            <title>Stories by Habtamu Tesfie on Medium</title>
            <link>https://medium.com/@habtamutesfie?source=rss-f42f01f8cee8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 06:31:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@habtamutesfie/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[Implementing a Robust Microservices Solution with Spring Cloud Gateway]]></title>
            <link>https://medium.com/@habtamutesfie/implementing-a-robust-microservices-solution-with-spring-cloud-gateway-cd9364a75f69?source=rss-f42f01f8cee8------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd9364a75f69</guid>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Habtamu Tesfie]]></dc:creator>
            <pubDate>Sun, 25 Oct 2026 09:10:34 GMT</pubDate>
            <atom:updated>2026-10-25T09:10:34.231Z</atom:updated>
            <content:encoded><![CDATA[<h4>Brokers, circuit breakers, service discovery, tracing and monitoring</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YF-dC2PagE_r-R84.jpg" /></figure><p>In today’s dynamic and interconnected digital landscape, building resilient and scalable microservices architecture is not just a trend but a necessity. As businesses strive for agility and efficiency, the implementation of robust frameworks like Spring Cloud Gateway becomes pivotal. Coupled with sophisticated components such as brokers, circuit breakers, service discovery, and distributed tracing systems, this approach promises to revolutionize the way applications are developed, deployed, and maintained.</p><p>In this article, we delve into the intricacies of implementing such a comprehensive architecture. From harnessing the power of Spring Cloud Gateway for efficient API management to leveraging robust brokers for asynchronous communication, we explore how each component contributes to the overall resilience and scalability of your microservices ecosystem. Furthermore, we uncover the pivotal role of circuit breakers in maintaining system integrity under duress and the transformative impact of distributed tracing systems on debugging and performance optimization.</p><p>Join us on a journey through the evolving landscape of microservices architecture, where cutting-edge technologies converge to elevate your applications to new heights of reliability and efficiency. By understanding and implementing these components effectively, you pave the way for a future-ready infrastructure that not only meets but exceeds the demands of modern digital enterprise.</p><h3>Prerequisites</h3><p>Before you begin, ensure you have the following:</p><ul><li><strong>Java 17:</strong> Installed on your development machine.</li><li><strong>Maven 3.8.5:</strong> Dependency management tool for Java projects.</li><li><strong>Basic Understanding of Spring Boot:</strong> Knowledge of how to create Spring Boot applications, define dependencies, and configure application properties.</li></ul><h3>Creating the Product Service</h3><h4>Step 1: Setting Up the Project</h4><p>1. Initialize a Spring Boot Project: You can use Spring Initializr (<a href="https://start.spring.io/">https://start.spring.io/</a>) or your IDE to create a new Spring Boot project with the following dependencies:</p><ul><li><strong>Spring Web</strong></li><li><strong>Spring Data MongoDB</strong></li><li><strong>Lombok</strong> (for automatic generation of boilerplate code)</li></ul><p>2. Configure MongoDB: Ensure MongoDB is installed and running locally. Update your application.properties with MongoDB configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LogVrhy8PXZ8fOFp.png" /></figure><h4>Step 2: Implementing the Product Service</h4><p>The Product Service is responsible for managing product information, including creating and retrieving products. This service is implemented using the following components:</p><p>1. <strong>Controller</strong>:</p><ul><li>The ProductController is the entry point for handling HTTP requests related to product operations.</li><li>It provides endpoints to create a new product and to retrieve all products.</li></ul><p>2. <strong>Service</strong>:</p><ul><li>The ProductService contains the business logic for managing products.</li><li>It interacts with the database via the ProductRepository to save new products and fetch all existing products.</li></ul><p>3. <strong>Repository</strong>:</p><ul><li>The ProductRepository is an interface that extends MongoRepository, providing methods for CRUD operations on the product collection in MongoDB.</li></ul><p>Please refer to the GitHub link provided for the implementation of the product service: <a href="https://github.com/HabtamuTesfie/microservices/tree/master/product-service">Github</a></p><h3>Creating the Inventory Service</h3><h4>Step 1: Setting Up the Project</h4><p>1) Initialize a Spring Boot Project: Start by creating a new Spring Boot project using Spring Initializr (<a href="https://start.spring.io/">https://start.spring.io/</a>) or your IDE. Include the following dependencies in your pom.xml:</p><ul><li><strong>Spring Web:</strong> Enables building web applications using Spring MVC.</li><li><strong>Spring Data JPA:</strong> Provides support for working with relational databases using Java Persistence API (JPA).</li><li><strong>MySQL Driver:</strong> JDBC driver for MySQL to connect Spring Boot application with MySQL database.</li><li><strong>Lombok:</strong> Simplifies Java code by reducing boilerplate code (optional, but recommended).</li></ul><p>2) Configure MySQL Database: Ensure MySQL is installed and running locally. Update your application.properties with MySQL configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/0*EHg5bSoIzwvPsjMv.png" /></figure><h4>Step 2: Implementing the Inventory Service</h4><p>The Inventory Service is responsible for managing inventory information, including checking stock availability for products. This service is implemented using the following components:</p><p>1. <strong>Controller</strong>:</p><ul><li>The InventoryController is the entry point for handling HTTP requests related to inventory operations.</li><li>It provides an endpoint to check the stock availability of products by SKU codes.</li></ul><p>2. <strong>Service</strong>:</p><ul><li>The InventoryService contains the business logic for managing inventory.</li><li>It interacts with the database via the InventoryRepository to fetch inventory details and check stock availability.</li></ul><p>3. <strong>Repository</strong>:</p><ul><li>The InventoryRepository is an interface that extends JpaRepository, providing methods for CRUD operations on the inventory table in the MySQL database.</li><li>It includes a method to find inventory items by their SKU codes.</li></ul><p>Please refer to the GitHub link provided for the implementation of the Inventory service: <a href="https://github.com/HabtamuTesfie/microservices/tree/master/inventory-service">Github</a></p><h3>Creating the Order Service</h3><h4>Step 1: Setting Up the Project</h4><p>1. Initialize a Spring Boot Project: use Spring Initializr (<a href="https://start.spring.io/">https://start.spring.io/</a>) or your preferred IDE to create a new Spring Boot project. Include the following dependencies in your pom.xml:</p><ul><li><strong>Spring Web:</strong> To build web applications using Spring MVC.</li><li><strong>Spring Data JPA:</strong> To interact with relational databases using JPA.</li><li><strong>MySQL Driver:</strong> To connect the Spring Boot application with a MySQL database.</li><li><strong>Lombok:</strong> To reduce boilerplate code by using annotations for generating getters, setters, and constructors automatically.</li></ul><p>2. Configure MySQL:</p><ul><li>Ensure MySQL is installed and running locally.</li></ul><p>Update your application.properties file with the MySQL configuration details to establish a connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/0*-rQ0VCRrB0iPyQUB.png" /></figure><h4>Step 2: Implementing the Order Service</h4><p>The Order Service is responsible for managing orders, including placing new orders and verifying stock availability through the Inventory Service. This service is implemented using the following components:</p><p><strong>1. Controller:</strong></p><ul><li>The OrderController is the entry point for handling HTTP requests related to order operations.</li><li>It provides an endpoint to place a new order.</li><li>It includes Resilience4j annotations for circuit breaker, retry, and time limiter to enhance the service’s resilience.</li></ul><p><strong>2. Service:</strong></p><ul><li>The OrderService contains the business logic for managing orders.</li><li>It interacts with the database via the OrderRepository to save new orders.</li><li>It communicates with the Inventory Service to verify stock availability before placing an order.</li></ul><p>Please refer to the GitHub link provided for the implementation of the order service: <a href="https://github.com/HabtamuTesfie/microservices/tree/master/order-service">Github</a></p><h3>Enhancing Microservices with Service Discovery, API Gateway, Fault Tolerance, Message Broker, and Distributed Tracing</h3><h3>1) Service Discovery</h3><p>Service discovery provides a mechanism for microservices to locate each other dynamically within a microservices architecture. In real-world scenarios, the port number or IP address of a microservice instance might change, which can cause service calls between microservices to fail if they rely on static addresses. To overcome this problem, a service discovery component is essential. Spring Cloud offers Eureka Server and Eureka Clients to address this challenge.</p><h4>Setting Up Eureka Server for Service Discovery</h4><p>To implement service discovery, we need to set up a Eureka Server. This server will maintain a registry of all the microservices and their instances, enabling dynamic discovery and interaction.</p><p><strong>Step 1: Adding Dependencies</strong></p><p>First, add the necessary dependencies for the Eureka Server in your pom.xml file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/0*OYEhWvHNofEGRxSj.png" /></figure><p><strong>Step 2: Adding Configuration Files</strong></p><p>Application.properties</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/0*qVxrCiyARNBrn6ph.png" /></figure><p><strong>Step 3: Main Application Class</strong></p><p>Create the main application class for the Eureka Server and annotate it with @EnableEurekaServer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NFscge3vAm1HMHWc.png" /></figure><p><strong>Step 4: Security Configuration</strong></p><p>To ensure that Eureka’s endpoints are secured while allowing access to the Eureka dashboard, configure security settings as follows:</p><p>1. Add spring security dependency:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/0*nyO-UbPzKAgp6cPq.png" /></figure><p>2. Configure credentials on the application.properties file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/0*5AT2NEJ92PzzQvZa.png" /></figure><p><strong>Step 5: Disable Security Configuration for Eureka Server</strong></p><p>The SecurityConfig class configures security settings for the Eureka Server. It ensures that CSRF protection is disabled for requests to the Eureka endpoints, allowing the Eureka dashboard and client registrations to function properly without interference from CSRF security measures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/0*XBqDWRKZu68JkMWg.png" /></figure><h4>Modifying Microservices for Service Discovery Integration</h4><p>To integrate each microservice (Product, Inventory and order services) with Service Discovery (Eureka Server), follow these steps to modify their configuration:</p><p>1. Update pom.xml Dependencies:</p><p>Add the following dependencies to product, order and inventory service’s pom.xml file to enable Eureka Client integration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/0*vIvLve14LgJ7f3ps.png" /></figure><p>2. Update application.properties:</p><p>Setting the server port to 0 for each service allows the service to run on any available port.</p><ul><li>server.port=0</li></ul><p>Setting the service name for Eureka registration like the following for each service.</p><ul><li>spring.application.name=product-service</li><li>spring.application.name=order-service</li><li>spring.application.name=inventory-service</li></ul><p>Setting the service discovery (Eureka) server url for each service’s configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jUbDgea4e79Ge8lu.png" /></figure><p>Please check the implementations of service discovery from the github link: <a href="https://github.com/HabtamuTesfie/microservices/tree/master/discovery-server">Github</a></p><h3>2) API Gateway</h3><p>It serves as a single entry point for all client requests to interact with the microservices architecture. It provides a unified interface, enhances security, and facilitates dynamic routing and filtering of requests.</p><p>Spring Cloud Gateway is a powerful and flexible API Gateway built on top of the Spring Framework. It provides essential features for managing and routing HTTP requests within a microservices architecture. Here’s a detailed explanation of its components and functionalities:</p><h4>Key Components and Features</h4><p><strong>1) Routing:</strong></p><p>Spring Cloud Gateway allows you to define routes that determine how incoming requests are forwarded to backend services. Routes can be defined based on URI path, headers, HTTP methods, and other request attributes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rfqJB6DYrmsdkWZk.png" /></figure><p><strong>id</strong>: Unique identifier for the route.</p><p><strong>uri</strong>: URI of the backend service or load-balanced service.</p><p><strong>predicates</strong>: Conditions that must be met for the route to be matched.</p><p><strong>2) Filters:</strong></p><p>Filters are applied to requests and responses as they pass through the gateway. They can modify requests and responses, apply rate limiting, add headers, authenticate requests, and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YJhc8H5wQQXJyaXu.png" /></figure><p><strong>name</strong>: Name of the filter (e.g., RequestRateLimiter, AddRequestHeader)</p><p><strong>args</strong>: Arguments specific to the filter configuration.</p><h4>Integration with Service Discovery (Eureka)</h4><p>Spring Cloud Gateway integrates seamlessly with Eureka Server (spring-cloud-starter-netflix-eureka-client). This allows it to dynamically discover and route requests to registered microservices without hardcoding their addresses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SPMxxuTsD3pUNw3H.png" /></figure><p><strong>Service Discovery:</strong> Routes can directly reference services registered with Eureka using logical names (lb://service-name).</p><h4>Load Balancing Strategy</h4><p><strong>Load Balancing with lb://</strong></p><p>The lb:// prefix in Spring Cloud Gateway routes indicates that requests should be load-balanced across multiple instances of a service registered with a service registry (such as Eureka). This approach ensures high availability, scalability, and fault tolerance by distributing incoming traffic across multiple instances of a service.</p><p>When a request matches a route configured with lb://service-name, Spring Cloud Gateway queries the service registry to retrieve available instances of service-name. It employs a load balancing strategy (e.g., Round Robin) to distribute incoming requests among the identified instances.</p><p><strong>Load Balancing with WebClient:</strong></p><p>In addition to configuring routes in Spring Cloud Gateway, you can also enable client-side load balancing in your services using WebClient with the @LoadBalanced annotation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MwRzatQ5pI0mBKqP.png" /></figure><p>Check out the link: <a href="https://github.com/HabtamuTesfie/microservices/blob/master/order-service/src/main/java/et/com/config/WebClientConfig.java">GitHub Link</a></p><p><strong>Dynamic Updates:</strong> The service registry continuously monitors the health and availability of service instances. Spring Cloud Gateway automatically updates its list of available instances based on changes in the service registry.</p><h4>Security</h4><p>Spring Cloud Gateway integrates with Spring Security (spring-boot-starter-security) to enforce security policies, authenticate requests, and manage access to routes and services.</p><pre># application.properties<br>spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8080/realms/spring-boot-microservices-realm</pre><h4>Rate Limiter with Redis</h4><p>It is a technique used to control the rate of requests sent or received by a server. In a microservices architecture, rate limiting is essential to prevent individual services from being overwhelmed by too many requests, thereby ensuring stability and reliability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rtnm4RsAnHoYspTU.png" /></figure><p>To effectively run the API Gateway, ensure the following servers are configured on your local environment:</p><p><strong>1. Redis Server:</strong> Redis should be configured and running on port 6379. Redis is used as a backend to manage rate limiting configurations and counters, crucial for controlling request rates across microservices.</p><p><strong>2. Keycloak Server:</strong> Keycloak server should be configured and running on port 8080. Keycloak is utilized for OAuth2-based authentication and authorization, ensuring secure access to the microservices via the API Gateway.</p><p>For a comprehensive implementation of the API Gateway, including detailed configuration and setup, refer to the GitHub repository: <a href="https://github.com/HabtamuTesfie/microservices/tree/master/api-gateway">GitHub Link</a></p><h3>3) Fault Tolerance (Circuit Breaker)</h3><p>A microservices application anticipates failures as it scales. As the application expands, the likelihood of service failures increases, necessitating robust fault tolerance mechanisms. The circuit breaker pattern is crucial for detecting and handling unresponsive services, thereby preventing cascading failures throughout the application. Resilience4j, a modern resilience library, replaces Netflix Hystrix in contemporary microservices architectures.</p><p>It offers comprehensive fault tolerance features including circuit breakers, fallback strategies, and failure isolation. These capabilities ensure that even when services fail, the application can gracefully degrade functionality, maintaining overall stability and reliability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*puQrdPpUEIP4wOSE.png" /></figure><h4>Implementation Explanation</h4><p>In the provided implementation, Resilience4j is integrated into the OrderController to ensure fault tolerance for the placeOrder method, which interacts with other microservices like the inventory service.</p><p>1. <strong>Dependency:</strong> To use Resilience4j in your Spring Boot application, include the following dependency in your pom.xml:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PErv2XoeBdEZtS5F.png" /></figure><p>2. <strong>Circuit Breaker:</strong> The @CircuitBreaker annotation applied to the placeOrder method specifies the circuit breaker pattern. It monitors the number of failures and opens the circuit after reaching a threshold, preventing further calls until the service is deemed healthy again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7eBKUAvONKG1At2Y.png" /></figure><p>3. <strong>Fallback Method:</strong> The fallbackMethod is defined to provide an alternative response if the circuit breaker opens, preventing a total failure.</p><p>In the placeOrder method, @CircuitBreaker(name = &quot;inventory&quot;, fallbackMethod = &quot;fallbackMethod&quot;) specifies that if the inventory circuit breaker triggers, the fallbackMethod should be executed.</p><p>4. <strong>Time Limiter:</strong> The @TimeLimiter annotation ensures that calls to the placeOrder method are completed within a specified time frame, failing fast if the time limit is exceeded.</p><p><strong>Configuration:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CS-JyEIVBcLnjOa-.png" /></figure><p>5. <strong>Retry:</strong> The @Retry annotation allows retrying the operation a specified number of times before considering it as failed.</p><p><strong>Configuration:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VvAii7ng3xaBFVMT.png" /></figure><p>These properties configure the retry mechanism to attempt the operation up to 3 times with a 5-second wait between attempts.</p><p>For a comprehensive implementation of the Fault Tolerance, including detailed configuration and setup, refer to the GitHub repository: <a href="https://github.com/HabtamuTesfie/microservices/tree/master/order-service">Github link</a></p><h3>4) Broker Integration</h3><p>In a microservices architecture, it’s crucial to have efficient and reliable communication between services. One common approach to achieve this is by using a message broker. In this implementation, Kafka is used to facilitate communication between the Order Service and the Notification Service.</p><h4>Order Service</h4><p>The Order Service is responsible for placing orders and publishing events when an order is successfully placed.</p><p>Dependencies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*34JeBEPR22tU6N48.png" /></figure><p>Implementation (OrderService)</p><p>Placing an Order: The placeOrder method handles the logic of placing an order, including checking inventory and saving the order to the repository.</p><p>Publishing Events: When an order is successfully placed, an OrderPlacedEvent is published using applicationEventPublisher.</p><p>Complete implementation link: <a href="https://github.com/HabtamuTesfie/microservices/tree/master/order-service">link</a></p><h4>Notification Service</h4><p>The Notification Service is responsible for processing the events published by the Order Service. When an order is placed, the Notification Service listens for the OrderPlacedEvent and sends a notification email.</p><p>Dependencies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VC7OGpaXj56N6qoR.png" /></figure><p>Configuration (application.properties):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*st4ef0lcPCXPgiQt.png" /></figure><p>Implementation:</p><p>The Notification Service consists of three components:</p><ul><li><strong>Main Application Class:</strong> This class starts the Notification Service and listens to Kafka messages.</li><li><strong>Email Notification Service:</strong> This service handles the logic of processing the notification and sending an email.</li><li><strong>Email Service:</strong> This service is responsible for sending the actual email.</li></ul><p>Main Application Class (NotificationServiceApplication):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*UcsVLUuiNWJWS10i.png" /></figure><p><strong>Listening to Kafka Messages:</strong> The handleNotification method is annotated with @KafkaListener to listen for messages on the notificationTopic. When a message is received, it is passed to the EmailNotificationService for processing.</p><p>Email Notification Service (EmailNotificationService):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/0*zXKu86AUCCxqivjI.png" /></figure><p>Processing Notifications: The handleNotification method processes the received OrderPlacedEvent and sends an email notification using the EmailService.</p><p><strong>In this setup:</strong></p><ul><li><strong>Order Service:</strong> publishes OrderPlacedEvent to a Kafka topic when an order is placed.</li><li><strong>Notification Service:</strong> listens to the Kafka topic for OrderPlacedEvent messages and processes the event by sending a notification email.</li></ul><p>This integration ensures decoupled and scalable communication between the Order Service and the Notification Service using Kafka as the message broker.</p><p>For a comprehensive implementation of the order service, including detailed configuration and setup, refer to the GitHub repository: <a href="https://github.com/HabtamuTesfie/microservices/tree/master/order-service">Github link</a></p><p>For a comprehensive implementation of the notification service, including detailed configuration and setup, refer to the GitHub repository: <a href="https://github.com/HabtamuTesfie/microservices/tree/master/notification-service">Github link</a></p><h3>5) Distributed Tracing System Integration</h3><p>Distributed tracing is a critical component in modern microservices architectures. It allows you to trace the path of a request as it traverses through various services, providing visibility into the interaction and performance of each service. This helps in identifying bottlenecks, debugging issues, and ensuring that all services in the architecture are working harmoniously.</p><p>Key benefits of distributed tracing include:</p><ul><li><strong>Performance Monitoring:</strong> Identify slow services and performance bottlenecks.</li><li><strong>Error Tracking:</strong> Detect where errors occur within the service chain.</li><li><strong>Dependency Analysis:</strong> Understand service dependencies and interactions.</li><li><strong>Root Cause Analysis:</strong> Quickly pinpoint the root cause of issues in a distributed environment.</li></ul><p>Zipkin is an open-source distributed tracing system that helps gather timing data needed to troubleshoot latency problems in service architectures. It manages both the collection and lookup of this data. Check out more about Zipkin on <a href="https://zipkin.io/">link</a></p><p>Local Setup of Zipkin: check the link <a href="https://zipkin.io/pages/quickstart">zipkin</a></p><h4>Adding Dependencies and Configuration</h4><p>To integrate distributed tracing into all of the microservices, including the API Gateway and service discovery, you need to add the necessary dependencies and configuration properties. This example uses Micrometer and Brave for tracing and Zipkin for tracing data collection and visualization.</p><p>Dependencies:</p><p>Add the following dependencies to your pom.xml file in each microservice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JK-C5aJ_ga2wAprq.png" /></figure><p>Configuration:</p><p>Add the following properties to the application.properties file in each microservice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ES9dpjLxc27ucvMO.png" /></figure><p>These properties configure the tracing system to report to Zipkin and ensure that all traces are sampled (for development and debugging purposes, a sampling probability of 1 means 100% of traces are collected).</p><h4>Verifying Tracing Setup</h4><p>After setting up tracing in all microservices, service discovery and the API Gateway:</p><ul><li><strong>Deploy and Start Services:</strong> Ensure all services are running.</li><li><strong>Generate Traffic:</strong> Interact with your application to generate some traffic.</li><li><strong>Check Zipkin:</strong> Open Zipkin UI at <a href="http://localhost:9411/">http://localhost:9411</a> to visualize traces.</li></ul><p>You should see traces representing requests flowing through your microservices. Each trace will show spans that correspond to individual services and their respective operations.</p><h3>6) Constant Monitoring and Alerting</h3><p>Constant monitoring and alerting are essential components of managing a microservices architecture. They provide real-time insights into the state of your services, allowing you to detect and address issues promptly. A robust monitoring system helps track resource usage (such as disk utilization, memory consumption, and CPU utilization) and alerts you to any anomalies. Tools like Prometheus and Grafana, are commonly used for monitoring and visualization in microservices environments.</p><h4>Adding Dependencies and Properties</h4><p>To enable monitoring and alerting across all services, including the API Gateway and service discovery, you need to add specific dependencies and configure properties.</p><p>Dependencies:</p><p>Add the following dependencies to pom.xml file in each microservice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kD0LFYtzTK2QMcgQ.png" /></figure><p>Configuration:</p><p>Add the following properties to the application.properties file in each microservice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lPYz52r8EpxrodJW.png" /></figure><p>These configurations expose the Prometheus endpoint for each microservice, allowing Prometheus to scrape metrics from your applications.</p><p>Setting Up Prometheus and Grafana Using Docker: check out the <a href="https://selftuts.in/prometheus-and-grafana-installation-using-docker-compose/">link</a></p><p>Configure Grafana to Use Prometheus as a Data Source:</p><ul><li>Open your browser and navigate to <a href="http://localhost:3000/">http://localhost:3000</a>.</li><li>Log in with the default credentials (username: admin, password: admin).</li><li>Add a new data source:</li><li>Go to Configuration &gt; Data Sources &gt; Add data source.</li><li>Select Prometheus.</li><li>Set the URL to <a href="http://host.docker.internal:9090/">http://host.docker.internal:9090</a> and click Save &amp; Test.</li></ul><h3>7) Containerization</h3><p>Containerization provides an independent, isolated environment for microservices, bundling all dependencies needed to run each service. Containers run on a unified OS kernel, isolating themselves from the host environment and each other. This isolation offers significant flexibility when deploying applications across different computing environments, such as on-premises servers or managed cloud services like AWS or Azure.</p><p>Using containers ensures consistent environments from development to production, making applications more portable, scalable, and easier to manage.</p><h4>Jib for Image Creation</h4><p>Jib is a Maven and Gradle plugin designed for building optimized Docker and OCI images for Java applications. Unlike traditional methods that require Dockerfiles, Jib directly creates images during the build process, simplifying containerization.</p><p><strong>Benefits of Jib:</strong></p><ul><li><strong>No Docker Daemon Required:</strong> Jib does not require Docker to be installed locally, making it easier to use in environments without Docker.</li><li><strong>Reproducible Builds:</strong> Jib produces the same image every time it is run, ensuring consistency across environments.</li><li><strong>Optimized Layers:</strong> Jib automatically optimizes the image layers, which speeds up the build and push process by reusing layers when possible.</li><li><strong>Integrated with Build Tools:</strong> As a plugin for Maven and Gradle, Jib integrates seamlessly into existing build pipelines.</li><li><strong>Security:</strong> By avoiding Dockerfiles and the need for Docker, Jib reduces potential security risks associated with misconfigured Dockerfiles or privileged Docker daemons.</li></ul><p>You can read more about Jib on <a href="https://cloud.google.com/java/getting-started/jib">link</a></p><p>Example Jib Configuration:</p><p>Here’s an example of how to configure Jib in your pom.xml:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/0*6P8_mt88W-O4CXww.png" /></figure><h3>Local Development and Testing Guide Using Docker Compose</h3><p><strong>Prerequisites:</strong></p><p>Install Docker and Docker Compose: Ensure Docker and Docker Compose are installed on your system.</p><h4>Steps to Run the Project</h4><p>1. Clone the Docker Compose File: Clone the docker-compose.yml file from the repository to your local machine:</p><pre>git clone https://github.com/HabtamuTesfie/microservices.git<br>cd microservices</pre><p>2. Start Docker Compose: Run the following command to start all the services defined in the docker-compose.yml file:</p><pre>docker-compose up -d</pre><p>3. Verify Services are Running: Check the status of the containers to ensure they are running correctly:</p><pre>docker-compose ps</pre><p>4. Access Keycloak: Keycloak is configured to run on port 8080. Access it via:</p><p><a href="http://localhost:8080/">http://localhost:8080</a></p><p>Default credentials are:</p><ul><li>Username: admin</li><li>Password: admin</li></ul><h4>Next Steps</h4><p><strong>1. Create a Realm:</strong></p><ul><li>On the top left of the dashboard, hover over the drop-down labeled “Master”.</li><li>Click the “Add realm” button.</li><li>Name the realm “spring-boot-microservices-realm”.</li><li>Click the “Create” button.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Eieb5ULckimUwpDs.png" /></figure><p><strong>2. Create a Client:</strong></p><ul><li>Navigate to “Realm Settings” in the left panel under the “Configure” section.</li><li>Click on “Clients” under “Realm Settings”.</li><li>Click the “Create” button on the top right.</li><li>Enter “spring-cloud-client” as the Client ID.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LAJU6nVr9HIlTFlb.png" /></figure><p><strong>3. Configure the Client:</strong></p><ul><li>Change “Access Type” from “Public” to “Confidential”.</li><li>Disable “Standard Flow Enabled” and “Direct Access Grants Enabled”.</li><li>Enable “Service Accounts Enabled”.</li><li>Click “Save” at the bottom.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D2kSEOPJwH5rJg6O.png" /></figure><p><strong>4. Get Client Secret:</strong></p><ul><li>Go to the “Credentials” tab.</li><li>Copy the Secret and save it for future use in OAuth2 requests with Postman or frontend applications.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_IVB4bdZ-MKgm7am.png" /></figure><h4>Verify Service Endpoints</h4><p><strong>Tip:</strong> Before testing any endpoint ensure “keycloak” is added to your local hosts file by mapping 127.0.0.1 keycloak in /etc/hosts (Linux/Mac) or C:\Windows\System32\drivers\etc\hosts (Windows).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rg_Z7quX9kUINb7Q.png" /></figure><h3>Common Postman Configuration</h3><h4>Step 1: Open Postman and Set Up the Request</h4><ul><li>Open Postman and create a new request.</li><li>Set the request type (GET, POST, etc.) according to the endpoint.</li><li>Enter the request URL (adjust based on endpoint, e.g., <a href="http://localhost:8181/api/product">http://localhost:8181/api/product</a>).</li></ul><h4>Step 2: Configure Authorization</h4><ul><li>Click on the <strong>Authorization</strong> tab.</li><li><strong>Select OAuth 2.0</strong> from the Type dropdown.</li><li><strong>Set the “Add authorization data to” field</strong> to “Request Headers”.</li></ul><h4>Step 3: Configure the OAuth 2.0 Token</h4><p>1. Fill in the following details in the “Configure New Token” section:</p><ul><li><strong>Token Name:</strong> Enter any descriptive name, e.g., sample.</li><li><strong>Grant Type:</strong> Select Client Credentials.</li><li><strong>Access Token URL:</strong> Enter <a href="http://keycloak:8080/realms/spring-boot-microservices-realm/protocol/openid-connect/token">http://keycloak:8080/realms/spring-boot-microservices-realm/protocol/openid-connect/token</a>.</li><li><strong>Client ID:</strong> Enter “spring-cloud-client”.</li><li><strong>Client Secret:</strong> Enter your client secret previously saved.</li><li><strong>Scope:</strong> Enter “openid offline_access”.</li><li><strong>Client Authentication:</strong> Select “Send as Basic Auth header”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HItZUKcIBsXhEbcS.png" /></figure><p>2. Click on “<strong>Get New Access Token</strong>” to retrieve the access token.</p><p>3. Then click on “<strong>Proceed</strong>”.</p><p>4. Once the token is retrieved, click on “<strong>Use Token</strong>”.</p><h4>Step 4: Endpoint-Specific Configuration</h4><p><strong>1. Create Product:</strong></p><p><strong>Method:</strong> POST</p><p><strong>Endpoint:</strong> <a href="http://localhost:8181/api/product">http://localhost:8181/api/product</a></p><p><strong>Request Body Example:</strong></p><pre>{<br>  &quot;name&quot;: &quot;iphone_13&quot;,<br>  &quot;description&quot;: &quot;iphone_13 description&quot;,<br>  &quot;price&quot;: 1000000<br>}</pre><p><strong>2. Get Product</strong></p><p><strong>Method:</strong> GET</p><p><strong>Endpoint:</strong> <a href="http://localhost:8181/api/product">http://localhost:8181/api/product</a></p><p><strong>Response Example:</strong></p><pre>[<br>  {<br>    &quot;id&quot;: &quot;667bde399291d3755f7c923a&quot;,<br>    &quot;name&quot;: &quot;iphone_13&quot;,<br>    &quot;description&quot;: &quot;iphone_13 description&quot;,<br>    &quot;price&quot;: 1000000<br>  }<br>]</pre><p><strong>3. Create Order</strong></p><p><strong>Method:</strong> POST</p><p><strong>Endpoint:</strong> <a href="http://localhost:8181/api/order">http://localhost:8181/api/order</a></p><p><strong>Request Body Example:</strong></p><pre>{<br>  &quot;orderLineItemsDtoList&quot;: [<br>    {<br>      &quot;skuCode&quot;: &quot;iphone_13&quot;,<br>      &quot;price&quot;: 100000,<br>      &quot;quantity&quot;: 20<br>    }<br>  ]<br>}</pre><p>Please check out the <a href="https://github.com/HabtamuTesfie/microservices/blob/master/docker-compose.yml">Github link</a> for the docker-compose.yml file.</p><p>You can clone and test the complete repository on your local.</p><p>Here is the Github <a href="https://github.com/HabtamuTesfie/microservices">link</a></p><p><em>Originally published at </em><a href="https://scalable-microservices-implementation.blogspot.com/2024/06/implementing-robust-microservices.html"><em>scalable-microservices-implementation.blogspot.com</em></a><em> on June 27, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd9364a75f69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic AEM Component Versioning: Managing Angular and React SPAs with Version Control]]></title>
            <link>https://medium.com/@habtamutesfie/dynamic-aem-component-versioning-managing-angular-and-react-spas-with-version-control-4c9b5e1826bd?source=rss-f42f01f8cee8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c9b5e1826bd</guid>
            <dc:creator><![CDATA[Habtamu Tesfie]]></dc:creator>
            <pubDate>Sat, 03 Aug 2024 10:39:25 GMT</pubDate>
            <atom:updated>2024-08-03T10:39:25.553Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pasVzTubRvY19uwqdRp4bg.jpeg" /></figure><p>Are you ready to revolutionize your web development projects with unparalleled versioning capabilities and dynamic flexibility? Look no further than Adobe Experience Manager (AEM) and its game-changing feature: dynamic AEM component versioning. Imagine effortlessly managing different versions of components tailored precisely to your authors’ preferences. In this captivating blog post, we invite you on an exhilarating journey into the realm of dynamic AEM component versioning with different client libraries.</p><p>Brace yourself as we guide you step-by-step through an extraordinary demo project, complete with enticing code snippets and captivating images. Discover how AEM’s seamless integration with React, Angular, and Sling Model empowers you to effortlessly switch between these frameworks. Learn how to use custom components to render both Angular and React SPAs and how a version manager component allows authors to dynamically switch between these versions. Whether you need to display the Angular version for one region and the React version for another, or revert to previous versions, AEM makes it easy.</p><p>Get ready to elevate your web development workflow with the unmatched power of dynamic AEM component versioning and different client libraries like never before!</p><p><strong>Benefits of Dynamic AEM component Versioning</strong></p><p><strong>1) Seamless Technology Switch: </strong><br>Dynamic AEM component versioning allows for a seamless transition between Angular and React frameworks. With the ability to switch between technologies effortlessly, developers can leverage the strengths of each framework based on their specific requirements, without the need for extensive code changes or reimplementation.</p><p><strong>2) Flexibility in Regional Customization:</strong> <br>By assigning different component versions to different regions, Dynamic AEM component Versioning empowers developers to tailor the user experience based on geographic or regional preferences. This flexibility enables the creation of unique and targeted experiences for specific audiences, enhancing engagement and satisfaction.</p><p><strong>3) Efficient Iterative Development:</strong> <br>With Dynamic AEM component versioning, developers can iteratively enhance and improve their components without disrupting the overall user experience. Separate versions of components can be developed and tested independently, enabling faster iterations and reducing the risk of introducing errors or regressions.</p><p><strong>4). Enhanced Collaboration:</strong> <br>Dynamic AEM component versioning facilitates collaboration between developers working on different versions of components. Teams can work concurrently on Angular and React versions, leveraging their respective expertise, and seamlessly integrate their work into a unified and cohesive application.</p><p><strong>5). Increased Productivity:</strong> <br>By leveraging Dynamic AEM component versioning, development teams can optimize their productivity. Developers familiar with Angular or React can work on their preferred framework, maximizing their efficiency and allowing them to leverage their existing skills and knowledge.</p><p><strong>6) Future-Proofing:</strong> <br>Dynamic AEM component versioning ensures that your web development projects are future-proofed. By embracing multiple frameworks, you can adapt and evolve with changing technology trends, ensuring that your applications remain up-to-date and compatible with the latest advancements.</p><p><strong>7). Enhanced User Experience:</strong> <br>By leveraging the strengths of Angular and React through Dynamic AEM component versioning, developers can create highly interactive and engaging user experiences. The frameworks’ rich ecosystem of libraries and components, combined with AEM’s powerful capabilities, empowers developers to deliver exceptional user experiences that captivate and delight their audience.</p><p>As Dynamic AEM component versioning with sling model, angular and react, I have added a <a href="https://github.com/HabtamuTesfie/AEM-COMPONENT-VERSIONING">POC</a> project with a component named “hospital-management-hub”. The component dialog has an additional field labeled “CHOOSE APP VERSION”, with a select dropdown for component versions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZMzIFimBhFa8SWyTpynjjw.png" /></figure><p><strong>Steps To Dynamic AEM Component Versioning</strong></p><p><strong>Step 1: Setting Up the AEM Projects</strong></p><ul><li>Begin by creating an AEM project, which serves as the foundation for your web development endeavors.</li><li>Within the project structure, create a module named “ui.frontend” to house the Angular application.</li><li>Additionally, create another module named “ui.frontend2” to contain the React application.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*fT3jAczDJ8MhjgjW0Gjovg.png" /></figure><p><strong>Step Two: Implement Dynamic AEM Component Versioning logic using sling model.</strong></p><pre>package com.sample.aem.core.models;<br><br>import com.day.cq.wcm.api.Page;<br>import com.day.cq.wcm.api.PageManager;<br>import org.apache.sling.api.SlingHttpServletRequest;<br>import org.apache.sling.api.resource.*;<br>import org.apache.sling.models.annotations.Model;<br>import org.apache.sling.models.annotations.injectorspecific.Self;<br><br>import javax.inject.Inject;<br>import javax.jcr.*;<br>import java.util.Objects;<br><br><br>//--------------------------------------------------------------------------------<br>/**<br> * A Sling Model representing a Version Manager for handling version-specific<br> * logic in AEM components.<br> */<br>//--------------------------------------------------------------------------------<br>@Model<br>    (<br>        adaptables   = {SlingHttpServletRequest.class, Resource.class}<br>    )<br>@SuppressWarnings(&quot;squid:S00115&quot;)<br>public class VersionManager<br>{<br>    private static final String COMPONENT_NAME      = &quot;hospital-management-hub&quot;;<br>    private static final String RESOURCE_PATH       = &quot;root/responsivegrid/hospital-hub&quot;;<br>    private static final String COMPONENT_PATH      = &quot;aem-component-versioning/components/content/&quot; + COMPONENT_NAME +&quot;/&quot;;<br>    private static final String SLING_RESOURCE_TYPE = &quot;sling:resourceType&quot;;<br>    private static final String VERSION_NUMBER      = &quot;versionNumber&quot;;<br>    private static final String VERSION_1_VALUE     = &quot;v1&quot;;<br>    private static final String VERSION_2_VALUE     = &quot;v2&quot;;<br>    private static final String V1_RESOURCE_TYPE    = COMPONENT_PATH + VERSION_1_VALUE + &quot;/&quot; + COMPONENT_NAME;<br>    private static final String V2_RESOURCE_TYPE    = COMPONENT_PATH + VERSION_2_VALUE + &quot;/&quot; + COMPONENT_NAME;<br><br>    @Inject<br>    private Resource resource;<br><br>    @Inject<br>    private ResourceResolver resolver;<br><br>    @Self<br>    private SlingHttpServletRequest request;<br><br><br>    //--------------------------------------------------------------------------------<br>    /**<br>     * Gets the version number from the content node.<br>     *<br>     * @return The version number or null if not found.<br>     */<br>    //--------------------------------------------------------------------------------<br>    public String getVersionNumber()<br>    {<br>        Node node = Objects<br>                   .requireNonNull(getPage()<br>                   .getContentResource(RESOURCE_PATH))<br>                   .adaptTo(Node.class);<br>        if (node == null) {<br>            return null;<br>        }<br><br>        return readText(node);<br>    } // getVersionNumber<br><br><br>    //--------------------------------------------------------------------------------<br>    /**<br>     * Checks if the version number is v2.<br>     *<br>     * @return True if the version number is v2, false otherwise.<br>     */<br>    //--------------------------------------------------------------------------------<br>    public boolean isVersion2()<br>    {<br>        return getVersionNumber().equals(VERSION_2_VALUE);<br>    } // isVersion2<br><br><br>    //--------------------------------------------------------------------------------<br>    /**<br>     * Changes the resource type based on the version number.<br>     *<br>     * @return An empty string.<br>     */<br>    //--------------------------------------------------------------------------------<br>    public String changeResourceType()<br>    {<br>        try<br>        {<br>            ModifiableValueMap properties = resource.adaptTo(ModifiableValueMap.class);<br><br>            if (properties != null)<br>            {<br>                String currentResourceType = properties.get(SLING_RESOURCE_TYPE, String.class);<br><br>                if (VERSION_1_VALUE.equals(getVersionNumber()) &amp;&amp; V2_RESOURCE_TYPE.equals(currentResourceType))<br>                {<br>                    properties.put(SLING_RESOURCE_TYPE, V1_RESOURCE_TYPE);<br>                    resolver.commit();<br>                }<br>                else if (VERSION_2_VALUE.equals(getVersionNumber()) &amp;&amp; V1_RESOURCE_TYPE.equals(currentResourceType))<br>                {<br>                    properties.put(SLING_RESOURCE_TYPE, V2_RESOURCE_TYPE);<br>                    resolver.commit();<br>                }<br>            }<br>        }<br>        catch (PersistenceException e)<br>        {<br>            throw new RuntimeException(SLING_RESOURCE_TYPE + &quot; error: Failed to persist&quot;, e);<br>        }<br><br>        return &quot;&quot;;<br>    } // changeResourceType<br><br><br>    //--------------------------------------------------------------------------------<br>    /**<br>     * Gets the Page object associated with the current resource.<br>     *<br>     * @return The Page object.<br>     */<br>    //--------------------------------------------------------------------------------<br>    private Page getPage()<br>    {<br>        PageManager pm = resolver.adaptTo(PageManager.class);<br><br>        return Objects.requireNonNull(pm).getContainingPage(getResource());<br>    } // getPage<br><br><br>    //--------------------------------------------------------------------------------<br>    /**<br>     * Gets the current Sling Resource.<br>     *<br>     * @return The current Sling Resource.<br>     */<br>    //--------------------------------------------------------------------------------<br>    private Resource getResource()<br>    {<br>        return request.getResource();<br>    } // getResource<br><br><br>    //--------------------------------------------------------------------------------<br>    /**<br>     * Reads text from a JCR property.<br>     *<br>     * @param node The JCR Node.<br>     * @return The text value of the property, or null if not found.<br>     */<br>    //--------------------------------------------------------------------------------<br>    private String readText(Node node)<br>    {<br>        Property property = readNodeProperty(node);<br>        if (property == null) return null;<br><br>        return readText(property);<br>    } // readText<br><br><br>    //--------------------------------------------------------------------------------<br>    /**<br>     * Reads text from a JCR property.<br>     *<br>     * @param property The JCR Property.<br>     * @return The text value of the property.<br>     */<br>    //--------------------------------------------------------------------------------<br>    private String readText(Property property)<br>    {<br>        try<br>        {<br>            return property.getString();<br>        }<br>        catch (ValueFormatException e)<br>        {<br>            String error = &quot; error: Failed to format&quot;;<br>            throw new RuntimeException(error, e);<br>        }<br>        catch (RepositoryException e)<br>        {<br>            String error = &quot; error: Failed to access&quot;;<br>            throw new RuntimeException(error, e);<br>        }<br>    } // readText<br><br><br>    //--------------------------------------------------------------------------------<br>    /**<br>     * Reads a JCR property from a node.<br>     *<br>     * @param node The JCR Node.<br>     * @return The JCR Property or null if not found.<br>     */<br>    //--------------------------------------------------------------------------------<br>    private Property readNodeProperty(Node node)<br>    {<br>        if (node == null) return null;<br><br>        try<br>        {<br>            if (!node.hasProperty(VersionManager.VERSION_NUMBER)) return null;<br><br>            return node.getProperty(VersionManager.VERSION_NUMBER);<br>        }<br>        catch (ValueFormatException e)<br>        {<br>            String error = &quot;Failed to format property &quot; + &#39;.&#39; + VersionManager.VERSION_NUMBER;<br>            throw new RuntimeException(error, e);<br>        }<br>        catch (PathNotFoundException e)<br>        {<br>            String error = &quot; error: No path for &quot;;<br>            throw new RuntimeException(error + node, e);<br>        }<br>        catch (RepositoryException e)<br>        {<br>            String error = &quot; error: Failed to access &quot;;<br>            throw new RuntimeException(error + node, e);<br>        }<br>    } // readNodeProperty<br><br>} // VersionManager</pre><p>Now, let’s dive into the detailed implementation of dynamic AEM component versioning with the provided sling model, <strong><em>VersionManager</em></strong> (model class). This step focuses on creating a flexible setup where authors can easily switch between versions.</p><p>The <strong><em>VersionManager</em></strong> Sling Model is a key component in implementing versioning for Adobe Experience Manager (AEM) components. Its general usage is centered around facilitating version-specific logic within AEM components, particularly for a component named <em>“hospital-management-hub.”</em></p><p>Here’s a high-level overview of the general usage of the code in the context of dynamic AEM component Versioning:</p><p>1.<strong>Version Detection:</strong> the model provides a method (<strong><em>getVersionNumber()</em></strong>) to detect the version number associated with the content node of the current AEM component.</p><p><strong>2.Version Comparison:</strong> It includes a method (<strong><em>isVersion2()</em></strong>) to check if the detected version is “v2.”</p><p><strong>3.Resource Type Management: </strong>The primary functionality lies in the <strong><em>changeResourceType()</em></strong> method, responsible for dynamically changing the resource type based on the detected version.</p><p>This is crucial for integrating AEM component versioning, allowing different resource types for different versions of the same component.</p><p><strong>Step Three: Loading Client Libraries Based on Version</strong></p><p>To ensure the seamless integration of dynamic AEM component versioning with Angular and React, the client libraries are dynamically loaded based on the selected version. The logic for version detection and resource type switching, implemented in the <strong><em>VersionManager </em></strong><em>sling model</em>, is utilized within the AEM component’s page.</p><p><em>page/customheaderlibs.html</em></p><pre>&lt;sly data-sly-use.clientLib=&quot;/libs/granite/sightly/templates/clientlib.html&quot;&gt;<br>  &lt;sly data-sly-use.version=&quot;com.sample.aem.core.models.VersionManager&quot;&gt;<br>    &lt;sly data-sly-test=&quot;${!version.version2}&quot;&gt;<br>      &lt;sly data-sly-call=&quot;${clientlib.css @ categories=&#39;hospital-hub-angular&#39;}&quot;/&gt;<br>    &lt;/sly&gt;<br>    &lt;sly data-sly-test=&quot;${version.version2}&quot;&gt;<br>      &lt;sly data-sly-call=&quot;${clientlib.css @ categories=&#39;hospital-hub-react&#39;}&quot;/&gt;<br>    &lt;/sly&gt;<br>  &lt;/sly&gt;<br>&lt;/sly&gt;</pre><p><em>page/customfooterlibs.html</em></p><pre>&lt;sly data-sly-use.clientlib=&quot;/libs/granite/sightly/templates/clientlib.html&quot;&gt;<br>  &lt;sly data-sly-use.version=&quot;com.sample.aem.core.models.VersionManager&quot;&gt;<br>    &lt;sly data-sly-test=&quot;${!version.version2}&quot;&gt;<br>      &lt;sly data-sly-call=&quot;${clientlib.js @ categories=&#39;hospital-hub-angular&#39;}&quot;/&gt;<br>    &lt;/sly&gt;<br>    &lt;sly data-sly-test=&quot;${version.version2}&quot;&gt;<br>      &lt;sly data-sly-call=&quot;${clientlib.js @ categories=&#39;hospital-hub-react&#39;}&quot;/&gt;<br>    &lt;/sly&gt;<br>  &lt;/sly&gt;<br>&lt;/sly&gt;</pre><p>In the provided code snippets:</p><ul><li>The <strong><em>VersionManager</em></strong> sling model is used to detect the current version.</li><li>Conditional statements (data-sly-test) are used to determine whether to load Angular client libraries (version one)or React client libraries (version two).</li></ul><p>By incorporating this logic into the AEM component’s client library loading mechanism, you ensure that the correct client libraries are served based on the selected version. This dynamic loading enhances the overall user experience and allows for efficient management of component versions in your AEM project.</p><p><strong>Step Four: Dynamically Changing Component Version</strong></p><p>Now that we have set up dynamic AEM component versioning and dynamically loaded client libraries based on author preferences, the next crucial step is to enable the seamless switching of component versions when the author makes a selection.</p><p><em>hospital-management-hub.html(V1)</em></p><pre>&lt;sly data-sly-use.model=&quot;com.sample.aem.core.models.HospitalManagementHub&quot;&gt;<br>  &lt;sly data-sly-test=&quot;${!wcmmode.edit}&quot;&gt;<br>    &lt;h1 style=&quot;align-content: center; text-align: center; background: cadetblue; color: black; width: 100%&quot;&gt;<br>        ${model.title} USING &lt;strong style=&quot;color: crimson&quot;&gt;ANGULAR&lt;/strong&gt;<br>    &lt;/h1&gt;<br>  &lt;/sly&gt;<br>  &lt;div style=&quot;margin-left: 75px;&quot;&gt;<br>    &lt;sly data-sly-use.version=&quot;com.sample.aem.core.models.VersionManager&quot;&gt;<br>      &lt;sly data-sly-test=&quot;${wcmmode.edit}&quot;&gt;<br>        &lt;h3&gt;${model.title}&lt;/h3&gt;<br>        &lt;sly&gt;${version.changeResourceType}&lt;/sly&gt;<br>          &lt;br/&gt;<br>          &lt;h3&gt;Edit hospital management app(v1)&lt;/h3&gt;<br>          &lt;h4&gt;Note*: Please publish the page to see the authored content.&lt;/h4&gt;<br>          &lt;br/&gt;<br>      &lt;/sly&gt;<br>      &lt;sly data-sly-test=&quot;${!wcmmode.edit}&quot;&gt;<br>        &lt;div&gt;<br>          &lt;app-root&gt;&lt;/app-root&gt;<br>        &lt;/div&gt;<br>      &lt;/sly&gt;<br>    &lt;/sly&gt;<br>  &lt;/div&gt;<br>&lt;/sly&gt;</pre><p><em>hospital-management-hub.html(V2)</em></p><pre>&lt;sly data-sly-use.model=&quot;com.sample.aem.core.models.HospitalManagementHub&quot;&gt;<br>  &lt;sly data-sly-test=&quot;${!wcmmode.edit}&quot;&gt;<br>    &lt;h1 style=&quot;align-content: center; text-align: center; background: cadetblue; color: black; width: 100%&quot;&gt;<br>        ${model.title} USING &lt;strong style=&quot;color: crimson&quot;&gt;REACT&lt;/strong&gt;<br>    &lt;/h1&gt;<br>  &lt;/sly&gt;<br>  &lt;div style=&quot;margin-left: 75px;&quot;&gt;<br>    &lt;sly data-sly-use.version=&quot;com.sample.aem.core.models.VersionManager&quot;&gt;<br>      &lt;sly data-sly-test=&quot;${wcmmode.edit}&quot;&gt;<br>        &lt;h3&gt;${model.title}&lt;/h3&gt;<br>        &lt;sly&gt;${version.changeResourceType}&lt;/sly&gt;<br>          &lt;br/&gt;<br>          &lt;h3&gt;Edit hospital management app(v2)&lt;/h3&gt;<br>          &lt;h4&gt;Note*: Please publish the page to see the authored content.&lt;/h4&gt;<br>          &lt;br/&gt;<br>      &lt;/sly&gt;<br>      &lt;sly data-sly-test=&quot;${!wcmmode.edit}&quot;&gt;<br>        &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>      &lt;/sly&gt;<br>    &lt;/sly&gt;<br>  &lt;/div&gt;<br>&lt;/sly&gt;</pre><ul><li>The <em>VersionManager’s</em> <strong><em>changeResourceType</em></strong> method is called when the page is in edit mode (<em>wcmmode.edit</em>).</li><li>This method dynamically changes the resource type based on the selected version, ensuring that the correct Angular or React client libraries are loaded.</li><li>The <strong><em>app-root</em></strong> or <strong><em>div</em></strong> is then rendered based on the selected version, showcasing the seamless integration of AEM component versioning with dynamic client library loading.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tOHu3aTxnN1lfFIF7qqBxA.png" /></figure><p>By incorporating this logic into your AEM components, you enable authors to effortlessly switch between versions and witness the real-time changes in the authored content. This enhances the authoring experience and streamlines the management of AEM projects with component versioning.</p><p>Github Code:<a href="https://github.com/HabtamuTesfie/AEM-COMPONENT-VERSIONING">link</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c9b5e1826bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Third-Party APIs into AEM 6.5 with Client-Side Rendering Approach]]></title>
            <link>https://medium.com/@habtamutesfie/integrating-third-party-apis-into-aem-6-5-with-client-side-rendering-approach-f1c07933bbdf?source=rss-f42f01f8cee8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1c07933bbdf</guid>
            <dc:creator><![CDATA[Habtamu Tesfie]]></dc:creator>
            <pubDate>Fri, 02 Aug 2024 12:54:17 GMT</pubDate>
            <atom:updated>2024-08-06T06:04:25.909Z</atom:updated>
            <content:encoded><![CDATA[<p>To integrate third-party APIs into Adobe Experience Manager (AEM) 6.5, there are two approaches: <br>1) Server-Side Rendering.<br>2) Client-Side Rendering.</p><p><strong>Server-Side Rendering (SSR)</strong> is best for SEO, initial page load performance, and content-heavy pages. It’s ideal for static content or less interactive pages and offers seamless integration with AEM’s authoring environment. SSR ensures faster time-to-content delivery, making it suitable for scenarios where quick access to static information is crucial.</p><p><strong>Client-Side Rendering (CSR)</strong> is suited for highly interactive user interfaces and single-page applications (SPAs). This approach reduces server load and provides smoother user experiences by offloading rendering tasks to the client side. CSR allows for decoupled frontend and backend architectures, enabling personalization and real-time updates, which are essential for modern web applications.</p><p>This blog will guide you through implementing Client-Side Rendering (CSR) to fetch and display third-party API data dynamically within AEM components.</p><p>For more information on the Server-Side Rendering approach, you can refer to this <a href="https://medium.com/@habtamutesfie/integrating-third-party-apis-in-aem-da188e910b7d"><strong>article</strong></a>.</p><p><strong>Client-Side Rendering Approach </strong><br><strong>1. Create an OSGi Service Layer </strong><br>The OSGi Service Layer is responsible for interacting with the third-party API. This service handles the API requests and processes the data, making it available for other components within the AEM environment. <br> <br><strong>OSGi Service Interface</strong>:</p><pre>package et.com.core.services;<br><br><br>import et.com.core.api.MedicalProviders;<br><br>public interface ProviderService {<br>    MedicalProviders getProviderData();<br>}</pre><p><strong>OSGi Service Implementation:</strong></p><pre>package et.com.core.services;<br><br>import com.google.gson.Gson;<br>import et.com.core.api.MedicalProviders;<br>import et.com.core.config.ProviderServiceConfig;<br>import org.apache.http.HttpEntity;<br>import org.apache.http.client.methods.CloseableHttpResponse;<br>import org.apache.http.client.methods.HttpGet;<br>import org.apache.http.impl.client.CloseableHttpClient;<br>import org.apache.http.impl.client.HttpClients;<br>import org.apache.http.util.EntityUtils;<br>import org.osgi.service.component.annotations.Activate;<br>import org.osgi.service.component.annotations.Component;<br>import org.osgi.service.component.annotations.Modified;<br>import org.osgi.service.metatype.annotations.Designate;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br><br>import java.io.IOException;<br><br>@Component(service = ProviderService.class, immediate = true)<br>@Designate(ocd = ProviderServiceConfig.class)<br>public class ProviderServiceImpl implements ProviderService {<br><br>    private static final Logger LOG = LoggerFactory.getLogger(ProviderServiceImpl.class);<br><br>    private String providerApiUrl;<br><br>    @Activate<br>    @Modified<br>    protected void activate(ProviderServiceConfig config) {<br>        this.providerApiUrl = config.apiUrl();<br>    }<br><br>    @Override<br>    public MedicalProviders getProviderData() {<br>        LOG.info(&quot;The provided url is {}&quot;, providerApiUrl);<br>        String jsonData = &quot;&quot;;<br>        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {<br>            HttpGet request = new HttpGet(providerApiUrl);<br>            try (CloseableHttpResponse response = httpClient.execute(request)) {<br>                HttpEntity entity = response.getEntity();<br>                if (entity != null) {<br>                    jsonData = EntityUtils.toString(entity);<br>                }<br>            }<br>        } catch (IOException e) {<br>            LOG.error(&quot;Error fetching data from URL: {}&quot;, providerApiUrl, e);<br>        }<br><br>        Gson gson = new Gson();<br>        return gson.fromJson(jsonData, MedicalProviders.class);<br>    }<br>}</pre><p><strong>2. Expose Operations via Sling Servlet</strong> <br>The Sling Servlet acts as a bridge between the AEM frontend and the OSGi service. It handles HTTP requests and responses, allowing the frontend to fetch data from the third-party API through the OSGi service.</p><p><strong>Sling Servlet:</strong></p><pre>package et.com.core.servlets;<br><br>import com.google.gson.Gson;<br>import et.com.core.services.ProviderService;<br>import et.com.core.api.MedicalProviders;<br>import org.apache.sling.api.SlingHttpServletRequest;<br>import org.apache.sling.api.SlingHttpServletResponse;<br>import org.apache.sling.api.servlets.SlingAllMethodsServlet;<br>import org.osgi.service.component.annotations.Component;<br>import org.osgi.service.component.annotations.Reference;<br><br>import javax.servlet.Servlet;<br>import java.io.IOException;<br><br>@Component(<br>    service = Servlet.class,<br>    property = {<br>        &quot;sling.servlet.paths=/bin/fetchProviderData&quot;,<br>        &quot;sling.servlet.methods=GET&quot;<br>    }<br>)<br>public class ProviderDataServlet extends SlingAllMethodsServlet {<br><br>    @Reference<br>    private transient ProviderService providerService;<br><br>    @Override<br>    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {<br>        MedicalProviders providers = providerService.getProviderData();<br>        response.setContentType(&quot;application/json&quot;);<br>        response.setCharacterEncoding(&quot;UTF-8&quot;);<br>        response.setHeader(&quot;Access-Control-Allow-Origin&quot;, &quot;http://localhost:4200&quot;);<br>        response.setHeader(&quot;Access-Control-Allow-Methods&quot;, &quot;GET,POST,OPTIONS&quot;);<br>        response.setHeader(&quot;Access-Control-Allow-Headers&quot;, &quot;Authorization,Content-Type&quot;);<br>        Gson gson = new Gson();<br>        String json = gson.toJson(providers);<br>        response.getWriter().write(json);<br>    }<br>}</pre><p><strong>3. Develop Client-Side Code with Angular</strong> <br>The Angular service and component are responsible for fetching and rendering the data from the third-party API. The service makes HTTP requests to the Sling Servlet, while the component handles the presentation logic.</p><p><strong>Angular Service:</strong></p><pre>import { HttpClient, HttpHeaders } from &#39;@angular/common/http&#39;;<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class ProviderService {<br>  private basseUrl:string = &#39;http://localhost:4502&#39;;<br>  private apiUrl:string = &#39;/bin/fetchProviderData&#39;;<br><br>  constructor(private http: HttpClient) { }<br><br>  getProviderData(): Observable&lt;any&gt; {<br>    return this.http.get&lt;any&gt;(this.apiUrl);<br>  }<br>}</pre><p><strong>Angular Component:</strong></p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { ProviderService } from &#39;../service/provider.service&#39;;<br><br>@Component({<br>  selector: &#39;app-provider&#39;,<br>  templateUrl: &#39;./provider.component.html&#39;,<br>  styleUrls: [&#39;./provider.component.css&#39;]<br>})<br>export class ProviderComponent implements OnInit {<br>  providers: any;<br><br>  constructor(private providerService: ProviderService) { }<br><br>  ngOnInit(): void {<br>    this.providerService.getProviderData().subscribe(data =&gt; {<br>      console.log(&quot;Entire response data:&quot;, data);<br>      this.providers = data.medical_providers;<br>      console.log(&quot;providers data&quot;, this.providers);<br>    });<br>  }<br>}</pre><p><strong>Angular HTML Template:</strong></p><pre>&lt;div *ngIf=&quot;providers&quot;&gt;<br>  &lt;div class=&quot;provider-container&quot;&gt;<br>    &lt;h2&gt;Providers Information&lt;/h2&gt;<br>    &lt;ul class=&quot;provider-list&quot;&gt;<br>      &lt;li *ngFor=&quot;let provider of providers&quot; class=&quot;provider-item&quot;&gt;<br>        &lt;img [src]=&quot;provider.image&quot; [alt]=&quot;provider.firstName + &#39; &#39; + provider.lastName&quot; /&gt;<br>        &lt;div class=&quot;provider-item-details&quot;&gt;<br>          &lt;h3&gt;{{ provider.firstName }} {{ provider.middleName }} {{ provider.lastName }}&lt;/h3&gt;<br>          &lt;p&gt;{{ provider.specialty }}&lt;/p&gt;<br>          &lt;p class=&quot;facility&quot;&gt;{{ provider.facility }}&lt;/p&gt;<br>          &lt;p&gt;<br>            &lt;a [href]=&quot;provider.directionsUrl&quot; class=&quot;contact-info&quot;&gt;Directions&lt;/a&gt; |<br>            &lt;a [href]=&quot;&#39;tel:&#39; + provider.phone&quot; class=&quot;contact-info&quot;&gt;{{ provider.phone }}&lt;/a&gt;<br>          &lt;/p&gt;<br>          &lt;p&gt;Accepting new patients.&lt;/p&gt;<br>          &lt;p&gt;Plans accepted: {{ provider.plansAccepted }}&lt;/p&gt;<br>          &lt;div class=&quot;provider-item-reviews&quot; *ngIf=&quot;provider.reviews?.length&quot;&gt;<br>            &lt;h4&gt;Reviews:&lt;/h4&gt;<br>            &lt;ul class=&quot;provider-reviews-list&quot;&gt;<br>              &lt;li *ngFor=&quot;let review of provider.reviews&quot; class=&quot;provider-reviews-item&quot;&gt;<br>                &lt;p&gt;Rating: {{ review.rating }}&lt;/p&gt;<br>                &lt;p&gt;Comment: {{ review.comment }}&lt;/p&gt;<br>                &lt;p&gt;Author: {{ review.author }}&lt;/p&gt;<br>              &lt;/li&gt;<br>            &lt;/ul&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;provider-item-services&quot; *ngIf=&quot;provider.services?.length&quot;&gt;<br>            &lt;h4&gt;Services:&lt;/h4&gt;<br>            &lt;ul class=&quot;provider-services-list&quot;&gt;<br>              &lt;li *ngFor=&quot;let service of provider.services&quot; class=&quot;provider-services-item&quot;&gt;<br>                &lt;p&gt;Name: {{ service.name }}&lt;/p&gt;<br>                &lt;p&gt;Description: {{ service.description }}&lt;/p&gt;<br>                &lt;p&gt;Price: {{ service.price }}&lt;/p&gt;<br>              &lt;/li&gt;<br>            &lt;/ul&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/li&gt;<br>    &lt;/ul&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p><strong>4. Integration with AEM Components (Optional)</strong> <br>Integration with AEM components involves embedding the client-side JavaScript code within AEM components to enable dynamic rendering. This step is optional because the client-side code can function independently without being tightly coupled to AEM components. However, integrating it can provide a more seamless authoring experience within AEM. <br> <br>To test the client-side code independently, you can follow these steps: <br><strong>1. Implement Authentication for the AEM Server </strong><br>Ensure that your Angular service includes authentication for the AEM server and provides the full URL path for the servlet, including the AEM instance hostname. <br> <br><strong>Angular Service with Authentication:</strong></p><pre>import { HttpClient, HttpHeaders } from &#39;@angular/common/http&#39;;<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class ProviderService {<br>  private basseUrl:string = &#39;http://localhost:4502&#39;;<br>  private apiUrl:string = &#39;/bin/fetchProviderData&#39;;<br><br>  constructor(private http: HttpClient) { }<br><br>  getProviderData(): Observable&lt;any&gt; {<br>    // Replace &#39;username&#39; and &#39;password&#39; with your AEM credentials<br>    const username = &#39;admin&#39;;<br>    const password = &#39;admin&#39;;<br>    const headers = new HttpHeaders({<br>      &#39;Authorization&#39;: &#39;Basic &#39; + btoa(`${username}:${password}`),<br>      &#39;Content-Type&#39;: &#39;application/json&#39;<br>    });<br><br>    return this.http.get&lt;any&gt;(this.basseUrl + this.apiUrl, { headers });<br>  }<br>}</pre><p><strong>2.Disable CORS in Your Browser</strong> <br>After running the Angular project, you should disable your browser’s CORS policy to test the integration. This can be done by using browser extensions or running the browser with specific flags that disable CORS.</p><p>Once the client-side code is tested independently, you can proceed with deploying it to the AEM instance.</p><p><strong>Deploying to AEM Instance</strong></p><p>To integrate the client-side code with AEM components, you can follow these steps: <br><strong>1. Embed Angular Code in AEM Components</strong> <br>Create an AEM component and embed the Angular application within it. You can include the necessary JavaScript files and Angular application entry point in the AEM component’s HTML template. <br> <br><strong>AEM Component Template:</strong></p><pre>&lt;sly data-sly-test=&quot;${wcmmode.edit}&quot;&gt;<br>  &lt;div class=&quot;edit-mode-description&quot;&gt;<br>    &lt;h2&gt;Provider List Component&lt;/h2&gt;<br>    &lt;p&gt;This component displays a list of medical providers retrieved from a third-party API. In author mode, this placeholder text provides information about the component&#39;s functionality.&lt;/p&gt;<br>    &lt;p&gt;When this component is rendered in publish mode, it fetches and displays the provider details such as name, specialty, facility, contact information, and more. &lt;/p&gt;<br>    &lt;p&gt;Ensure that the API endpoint is correctly configured on the configuration manager (http://localhost:4502/system/console/configMgr) page.&lt;/p&gt;<br>    &lt;p&gt;Note: This message is only visible in edit mode. In publish mode, when the page is opened using &quot;view as published,&quot; the provider information will be visible.&lt;/p&gt;<br>  &lt;/div&gt;<br>&lt;/sly&gt;<br>&lt;sly data-sly-test=&quot;${!wcmmode.edit}&quot;&gt;<br>  &lt;div&gt;<br>    &lt;app-root&gt;&lt;/app-root&gt;<br>  &lt;/div&gt;<br>&lt;/sly&gt;</pre><p><strong>2. Build and Deploy the Project </strong><br>Use Maven to build and deploy your project, including the Angular application and other modules. This command will compile the Angular application, package all project modules, and deploy them to the AEM instance. It also handles copying the Angular generated dist files to the appropriate AEM client libraries.</p><p><strong>Building and Deploying the Project:</strong></p><pre>mvn clean install -PautoInstallPackage</pre><p>This command performs the following tasks:</p><ul><li>Builds the Angular application using the Angular CLI.</li><li>Packages the Angular application files and other project modules into an AEM content package.</li><li>Deploys the content package to the AEM instance.</li><li>Copies the Angular build files to the AEM client libraries, ensuring they are available for client-side rendering.</li></ul><p>By following these steps, you can integrate third-party APIs into AEM 6.5 using Client-Side Rendering, providing a dynamic and interactive user experience within your AEM components. This approach leverages Angular’s capabilities to deliver a rich user interface while maintaining seamless integration with AEM’s backend.</p><p><strong>GitHub Repository</strong> <br>For a practical implementation of integrating third-party APIs into AEM 6.5 with the client-Side Rendering approach, check out the <a href="https://github.com/HabtamuTesfie/aem-third-party-api-integration-using-client-side-rendering-approach">GitHub repository for this project.</a> The repository includes a detailed README file with important procedures for testing the project locally.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1c07933bbdf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Third-Party APIs into AEM 6.5 with Server-Side Rendering Approach]]></title>
            <link>https://medium.com/@habtamutesfie/integrating-third-party-apis-in-aem-da188e910b7d?source=rss-f42f01f8cee8------2</link>
            <guid isPermaLink="false">https://medium.com/p/da188e910b7d</guid>
            <dc:creator><![CDATA[Habtamu Tesfie]]></dc:creator>
            <pubDate>Wed, 24 Jul 2024 13:33:45 GMT</pubDate>
            <atom:updated>2024-08-06T06:06:57.363Z</atom:updated>
            <content:encoded><![CDATA[<p>Integrating third-party APIs into Adobe Experience Manager (AEM) can be approached in two primary ways: Server-Side Rendering (SSR) and Client-Side Rendering (CSR). This blog will focus on the SSR approach, which is ideal for SEO, initial page load performance, and content-heavy pages.<br>For more information on the client-Side Rendering approach, you can refer to this <a href="https://medium.com/@habtamutesfie/integrating-third-party-apis-into-aem-6-5-with-client-side-rendering-approach-f1c07933bbdf">article</a>.</p><h4>Steps to Integrate Third-Party APIs Using Server-Side Rendering in AEM</h4><ol><li><strong>Create an OSGi Service Layer</strong><br>Develop an OSGi service responsible for interacting with the third-party API. This service will handle API requests and process responses.</li></ol><pre>package et.com.aem.core.services;<br><br>import et.com.aem.core.api.MedicalProviders;<br><br>public interface ProviderService {<br>    MedicalProviders getProviderData();<br>}</pre><p><strong>2. Expose Operations<br></strong>Define methods within the service to perform various operations required by the integration and expose these operations from the third-party API through methods in the OSGi service. Before diving into the code, it is crucial to consider implementing best practices. These include fault tolerance mechanisms to handle potential API failures gracefully, ensuring security through secure communication and authentication with the third-party API, and implementing comprehensive logging and monitoring to track the service’s performance and identify potential issues quickly. Additionally, consider using caching to reduce the load on the third-party API and improve response times for frequently requested data.</p><pre>package et.com.aem.core.services;<br><br>import com.google.gson.Gson;<br>import et.com.aem.core.api.MedicalProviders;<br>import et.com.aem.core.config.ProviderServiceConfig;<br>import org.apache.http.HttpEntity;<br>import org.apache.http.client.methods.CloseableHttpResponse;<br>import org.apache.http.client.methods.HttpGet;<br>import org.apache.http.impl.client.CloseableHttpClient;<br>import org.apache.http.impl.client.HttpClients;<br>import org.apache.http.util.EntityUtils;<br>import org.osgi.service.component.annotations.Activate;<br>import org.osgi.service.component.annotations.Component;<br>import org.osgi.service.component.annotations.Modified;<br>import org.osgi.service.metatype.annotations.Designate;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br><br>import java.io.IOException;<br><br>@Component(service = ProviderService.class, immediate = true)<br>@Designate(ocd = ProviderServiceConfig.class)<br>public class ProviderServiceImpl implements ProviderService {<br><br>    private static final Logger LOG = LoggerFactory.getLogger(ProviderServiceImpl.class);<br><br>    private String providerApiUrl;<br><br>    @Activate<br>    @Modified<br>    protected void activate(ProviderServiceConfig config) {<br>        this.providerApiUrl = config.apiUrl();<br>    }<br><br>    @Override<br>    public MedicalProviders getProviderData() {<br>        LOG.info(&quot;The provided url is {}&quot;, providerApiUrl);<br>        String jsonData = &quot;&quot;;<br>        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {<br>            HttpGet request = new HttpGet(providerApiUrl);<br>            try (CloseableHttpResponse response = httpClient.execute(request)) {<br>                HttpEntity entity = response.getEntity();<br>                if (entity != null) {<br>                    jsonData = EntityUtils.toString(entity);<br>                }<br>            }<br>        } catch (IOException e) {<br>            LOG.error(&quot;Error fetching data from URL: {}&quot;, providerApiUrl, e);<br>        }<br><br>        Gson gson = new Gson();<br>        return gson.fromJson(jsonData, MedicalProviders.class);<br>    }<br>}</pre><ul><li><strong>@Component</strong>: Defines the class as an OSGi component. service = ProviderService.class indicates that this component provides an implementation for the ProviderService interface.</li><li><strong>@Designate</strong>: Associates the component with a configuration class (ProviderServiceConfig).</li><li><strong>@Activate</strong> and <strong>@Modified</strong>: Methods annotated with @Activate are called when the component is activated, and methods annotated with @Modified are called when the component configuration is updated.</li></ul><p><strong>3. Configuration<br></strong>Create an OSGi configuration to store the API URL and other configuration parameters.</p><pre>package et.com.aem.core.config;<br><br>import org.osgi.service.metatype.annotations.AttributeDefinition;<br>import org.osgi.service.metatype.annotations.ObjectClassDefinition;<br><br>@ObjectClassDefinition(name = &quot;Provider Service Configuration Url&quot;)<br>public @interface ProviderServiceConfig {<br>    @AttributeDefinition(name = &quot;Provider API URL&quot;, description = &quot;URL for the Provider API&quot;)<br>    String apiUrl();<br>}</pre><p><strong>4. Sling Models for Server-Side Components<br></strong>Create Sling Models for AEM components that will display data fetched from the third-party API. Inject the OSGi service into these Sling Models using the @OSGiService annotation.</p><pre>package et.com.aem.core.models;<br><br>import com.google.gson.Gson;<br>import et.com.aem.core.api.MedicalProvider;<br>import et.com.aem.core.api.MedicalProviders;<br>import et.com.aem.core.services.ProviderService;<br>import org.apache.sling.api.resource.Resource;<br>import org.apache.sling.models.annotations.DefaultInjectionStrategy;<br>import org.apache.sling.models.annotations.Model;<br>import org.apache.sling.models.annotations.injectorspecific.ValueMapValue;<br>import org.apache.sling.models.annotations.injectorspecific.OSGiService;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br><br>import javax.annotation.PostConstruct;<br>import java.util.List;<br><br>@Model(adaptables = Resource.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)<br>public class ProviderModel {<br><br>    private static final Logger LOG = LoggerFactory.getLogger(ProviderModel.class);<br><br>    @OSGiService<br>    private ProviderService providerService;<br><br>    @ValueMapValue<br>    private String title;<br><br>    private List&lt;MedicalProvider&gt; providers;<br><br>    @PostConstruct<br>    protected void init() {<br>        MedicalProviders medicalProviders = providerService.getProviderData();<br>        if (medicalProviders != null &amp;&amp; !medicalProviders.getMedicalProviders().isEmpty()) {<br>            this.providers = medicalProviders.getMedicalProviders();<br>            LOG.info(&quot;Provider data initialized: {}&quot;, new Gson().toJson(providers));<br>        } else {<br>            LOG.error(&quot;Received empty or null JSON data from the provider service&quot;);<br>        }<br>    }<br><br>    public List&lt;MedicalProvider&gt; getProviders() {<br>        return providers;<br>    }<br><br>    public String getTitle() {<br>        return title;<br>    }<br>}</pre><p><strong>5. Create Custom AEM Component<br></strong>Develop a custom AEM component and populate its HTML template with the provided code. This component will use the Sling Model to fetch and render data from the third-party API.</p><p><strong>Component Definition</strong>: Create a new component in AEM under /apps/your-project/components/apiintegrationcomponent.</p><p>apiintegrationcomponent.html</p><pre>&lt;sly data-sly-use.provider=&quot;et.com.aem.core.models.ProviderModel&quot;&gt;<br>  &lt;h2&gt;${provider.title}&lt;/h2&gt;<br>  &lt;div class=&quot;provider-container&quot;&gt;<br>    &lt;h2&gt;Providers Information&lt;/h2&gt;<br>    &lt;ul class=&quot;provider-list&quot;&gt;<br>      &lt;sly data-sly-list.provider=&quot;${provider.providers}&quot;&gt;<br>        &lt;li class=&quot;provider-item&quot;&gt;<br>          &lt;img src=&quot;${provider.image}&quot; alt=&quot;${provider.firstName} ${provider.lastName}&quot; /&gt;<br>          &lt;div class=&quot;provider-item-details&quot;&gt;<br>            &lt;h3&gt;${provider.firstName} ${provider.middleName} ${provider.lastName}&lt;/h3&gt;<br>            &lt;p&gt;${provider.specialty}&lt;/p&gt;<br>            &lt;p class=&quot;facility&quot;&gt;${provider.facility}&lt;/p&gt;<br>            &lt;p&gt;&lt;a href=&quot;${provider.directionsUrl}&quot; class=&quot;contact-info&quot;&gt;Directions&lt;/a&gt; | &lt;a href=&quot;tel:${provider.phone}&quot; class=&quot;contact-info&quot;&gt;${provider.phone}&lt;/a&gt;&lt;/p&gt;<br>            &lt;p&gt;Accepting new patients.&lt;/p&gt;<br>            &lt;p&gt;Plans accepted: ${provider.plansAccepted}&lt;/p&gt;<br>            &lt;div class=&quot;provider-item-reviews&quot;&gt;<br>              &lt;h4&gt;Reviews:&lt;/h4&gt;<br>              &lt;ul class=&quot;provider-reviews-list&quot;&gt;<br>                &lt;sly data-sly-list.review=&quot;${provider.reviews}&quot;&gt;<br>                  &lt;li class=&quot;provider-reviews-item&quot;&gt;<br>                    &lt;p&gt;Rating: ${review.rating}&lt;/p&gt;<br>                    &lt;p&gt;Comment: ${review.comment}&lt;/p&gt;<br>                    &lt;p&gt;Author: ${review.author}&lt;/p&gt;<br>                  &lt;/li&gt;<br>                &lt;/sly&gt;<br>              &lt;/ul&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;provider-item-services&quot;&gt;<br>              &lt;h4&gt;Services:&lt;/h4&gt;<br>              &lt;ul class=&quot;provider-services-list&quot;&gt;<br>                &lt;sly data-sly-list.service=&quot;${provider.services}&quot;&gt;<br>                  &lt;li class=&quot;provider-services-item&quot;&gt;<br>                    &lt;p&gt;Name: ${service.name}&lt;/p&gt;<br>                    &lt;p&gt;Description: ${service.description}&lt;/p&gt;<br>                    &lt;p&gt;Price: ${service.price}&lt;/p&gt;<br>                  &lt;/li&gt;<br>                &lt;/sly&gt;<br>              &lt;/ul&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/li&gt;<br>      &lt;/sly&gt;<br>    &lt;/ul&gt;<br>  &lt;/div&gt;<br>&lt;/sly&gt;</pre><p><strong>6. Testing the Implementation<br></strong>To test the implementation locally, please clone the project from the following repository: <a href="https://github.com/HabtamuTesfie/AEM-Third-Party-API-Integration">Github Link</a></p><p>After cloning the project, refer to the README.md file included in the repository for detailed instructions on how to set up and execute the project. This file provides comprehensive steps to ensure that the implementation can be successfully tested in your local environment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da188e910b7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>