<?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 Zubair Idrees on Medium]]></title>
        <description><![CDATA[Stories by Zubair Idrees on Medium]]></description>
        <link>https://medium.com/@zubairidrees.cs?source=rss-1dfd2d53282f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RBm7xhrbVFPsTtc_.</url>
            <title>Stories by Zubair Idrees on Medium</title>
            <link>https://medium.com/@zubairidrees.cs?source=rss-1dfd2d53282f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:38:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zubairidrees.cs/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[Unleashing the Power of GraphQL with Spring Boot: A Modern Approach to API Development]]></title>
            <link>https://medium.com/@zubairidrees.cs/unleashing-the-power-of-graphql-with-spring-boot-a-modern-approach-to-api-development-e95a6685d364?source=rss-1dfd2d53282f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e95a6685d364</guid>
            <dc:creator><![CDATA[Zubair Idrees]]></dc:creator>
            <pubDate>Sun, 20 Oct 2024 08:10:24 GMT</pubDate>
            <atom:updated>2024-10-20T08:10:24.461Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s rapidly evolving tech landscape, the need for efficient and flexible data management has led to the rise of GraphQL, a query language for APIs developed by Facebook in 2012. GraphQL was created to address the limitations of traditional REST APIs, particularly in handling complex data-fetching requirements. Unlike REST, where clients may need to make multiple requests to fetch related data, GraphQL allows clients to request exactly what they need in a single request, improving performance and reducing bandwidth consumption. Major companies like Facebook, GitHub, Shopify, and Twitter have adopted GraphQL for its efficiency and flexibility, making it a popular choice for modern web development.</p><h3>Why GraphQL Over REST?</h3><p>While REST APIs have served as the backbone of web services for years, they come with challenges such as over-fetching and under-fetching of data. With REST, a client often receives more data than needed or has to make multiple requests to gather related information. GraphQL addresses these issues by allowing clients to specify their data requirements precisely. Here are some key benefits of using GraphQL over REST:</p><ul><li><strong>Single Endpoint</strong>: Unlike REST APIs, which require multiple endpoints for different resources, GraphQL uses a single endpoint to handle all requests, simplifying the API structure.</li><li><strong>Efficient Data Fetching</strong>: Clients can request only the data they need, resulting in reduced payload sizes and improved performance.</li><li><strong>Strongly Typed Schema</strong>: GraphQL’s schema defines the types and relationships in the data model, making it easier to understand and work with.</li><li><strong>Automatic Input Generation</strong>: In GraphQL, input types are defined in the schema, automatically generating the necessary data transfer objects (DTOs) for mutations and queries, eliminating the boilerplate code often associated with REST.</li><li><strong>Resolver Pattern</strong>: Instead of controllers, GraphQL uses resolvers, which are functions responsible for fetching the data for each field in the schema. This allows for better separation of concerns and cleaner code.</li></ul><h3>Getting Started with Spring Boot and GraphQL</h3><h3>Prerequisites</h3><ul><li><strong>Java 21</strong></li><li><strong>Maven</strong></li></ul><h3>Clone the Repository</h3><p>To get started, clone the repository containing the sample project:</p><pre>it clone https://github.com/zubairidrees/graph-ql.git<br>cd graph-ql</pre><h3>Build and Run the Application</h3><p>To build the project and generate the necessary sources, execute:</p><pre>mvn clean generate-sources install</pre><p>Once the build is successful, you can run the application with:</p><pre>mvn spring-boot:run</pre><p>The application will be accessible at <a href="http://localhost:8080/graphql.">http://localhost:8080/graphql.</a></p><h3>Schema and Resolvers</h3><p>GraphQL schemas define the types and structure of your data. The project includes a schema file where you can define queries and mutations. Here’s a brief look at the key components:</p><ul><li><strong>Mutation Resolver</strong>: This handles the creation of new records. For example, here’s a mutation for creating a department:</li></ul><pre>@DgsComponent<br>public class MutationResolver {<br>    private final DepartmentRepository departmentRepository;<br>public MutationResolver(DepartmentRepository departmentRepository) {<br>        this.departmentRepository = departmentRepository;<br>    }<br>    @DgsMutation<br>    public Department createDepartment(@InputArgument DepartmentInput input) {<br>        Department department = new Department();<br>        department.setName(input.getName());<br>        return departmentRepository.save(department);<br>    }<br>}</pre><ul><li><strong>Query Resolver</strong>: This retrieves data from the database. Here’s an example of a query resolver that fetches all departments:</li></ul><pre>@DgsComponent<br>public class QueryResolver {<br>    private final DepartmentRepository departmentRepository;<br>public QueryResolver(DepartmentRepository departmentRepository) {<br>        this.departmentRepository = departmentRepository;<br>    }<br>    @DgsQuery<br>    public List&lt;Department&gt; departments() {<br>        return departmentRepository.findAll();<br>    }<br>}</pre><h3>Postman Queries and Mutations</h3><p>Use Postman to test your GraphQL API by sending queries and mutations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GNXiObBeMx7tGmUaWkixPg.png" /><figcaption>Mutation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*docqj1YNghIgLzKSxPRmIw.png" /><figcaption>Query</figcaption></figure><h3>Conclusion</h3><p>GraphQL offers numerous advantages over traditional REST APIs, making it a powerful choice for modern applications. By leveraging Spring Boot and GraphQL, developers can create flexible, efficient APIs that meet the demands of today’s applications. For a full example and further exploration, refer to the project on <a href="https://github.com/zubairidrees/graph-ql">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e95a6685d364" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka in Action: A Step-by-Step Guide to Building with Spring Boot and Docker]]></title>
            <link>https://medium.com/@zubairidrees.cs/kafka-in-action-a-step-by-step-guide-to-building-with-spring-boot-and-docker-91411a895b5c?source=rss-1dfd2d53282f------2</link>
            <guid isPermaLink="false">https://medium.com/p/91411a895b5c</guid>
            <dc:creator><![CDATA[Zubair Idrees]]></dc:creator>
            <pubDate>Sun, 13 Oct 2024 15:14:56 GMT</pubDate>
            <atom:updated>2024-10-13T15:14:56.012Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p><strong>Apache Kafka</strong> is a powerful distributed event streaming platform that allows you to publish, subscribe to, and process streams of records in real time. It is widely used for handling large volumes of data and is ideal for scenarios like event logging, real-time analytics, and microservices communication.</p><p>In this blog post, we will setup Kafka using Docker Compose and integrating it with a Spring Boot application. We’ll cover the core components of Kafka, demonstrate a basic setup, and show how to publish and consume messages via a REST API.</p><h3>Use Cases</h3><p>Kafka is versatile and can be applied in various scenarios, including:</p><ul><li><strong>Log Aggregation</strong>: Collecting logs from multiple services for centralized analysis.</li><li><strong>Real-time Analytics</strong>: Processing data streams in real time for immediate insights.</li><li><strong>Data Pipelines</strong>: Facilitating data transfer between different systems.</li></ul><h3>Core Components of Kafka</h3><p>Before we proceed with the setup, here’s a brief overview of Kafka’s core components:</p><ol><li><strong>Producer</strong>: An application that publishes messages to Kafka topics.</li><li><strong>Consumer</strong>: An application that subscribes to topics and processes the published messages.</li><li><strong>Broker</strong>: A Kafka server that stores data and serves requests.</li><li><strong>Topic</strong>: A category or feed name for messages.</li></ol><h3>Setting Up Kafka with Docker Compose</h3><h3>Docker Compose Configuration</h3><p>We’ll use Docker Compose to easily set up our Kafka environment. Below is a placeholder for the docker-compose.yml file:</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  zookeeper:<br>    image: confluentinc/cp-zookeeper:7.4.0<br>    container_name: zookeeper<br>    environment:<br>      ZOOKEEPER_CLIENT_PORT: 2181<br>      ZOOKEEPER_TICK_TIME: 2000<br>    ports:<br>      - &quot;2181:2181&quot;<br>    networks:<br>      - kafka-net<br><br>  kafka-broker-1:<br>    image: confluentinc/cp-kafka:7.4.0<br>    container_name: kafka-broker-1<br>    ports:<br>      - &quot;9092:9092&quot;<br>      - &quot;9991:9991&quot;  <br>    environment:<br>      KAFKA_BROKER_ID: 1<br>      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181<br>      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka-broker-1:9092<br>      KAFKA_LISTENERS: PLAINTEXT://0.0.0.0:9092<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br>      KAFKA_LOG_RETENTION_HOURS: 168<br>      KAFKA_AUTO_CREATE_TOPICS_ENABLE: &quot;true&quot;<br>      KAFKA_JMX_PORT: 9991<br>      KAFKA_JMX_HOSTNAME: kafka-broker-1<br>      KAFKA_OPTS: &quot;-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=kafka-broker-1 -Dcom.sun.management.jmxremote.rmi.port=9991&quot;<br>    depends_on:<br>      - zookeeper<br>    networks:<br>      - kafka-net<br><br>  kafka-broker-2:<br>    image: confluentinc/cp-kafka:7.4.0<br>    container_name: kafka-broker-2<br>    ports:<br>      - &quot;9093:9093&quot;<br>      - &quot;9992:9992&quot; <br>    environment:<br>      KAFKA_BROKER_ID: 2<br>      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181<br>      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka-broker-2:9093<br>      KAFKA_LISTENERS: PLAINTEXT://0.0.0.0:9093<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br>      KAFKA_LOG_RETENTION_HOURS: 168<br>      KAFKA_AUTO_CREATE_TOPICS_ENABLE: &quot;true&quot;<br>      KAFKA_JMX_PORT: 9992<br>      KAFKA_JMX_HOSTNAME: kafka-broker-2<br>      KAFKA_OPTS: &quot;-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=kafka-broker-2 -Dcom.sun.management.jmxremote.rmi.port=9992&quot;<br>    depends_on:<br>      - zookeeper<br>    networks:<br>      - kafka-net<br><br>  kafka-broker-3:<br>    image: confluentinc/cp-kafka:7.4.0<br>    container_name: kafka-broker-3<br>    ports:<br>      - &quot;9094:9094&quot;<br>      - &quot;9993:9993&quot;  <br>    environment:<br>      KAFKA_BROKER_ID: 3<br>      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181<br>      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka-broker-3:9094<br>      KAFKA_LISTENERS: PLAINTEXT://0.0.0.0:9094<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br>      KAFKA_LOG_RETENTION_HOURS: 168<br>      KAFKA_AUTO_CREATE_TOPICS_ENABLE: &quot;true&quot;<br>      KAFKA_JMX_PORT: 9993<br>      KAFKA_JMX_HOSTNAME: kafka-broker-3<br>      KAFKA_OPTS: &quot;-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=kafka-broker-3 -Dcom.sun.management.jmxremote.rmi.port=9993&quot;<br>    depends_on:<br>      - zookeeper<br>    networks:<br>      - kafka-net<br><br>  cmak:<br>    image: ghcr.io/eshepelyuk/dckr/cmak-3.0.0.5:latest<br>    container_name: cmak<br>    restart: always<br>    ports:<br>      - &quot;9000:9000&quot;<br>    command:<br>      - &quot;-Dcmak.zkhosts=zookeeper:2181&quot;<br>      - &quot;-Dcmak.kafka.manager.brokerlist=kafka-broker-1:9092,kafka-broker-2:9093,kafka-broker-3:9094&quot;<br>    depends_on:<br>      - zookeeper<br>      - kafka-broker-1<br>      - kafka-broker-2<br>      - kafka-broker-3<br>    networks:<br>      - kafka-net<br><br>  app:<br>    image: messaging-app  <br>    container_name: messaging-app<br>    ports:<br>      - &quot;8080:8080&quot; <br>    depends_on:<br>      - kafka-broker-1<br>      - kafka-broker-2<br>      - kafka-broker-3<br>    networks:<br>      - kafka-net<br><br>networks:<br>  kafka-net:<br>    driver: bridge</pre><h3>Starting the Docker Compose Setup</h3><p>To start your Kafka environment, run the following command in the directory with your docker-compose.yml file:</p><pre>docker-compose up -d</pre><p>This will start all the services, including Kafka and CMAK (Cluster Manager for Apache Kafka).</p><h3>CMAK Introduction</h3><p>CMAK provides a user-friendly web interface for managing Kafka clusters. It allows you to monitor cluster health, manage topics, and view consumer groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LfWTEwUBH9fXqovqq45BAg.png" /><figcaption>Screenshot of the CMAK interface</figcaption></figure><h3>Spring Boot Configuration</h3><p>In our Spring Boot application, we need to configure both the Kafka producer and consumer. Below are placeholders for the Java configuration files.</p><h3>Kafka Consumer Configuration</h3><pre>@Configuration<br>@EnableKafka<br>public class KafkaConsumerConfig {<br><br>    @Bean<br>    public ConsumerFactory&lt;String, String&gt; consumerFactory() {<br>        Map&lt;String, Object&gt; props = new HashMap&lt;&gt;();<br>        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, &quot;kafka-broker-1:9092,kafka-broker-2:9093,kafka-broker-3:9094&quot;);<br>        props.put(ConsumerConfig.GROUP_ID_CONFIG, &quot;my-group&quot;);<br>        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, &quot;earliest&quot;);<br>        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);<br>        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);<br>        return new DefaultKafkaConsumerFactory&lt;&gt;(props);<br>    }<br><br>    @Bean<br>    public ConcurrentKafkaListenerContainerFactory&lt;String, String&gt;<br>    kafkaListenerContainerFactory() {<br><br>        ConcurrentKafkaListenerContainerFactory&lt;String, String&gt; factory =<br>                new ConcurrentKafkaListenerContainerFactory&lt;&gt;();<br>        factory.setConsumerFactory(consumerFactory());<br>        return factory;<br>    }<br>}</pre><p>Kafka Producer Configuration</p><pre>@Configuration<br>public class KafkaProducerConfig {<br><br>    @Bean<br>    public ProducerFactory&lt;String, String&gt; producerFactory() {<br>        Map&lt;String, Object&gt; configProps = new HashMap&lt;&gt;();<br>        configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, &quot;kafka-broker-1:9092,kafka-broker-2:9093,kafka-broker-3:9094&quot;);<br>        configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);<br>        configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);<br>        // Configure partitioner if needed<br>        return new DefaultKafkaProducerFactory&lt;&gt;(configProps);<br>    }<br><br>    @Bean<br>    public KafkaTemplate&lt;String, String&gt; kafkaTemplate() {<br>        return new KafkaTemplate&lt;&gt;(producerFactory());<br>    }<br>}</pre><p>Message Publishing Controller</p><pre><br>@RestController<br>@RequestMapping(&quot;/kafka&quot;)<br>public class KafkaProducerController {<br><br>    private final KafkaProducerService producerService;<br><br>    public KafkaProducerController(KafkaProducerService producerService) {<br>        this.producerService = producerService;<br>    }<br><br>    @PostMapping(&quot;/publish&quot;)<br>    public String publishMessage(@RequestParam String key, @RequestParam String message) {<br>        producerService.sendMessage(key, message);<br>        return &quot;Message published successfully&quot;;<br>    }<br>}</pre><h3>Creating the Spring Boot Application Docker Image</h3><p>If you have already added a Dockerfile to your Spring Boot project, you can build the Docker image with the following command:</p><pre>docker build -t messaging-app .</pre><h3>Testing the Setup</h3><h3>Sending Messages with Curl</h3><p>Once your application is running, you can test message publishing using curl:</p><pre>curl -X POST &quot;http://localhost:8080/kafka/publish?key=myKey&amp;message=Hello+from+Kafka&quot;</pre><p>This command sends a message to your Kafka topic, confirming that everything is working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iaYoDIMB5r5saagev4owOg.png" /><figcaption>Verifying Message Consumption</figcaption></figure><h3>Code Reference</h3><p>For a complete code reference, please visit our GitHub repository: <a href="https://github.com/zubairidrees/kafka/tree/master">GitHub — zubairidrees/kafka</a></p><h3>Conclusion</h3><p>In this post, we set up Apache Kafka with Docker Compose and integrated it with a Spring Boot application. We explored Kafka’s core components and demonstrated how to publish and consume messages through a REST API.</p><p>Kafka is a robust solution for managing real-time data streams and can significantly enhance your application’s data processing capabilities. Explore further to discover more complex configurations and use cases!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91411a895b5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Scaling for JMS Listeners: Optimize Performance Without Restarting in Spring Boot]]></title>
            <link>https://medium.com/@zubairidrees.cs/dynamic-jms-listener-concurrency-management-in-spring-boot-with-solace-3cef8e9ab505?source=rss-1dfd2d53282f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cef8e9ab505</guid>
            <dc:creator><![CDATA[Zubair Idrees]]></dc:creator>
            <pubDate>Mon, 07 Oct 2024 17:38:51 GMT</pubDate>
            <atom:updated>2024-10-20T08:16:05.576Z</atom:updated>
            <content:encoded><![CDATA[<p>Managing message load efficiently is essential in JMS-based systems. By default, the number of consumers (listeners) is statically configured, which can be limiting when message traffic fluctuates. In this blog, we’ll demonstrate how to dynamically adjust the concurrency of JMS listeners in a Spring Boot application integrated with Solace, without requiring a restart.</p><h3>Why Dynamic Concurrency?</h3><p>When message volume increases, more consumers are needed to process the messages faster. On the other hand, during low traffic, fewer consumers can help conserve resources. Adjusting concurrency dynamically allows the system to handle both scenarios optimally.</p><h3>Solution Overview</h3><p>We will build a Spring Boot REST API that allows us to dynamically change the number of JMS consumers based on incoming traffic. The core components of our solution include:</p><ul><li>A REST endpoint to update concurrency.</li><li>A service that modifies the concurrency of JMS listeners.</li><li>Solace configuration to integrate the messaging system.</li></ul><h3>1. Expose an API for Concurrency Updates</h3><p>We create a simple REST endpoint to accept minimum and maximum consumer values, which will trigger the concurrency update for JMS listeners.</p><pre>@RestController<br>public class JmsController {    <br>@Autowired<br>    private JmsListenerConcurrencyService jmsService;<br>@PostMapping(&quot;/updateConcurrency&quot;)<br>    public void updateConcurrency(@RequestParam int minConsumers, @RequestParam int maxConsumers) {<br>        jmsService.updateConcurrency(minConsumers, maxConsumers);<br>    }<br>}</pre><p>This controller exposes an endpoint /updateConcurrency which accepts the minConsumers and maxConsumers parameters.</p><h3>2. Service to Handle Concurrency Changes</h3><p>This service accesses the JMS listener containers and adjusts their concurrency using the provided min and max values.</p><pre>@Service<br>public class JmsListenerConcurrencyService {<br>@Autowired<br>    private JmsListenerEndpointRegistry registry;<br>    public void updateConcurrency(int minConsumers, int maxConsumers) {<br>        registry.getListenerContainers()<br>                .stream()<br>                .filter(container -&gt; container instanceof DefaultMessageListenerContainer)<br>                .map(container -&gt; (DefaultMessageListenerContainer) container)<br>                .forEach(container -&gt; {<br>                    container.setConcurrency(minConsumers + &quot;-&quot; + maxConsumers);<br>                    container.initialize();<br>                    container.start();<br>                });<br>    }<br>}</pre><p>The JmsListenerConcurrencyService gets the list of listener containers, updates the concurrency, re-initializes, and restarts them to apply the new configuration.</p><h3>3. Solace Configuration for JMS</h3><p>We need to configure Solace as the messaging broker for JMS. The configuration sets up the connection factory and listener container factory.</p><pre>@Configuration<br>@EnableJms<br>public class JmsConfig {<br>@Autowired<br>    private SolaceProperties solaceProperties;<br>    @Autowired<br>    private ExternalPropertiesProvider externalPropertiesProvider;<br>    @Bean<br>    public ConnectionFactory connectionFactory() {<br>        SolConnectionFactory solConnectionFactory = new SolConnectionFactoryImpl();<br>        solConnectionFactory.setHost(solaceProperties.getHost());<br>        solConnectionFactory.setUsername(solaceProperties.getClientUsername());<br>        solConnectionFactory.setPassword(solaceProperties.getSolacePassword());<br>        solConnectionFactory.setVPN(solaceProperties.getMsgVpn());<br>        solConnectionFactory.setClientID(solaceProperties.getClientName());<br>        return new CachingConnectionFactory(solConnectionFactory);<br>    }<br>    @Bean<br>    public DefaultJmsListenerContainerFactory jmsListenerContainerFactory(ConnectionFactory connectionFactory) {<br>        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();<br>        factory.setConnectionFactory(connectionFactory);<br>        factory.setConcurrency(&quot;3&quot;);  // Initial concurrency<br>        return factory;<br>    }<br>}</pre><p>This configuration integrates the Solace messaging system using SolConnectionFactory and sets an initial concurrency of 3.</p><h3>4. Sample application.yml for Solace Properties</h3><p>Here’s a dummy application.yml that holds the Solace configuration.</p><pre>solace:<br>  host: tcp://localhost:55555<br>  clientUsername: solace-client<br>  clientName: my-client<br>  msgVpn: default-vpn<br>  solacePassword: your-solace-password</pre><p>This file provides Solace connection details and the external service password.</p><h3>Testing the Setup</h3><p>To test this setup, follow these steps:</p><ol><li><strong>Start the application</strong>: Initially, it will use the default concurrency (e.g., 3 consumers).</li></ol><p><strong>Before scaling:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XE3WFlXRPPCBQtFTorhIuw.png" /></figure><p><strong>2. Make an API request</strong> to dynamically change the concurrency based on the load:</p><pre>POST /updateConcurrency?minConsumers=5&amp;maxConsumers=10</pre><p><strong>After scaling:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eDO0eTVJIyvaz6V_5oQrBg.png" /></figure><h3>Conclusion</h3><p>Dynamic concurrency management in JMS allows your application to handle message surges effectively by scaling consumers up or down based on the load. This solution ensures resource efficiency while maintaining optimal message processing, all through a simple REST API.</p><p>By integrating dynamic concurrency management with Solace, your application becomes more flexible, enabling it to adapt to varying traffic conditions seamlessly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cef8e9ab505" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Reactive Functions in Java with Project Reactor]]></title>
            <link>https://medium.com/@zubairidrees.cs/mastering-reactive-functions-in-java-with-project-reactor-ba256e9ee8cf?source=rss-1dfd2d53282f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba256e9ee8cf</guid>
            <dc:creator><![CDATA[Zubair Idrees]]></dc:creator>
            <pubDate>Sat, 28 Sep 2024 06:40:38 GMT</pubDate>
            <atom:updated>2024-09-28T06:40:38.048Z</atom:updated>
            <content:encoded><![CDATA[<p>Reactive programming is an approach that allows for building asynchronous, non-blocking applications. In this blog, we will delve into various methods available in Project Reactor’s Mono type, enhancing our ability to handle data streams effectively.</p><h3>1. doOnError()</h3><p>The doOnError method allows you to specify a side effect when an error occurs during the processing of a Mono. This is useful for logging errors or performing cleanup tasks.</p><p><strong>Example:</strong></p><pre>Mono&lt;String&gt; errorMono = Mono.error(new RuntimeException(&quot;An error occurred&quot;))<br>    .doOnError(e -&gt; System.err.println(&quot;Error: &quot; + e.getMessage()));<br><br>errorMono.subscribe(System.out::println, <br>                    error -&gt; System.err.println(&quot;Subscription error: &quot; + error.getMessage()));</pre><h3>2. doFinally()</h3><p>The doFinally method is executed when a Mono completes, whether successfully or with an error. This is useful for resource cleanup or logging completion signals.</p><p><strong>Example:</strong></p><pre>Mono&lt;String&gt; finallyMono = Mono.just(&quot;Data&quot;)<br>    .doFinally(signalType -&gt; System.out.println(&quot;Finished with signal: &quot; + signalType));<br><br>finallyMono.subscribe(System.out::println);</pre><h3>3. onErrorResume()</h3><p>onErrorResume allows you to provide an alternative Mono if an error occurs. This can be useful for fallback mechanisms.</p><p><strong>Example:</strong></p><pre>Mono&lt;String&gt; errorHandlingMono = Mono.error(new RuntimeException(&quot;Failed!&quot;))<br>    .onErrorResume(e -&gt; Mono.just(&quot;Recovered from error: &quot; + e.getMessage()));<br><br>errorHandlingMono.subscribe(System.out::println); // Prints: Recovered from error: Failed!</pre><h3>4. doOnSuccess()</h3><p>This method allows you to execute a side effect when a Mono completes successfully. It&#39;s often used for logging purposes.</p><p><strong>Example:</strong></p><pre>Mono&lt;String&gt; successMono = Mono.just(&quot;Operation successful&quot;)<br>    .doOnSuccess(result -&gt; System.out.println(&quot;Success: &quot; + result));<br><br>successMono.subscribe();</pre><h3>5. flatMap()</h3><p>flatMap transforms the emitted value of a Mono into another Mono. It is particularly useful when dealing with asynchronous operations that return another Mono.</p><p><strong>Example:</strong></p><pre>Mono&lt;String&gt; flatMappedMono = Mono.just(&quot;42&quot;)<br>    .flatMap(value -&gt; Mono.just(&quot;Value is: &quot; + value));<br>flatMappedMono.subscribe(System.out::println); // Prints: Value is: 42</pre><h3>6. flatMapMany()</h3><p>flatMapMany is used to convert a Mono into a Flux, allowing multiple values to be emitted. This is useful when you want to work with collections.</p><p><strong>Example:</strong></p><pre>Mono&lt;List&lt;String&gt;&gt; listMono = Mono.just(Arrays.asList(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;));<br>Flux&lt;String&gt; flux = listMono.flatMapMany(Flux::fromIterable);<br>flux.subscribe(System.out::println); // Prints: A B C</pre><h3>7. defer()</h3><p>defer creates a Mono that does not execute its logic until it is subscribed to. This is useful for creating dynamic Monos based on the current state.</p><p><strong>Example:</strong></p><pre>AtomicInteger count = new AtomicInteger(0);<br>Mono&lt;String&gt; deferredMono = Mono.defer(() -&gt; Mono.just(&quot;Count: &quot; + count.incrementAndGet()));<br>deferredMono.subscribe(System.out::println); // Prints: Count: 1<br>deferredMono.subscribe(System.out::println); // Prints: Count: 2</pre><h3>8. fromCallable()</h3><p>fromCallable wraps a blocking call in a Callable, allowing it to be executed in a non-blocking way using a scheduler.</p><p><strong>Example:</strong></p><pre>Mono&lt;Integer&gt; callableMono = Mono.fromCallable(() -&gt; {<br>    Thread.sleep(1000); // Simulating a blocking call<br>    return 42;<br>}).subscribeOn(Schedulers.boundedElastic());<br><br>callableMono.subscribe(System.out::println); // Prints: 42 after 1 second</pre><h3>9. fromRunnable()</h3><p>fromRunnable allows you to create a Mono from a Runnable. It does not return a value and is typically used for tasks that perform side effects.</p><p><strong>Example:</strong></p><pre>Mono&lt;Void&gt; runnableMono = Mono.fromRunnable(() -&gt; {<br>    System.out.println(&quot;Running a task...&quot;);<br>    // Task execution logic here<br>});<br>runnableMono.subscribe(); // Prints: Running a task...</pre><h3>10. then()</h3><p>The then method allows you to continue processing with another Mono, effectively ignoring the result of the first Mono.</p><p><strong>Example:</strong></p><pre>Mono&lt;Void&gt; thenMono = Mono.just(&quot;Hello&quot;)<br>    .then(Mono.just(&quot;World&quot;)); // Continues with &quot;World&quot;<br><br>thenMono.subscribe(System.out::println); // Prints: World</pre><h3>11. thenReturn()</h3><p>thenReturn allows you to return a specified value after the completion of a Mono, ignoring its result.</p><p><strong>Example:</strong></p><pre>Mono&lt;String&gt; thenReturnMono = Mono.just(&quot;Hello&quot;)<br>    .thenReturn(&quot;World&quot;);<br><br>thenReturnMono.subscribe(System.out::println); // Prints: World</pre><h3>Full Example: Combining Reactive Functions</h3><p>Let’s combine all the methods discussed into a comprehensive example, showcasing their utility in handling data asynchronously and managing errors effectively.</p><pre>import reactor.core.publisher.Mono;<br>import reactor.core.publisher.Flux;<br>import reactor.core.scheduler.Schedulers;<br><br>import java.time.Duration;<br>import java.util.Arrays;<br>import java.util.List;<br>import java.util.concurrent.atomic.AtomicInteger;<br><br>public class ReactiveExample {<br>    public static void main(String[] args) {<br>        // Using fromCallable to simulate a blocking operation<br>        Mono&lt;List&lt;String&gt;&gt; processedData = Mono.fromCallable(() -&gt; {<br>            Thread.sleep(1000); // Simulating a blocking call<br>            return Arrays.asList(&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;);<br>        }).subscribeOn(Schedulers.boundedElastic()) // Use a bounded elastic scheduler<br>          .flatMapMany(Flux::fromIterable) // Convert to Flux<br>          .filter(name -&gt; name.startsWith(&quot;A&quot;)) // Filter names starting with &quot;A&quot;<br>          .doOnNext(name -&gt; System.out.println(&quot;Processing: &quot; + name)) // Log processing<br>          .doOnError(error -&gt; System.err.println(&quot;Error occurred: &quot; + error.getMessage())) // Handle errors<br>          .onErrorResume(e -&gt; Flux.just(&quot;Fallback Name&quot;)) // Fallback on error<br>          .doFinally(signalType -&gt; System.out.println(&quot;Finished with signal: &quot; + signalType)); // Cleanup<br><br>        processedData.subscribe();<br>        <br>        // Keeping the application alive to see the asynchronous processing<br>        try {<br>            Thread.sleep(2000);<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}</pre><h3>Conclusion</h3><p>By mastering the reactive functions provided by Project Reactor, you can build robust, asynchronous applications that handle data streams efficiently. The methods discussed allow you to manage errors, perform side effects, and transform data effectively, making your applications more resilient and responsive. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba256e9ee8cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Evolution: Key Features from JDK 11 to 21]]></title>
            <link>https://medium.com/@zubairidrees.cs/java-evolution-key-features-from-jdk-11-to-21-d9efb7ddd3ca?source=rss-1dfd2d53282f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9efb7ddd3ca</guid>
            <dc:creator><![CDATA[Zubair Idrees]]></dc:creator>
            <pubDate>Sun, 01 Sep 2024 17:42:03 GMT</pubDate>
            <atom:updated>2024-09-01T17:42:03.049Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduction: Java, one of the most popular programming languages, continues to evolve with each new release of the Java Development Kit (JDK). From performance enhancements to language improvements, each JDK version brings along a plethora of new features and enhancements that shape the way we write Java code. In this blog post, we’ll take a closer look at some of the key features introduced in JDK versions 11 through 22.</p><p><strong>JDK 11</strong></p><p>1. Local-Variable Syntax for Lambda Parameters <a href="https://openjdk.org/jeps/323">(JEP 323</a>): This feature allows the use of ‘var’ when declaring the formal parameters of implicitly typed lambda expressions, reducing verbosity and enhancing readability.</p><p>2. HTTP Client (<a href="https://openjdk.org/jeps/321">JEP 321</a>): Introduces a modern HTTP client API for making requests to HTTP servers and handling responses, providing a more flexible and efficient alternative to the HttpURLConnection API.</p><p>3. Flight Recorder (<a href="https://openjdk.org/jeps/328">JEP 328</a>): Makes the Java Flight Recorder (JFR) available in OpenJDK 11, enabling continuous monitoring of the JVM and application performance without the need for commercial JDK distributions.</p><p>Flight Recorder can be started on the command line:</p><p>$ java -XX:StartFlightRecording …</p><p>Recordings may also be started and controlled using the bin/jcmd tool:</p><p>$ jcmd &lt;pid&gt; JFR.start</p><p>$ jcmd &lt;pid&gt; JFR.dump filename=recording.jfr</p><p>$ jcmd &lt;pid&gt; JFR.stop</p><p>4. Epsilon: A No-Op Garbage Collector (<a href="https://openjdk.org/jeps/318">JEP 318</a>): A garbage collector that doesn’t reclaim memory, useful for performance testing and debugging scenarios.</p><p>Epsilon GC looks and feels like any other OpenJDK GC, enabled with -XX:+UseEpsilonGC.</p><p>5. TLS 1.3 (<a href="https://openjdk.org/jeps/332">JEP 332</a>): Adds support for Transport Layer Security (TLS) 1.3, improving security and performance for secure communication.</p><p>6. Launch Single-File Source-Code Programs (<a href="https://openjdk.org/jeps/330">JEP 330</a>): Allows launching single-file Java source code programs directly using the java command without prior compilation.</p><p><strong>JDK 12</strong></p><p>1. Switch Expressions (<a href="https://openjdk.org/jeps/325">JEP 325</a>): Enhances the switch statement to allow it to be used as either a statement or an expression, simplifying code and reducing boilerplate.</p><p>2. Shenandoah: A Low-Pause-Time Garbage Collector (<a href="https://openjdk.org/jeps/189">JEP 189</a>): Introduces a new garbage collector aimed at reducing GC pause times by performing most of its work concurrently with application threads.</p><p>3. Microbenchmark Suite (<a href="https://openjdk.org/jeps/230">JEP 230</a>): Adds a set of microbenchmarks to the JDK source code, enabling developers to measure the performance of Java language features and APIs.</p><p><strong>JDK 13</strong></p><p>1. Text Blocks (<a href="https://openjdk.org/jeps/355">JEP 355</a>): JDK 13 introduces text blocks, streamlining the representation of multiline string literals with triple double quotes (“””). This feature enhances code readability by eliminating the need for escape sequences like \n, particularly beneficial for structured text formats such as HTML and SQL.</p><p>2. Switch Expressions (Preview) (<a href="https://openjdk.org/jeps/354">JEP 354</a>): JDK 13 standardizes switch expressions as a core language feature, extending the preview introduced in JDK 12. This enhancement allows switch expressions to function as both statements and expressions, with the introduction of the yield keyword for concise value return, simplifying control flow.</p><p>3. Reimplement the Legacy Socket API (<a href="https://openjdk.org/jeps/353">JEP 353</a>): JDK 13 optimizes the java.net.Socket and java.net.ServerSocket APIs, improving maintainability and performance for network-related operations. This enhancement provides a cleaner and more efficient implementation, simplifying socket usage and reducing boilerplate code, ultimately enhancing the development experience for networking applications in Java.</p><p><strong>JDK 14</strong></p><p>1. Switch Expressions (Second Preview Finalized) <strong>(</strong><a href="https://openjdk.org/jeps/361">JEP 361</a><strong>)</strong> This EP formalized switch expressions as a permanent feature in the Java language. It essentially took the work done in JEP 354 and made it an official part of Java without any further changes.</p><p>2. Non-Volatile Mapped Byte Buffers (<a href="https://openjdk.org/jeps/352">JEP 352</a>): Introduces new APIs for working with memory-mapped files, improving performance for certain I/O operations.</p><p>3. Packaging Tool (Incubator) (<a href="https://openjdk.org/jeps/343">JEP 343</a>): Introduces a new tool, jpackage, for packaging self-contained Java applications into platform-specific packages.</p><p>Suppose you have an application composed of JAR files, all in a directory named lib, and that lib/main.jar contains the main class. Then the command</p><pre>$ jpackage --name myapp --input lib --main-jar main.jar</pre><p>will package the application in the local system’s default format, leaving the resulting package file in the current directory. If the MANIFEST.MF file in main.jar does not have a Main-Class attribute then you must specify the main class explicitly:</p><pre>$ jpackage --name myapp --input lib --main-jar main.jar \</pre><pre>--main-class myapp.Main</pre><p>The name of the package will be myapp, though the name of the package file itself will be longer, and end with the package type (e.g., myapp.exe). The package will include a launcher for the application, also called myapp. To start the application, the launcher will place every JAR file that was copied from the input directory on the class path of the JVM.</p><p>If you wish to produce a package in a format other than the default, then use the --type option. For example, to produce a pkg file rather than dmg file on macOS:</p><pre>$ jpackage --name myapp --input lib --main-jar main.jar --type pkg</pre><p><strong>JDK 15</strong></p><p>1. Sealed Classes (JEP 360): Introduces sealed classes and interfaces to restrict which classes can extend or implement them, enhancing encapsulation.</p><p>2. Hidden Classes (JEP 371): Introduces hidden classes, which can be defined and loaded by the JVM without being visible to other classes, improving encapsulation and security. The hidden classes feature is helpful for anyone who works with dynamic bytecode or JVM languages.</p><p>3. Remove the Nashorn JavaScript Engine (JEP 372): Removes the Nashorn JavaScript Engine from the JDK, as it’s considered outdated.</p><p><strong>JDK 16:</strong></p><p>1. Records (JEP 395): Introduces records, a new kind of class designed for immutable data aggregates, reducing boilerplate code.</p><p>2. Foreign-Memory Access API (Second Incubator) (JEP 389): Enhances the Foreign-Memory Access API introduced in JDK 14, providing improved performance and safety.</p><p>3. Vector API (Second Incubator) (JEP 338): Enhances the Vector API introduced in JDK 15, providing better performance for manipulating arrays of data.</p><p><strong>JDK 17:</strong></p><p>1. Sealed Classes (Second Preview) (JEP 409): Further enhances sealed classes based on feedback received during the preview in JDK 15.</p><p>2. Foreign Function &amp; Memory API (Incubator) (JEP 419): Introduces a new API for interacting with native code and memory from Java, providing a safer alternative to JNI.</p><p>3. Pattern Matching for switch (Second Preview) (JEP 406): Extends pattern matching to the switch statement, allowing patterns to be used to destructure and extract data from objects.</p><p>4. Java 17 introduces new, high-quality pseudo-random number generators (PRNGs) that provide better performance and randomness compared to previous versions.</p><p><strong>JDK 18</strong></p><p>1. Pattern Matching for switch (Final Release) (JEP 420): Completes the preview feature introduced in JDK 17, making pattern matching for switch a standard feature of the Java language.</p><p>2. Simple Web Server (JEP 408): Introduces a simple web server in the JDK, providing a lightweight option for serving static and dynamic content over HTTP.</p><pre>The jwebserver tool comes with the following usage options:</pre><pre>jwebserver [-b bind address] [-p port] [-d directory]  [-o none|info|verbose]</pre><pre>[-h to show   options] [-version to show version information]</pre><p>3. Code Snippets in Java API Documentation (JEP 413): Java API documentation now includes formatted code snippets for better readability and easier integration into developer workflows. JEP 413 introduces a new inline tag, {@snippet …}, to declare code fragments to appear in the generated documentation. It can be used to declare both <em>inline snippets</em>, where the code fragment is included within the tag itself, and <em>external snippets</em>, where the code fragment is read from a separate source file.</p><p><strong>JDK 19</strong></p><p>1. Pattern Matching for switch (Third Preview — JEP 427): This JEP proposes a third preview with further refinements based upon continued experience and feedback.</p><p>The main changes since the second preview are:</p><p>· Guarded patterns are replaced with “<strong>when”</strong> clauses in switch blocks.</p><p>· The runtime semantics of a pattern switch when the value of the selector expression is null are more closely aligned with legacy switch semantics.</p><p>2. Virtual threads (JEP 425): Virtual threads are lightweight threads that run on top of a small number of operating system (OS) threads. Unlike traditional Java threads (platform threads), which are mapped directly to OS threads, virtual threads are scheduled and managed by the Java Virtual Machine (JVM). Blocking operations, such as I/O, only block the virtual thread and not the underlying OS thread. This means that while one virtual thread is blocked, other virtual threads can continue to run on the same OS thread, making more efficient use of system resources and improving overall application performance.</p><p><strong>JDK 20</strong></p><ol><li>Record Patterns (Second Preview) — JEP 432: Record patterns enable more concise and expressive pattern matching by allowing you to directly deconstruct records within pattern matching statements.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*69D1zjzXfnQGY4PKLd3kDw.png" /></figure><p>2. Scoped Values (Incubator — JEP 429) Scoped values provide a better alternative to thread-local variables, particularly for sharing immutable data across threads.</p><pre>public class ScopedValuesExample {<br>  public static final ScopedValue&lt;String&gt; USER_ID = ScopedValue.newInstance();<br>    public static void main(String[] args) throws Exception {<br>      try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {<br>        scope.fork(() -&gt; {<br>        ScopedValue.where(USER_ID, &quot;user1&quot;).run(() -&gt; {<br>        System.out.println(&quot;User ID in thread: &quot; + USER_ID.get());<br>      });<br>        return USER_ID.get();<br>      });<br>      scope.join();<br>    }<br>  }<br>}</pre><p>3. Virtual Threads (Second Preview — JEP 436) Improved observability and error reporting. Further refinements based on feedback.</p><p>4. Structured Concurrency (Second Incubator — JEP 429): Enhanced API ergonomics and additional functionality.</p><p>5. Foreign Function &amp; Memory API (Second Preview — JEP 434): Added features for better integration and more efficient handling of foreign memory.</p><p>6. Pattern Matching for Switch (Fourth Preview — JEP 433): Expanded pattern matching capabilities and enhanced error handling.</p><p><strong>JDK 21:</strong></p><p>JDK 21 does focus heavily on the continuation and refinement of features from previous previews. However, it does introduce a couple of new features and enhancements, along with the continuation of existing previews</p><p><strong>1.</strong> String Templates (Preview — JEP 430)<strong> </strong>Introduces string templates to simplify the process of combining literal text with computed values, improving readability and maintainability.</p><p><strong>2.</strong> Sequenced Collections (JEP 431) Introduces a new set of collection interfaces to represent sequenced collections, i.e., collections with a defined encounter order.</p><p><strong>3.</strong> Virtual Threads (Third Preview- JEP 453) The third preview of Virtual Threads (JEP 453) in JDK 21 brings better integration with existing Java concurrency frameworks, additional tools and support for debugging and profiling virtual threads, and continued optimization for performance and scalability based on user feedback.</p><p><strong>4.</strong> <strong>Structured Concurrency (Third Incubator — JEP 446) The</strong> third incubator of Structured Concurrency (JEP 446) in JDK 21 includes further refinement of the API based on user feedback, additional tools and support for observing and managing structured tasks, and the incorporation of new features to improve usability and functionality.</p><p><strong>5.</strong> <strong>Foreign Function &amp; Memory API (Third Preview — JEP 442) </strong>The third preview of the Foreign Function &amp; Memory API (JEP 442) in JDK 21 features improved integration with the rest of the JDK, a continued focus on performance enhancements, and the addition of new API features to improve safety and efficiency.</p><p><strong>6.</strong> <strong>Record Patterns (Third Preview — JEP 440) </strong>The third preview of Record Patterns (JEP 440) in JDK 21 offers further enhancements to pattern matching capabilities, improved integration with other language features, and minor syntax refinements and usability improvements.</p><p><strong>7.</strong> <strong>Pattern Matching for Switch (Fifth Preview — JEP 443) </strong>The fifth preview of Pattern Matching for Switch (JEP 443) in JDK 21 includes further extension of pattern matching capabilities, enhanced error handling and diagnostics, and support for additional pattern types based on user feedback.</p><p><strong>8.</strong> <strong>Vector API (Sixth Incubator- JEP 448) </strong>The sixth incubator of the Vector API (JEP 448) in JDK 21 continues the optimization for performance on supported CPU architectures, further expansion of platform support, and additional API refinements to improve usability.</p><p>For detailed code examples and further exploration of these features, check out the GitHub repository<a href="https://github.com/zubairidrees/java/tree/main"> here.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9efb7ddd3ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>