<?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 Mustafa Karataş on Medium]]></title>
        <description><![CDATA[Stories by Mustafa Karataş on Medium]]></description>
        <link>https://medium.com/@musticode?source=rss-b8a56f7c387c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gewqaJTI41NvCLtXHPB2Zg.png</url>
            <title>Stories by Mustafa Karataş on Medium</title>
            <link>https://medium.com/@musticode?source=rss-b8a56f7c387c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:45:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@musticode/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[Debezium CDC - Integration & Implementation]]></title>
            <link>https://musticode.medium.com/debezium-cdc-integration-implementation-a877d14e9414?source=rss-b8a56f7c387c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a877d14e9414</guid>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[change-data-capture]]></category>
            <category><![CDATA[debezium]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Mustafa Karataş]]></dc:creator>
            <pubDate>Fri, 01 Nov 2024 22:07:40 GMT</pubDate>
            <atom:updated>2024-11-04T13:33:47.623Z</atom:updated>
            <content:encoded><![CDATA[<h3>Debezium CDC — SpringBoot Integration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*RuiFfsYNVWxSST8B_kOfSw@2x.jpeg" /></figure><h3>Introduction to Change Data Capture (CDC)</h3><p>In today’s data-driven world, businesses rely on accurate and timely data to make decisions. However, with data stored across various systems, ensuring that data remains synchronized and up-to-date can be a complex task. Change Data Capture (CDC) is a set of techniques that helps capture changes in data from one system and propagate them to others in near real-time. By identifying and tracking database modifications such as inserts, updates, and deletes, CDC enables organizations to maintain data consistency across multiple systems without the need for complex, resource-intensive data sync processes.</p><h3>Why Use CDC in Modern Data Architectures?</h3><p>CDC has become essential in modern data architectures, particularly with the rise of microservices, event-driven systems, and real-time analytics. Traditional approaches to data synchronization, like batch processing, often fall short for applications that require low-latency updates. CDC enables real-time data integration, allowing businesses to keep data consistent across distributed systems. This can drive use cases such as real-time inventory tracking, personalized customer experiences, and fraud detection. By using CDC, businesses can unlock more timely insights and ensure data accuracy, all while reducing the strain on system resources.</p><h3>Introducing Debezium</h3><p>Debezium is an open-source CDC platform that simplifies the process of capturing changes from databases and propagating them to downstream systems. Built on Apache Kafka, Debezium is designed to capture changes from a range of databases, including MySQL, PostgreSQL, SQL Server, Oracle, and MongoDB. The platform acts as a bridge between transactional databases and streaming platforms, allowing data teams to stream changes reliably and with minimal latency. Since it leverages Kafka, Debezium is also highly scalable and capable of handling large volumes of data changes, making it ideal for enterprise use cases.</p><h3>How Debezium Works</h3><p>Debezium operates by monitoring the transaction logs of databases, which record every change made within a database. By reading these logs, Debezium captures changes and publishes them as Kafka events without impacting the database’s performance. This approach is efficient because it relies on the database’s existing mechanisms rather than querying tables directly. Once changes are captured and published to Kafka topics, downstream systems can consume them in near real-time, making it easy to trigger actions based on changes or to synchronize with other systems. This architecture not only minimizes load on the source database but also ensures low-latency data streaming to other systems.</p><h3>Integration &amp; Implementation</h3><p>docker-compose.yml</p><pre>version: &#39;2&#39;<br>services:<br>  zookeeper:<br>    image: confluentinc/cp-zookeeper:latest<br>    environment:<br>      ZOOKEEPER_CLIENT_PORT: 2181<br>      ZOOKEEPER_TICK_TIME: 2000<br>    ports:<br>      - 52181:2181<br><br>  kafka:<br>    image: confluentinc/cp-kafka:7.0.1<br>    ports:<br>      - &quot;9092:9092&quot;<br>    depends_on:<br>      - zookeeper<br>    environment:<br>      KAFKA_BROKER_ID: 1<br>      KAFKA_ZOOKEEPER_CONNECT: &#39;zookeeper:2181&#39;<br>      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_INTERNAL:PLAINTEXT<br>      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092,PLAINTEXT_INTERNAL://kafka:29092<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br>      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1<br>      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1<br><br>  kafka-admin:<br>    image: provectuslabs/kafka-ui<br>    container_name: kafka-admin<br>    ports:<br>      - &quot;9091:8080&quot;<br>    restart: always<br>    depends_on:<br>      - kafka<br>      - zookeeper<br>    environment:<br>      - KAFKA_CLUSTERS_0_NAME=local<br>      - KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS=kafka:29092<br>      - KAFKA_CLUSTERS_0_ZOOKEEPER=zookeeper:2181<br><br>  db:<br>    platform: linux/x86_64<br>    image: debezium/example-postgres<br>    restart: always<br>    environment:<br>      POSTGRES_PASSWORD: example<br>    ports:<br>      - 5432:5432<br>    extra_hosts:<br>      - &quot;host.docker.internal:host-gateway&quot;<br>    command:<br>      - &quot;postgres&quot;<br>      - &quot;-c&quot;<br>      - &quot;wal_level=logical&quot;<br>    volumes:<br>      - ./resource/init.sql:/docker-entrypoint-initdb.d/create-db-tables.sql<br><br>  adminer:<br>    image: adminer<br>    restart: always<br>    ports:<br>      - 8001:8080<br><br>  kafka_connect:<br>    container_name: kafka_connect<br>    image: debezium/connect<br>    links:<br>      - db<br>      - kafka<br>    ports:<br>      - &#39;8083:8083&#39;<br>    environment:<br>      - BOOTSTRAP_SERVERS=kafka:29092<br>      - GROUP_ID=medium_debezium<br>      - CONFIG_STORAGE_TOPIC=my_connect_configs<br>      - OFFSET_STORAGE_TOPIC=my_connect_offsets<br>      - STATUS_STORAGE_TOPIC=my_connect_statuses</pre><p>dependencies for pom.xml</p><pre>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.kafka&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-kafka&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.postgresql&lt;/groupId&gt;<br>   &lt;artifactId&gt;postgresql&lt;/artifactId&gt;<br>   &lt;scope&gt;runtime&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>   &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>   &lt;optional&gt;true&lt;/optional&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.kafka&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-kafka-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;</pre><p>Product Entity</p><pre>@Entity<br>@Data<br>@NoArgsConstructor<br>@AllArgsConstructor<br>@Builder<br>@Table(name = &quot;product&quot;)<br>public class Product {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br>    private String name;<br>    private BigDecimal price;<br>    private int stock;<br>}</pre><p>ProductRepository interface:</p><pre>@Repository<br>public interface ProductRepository extends JpaRepository&lt;Product, Long&gt; {<br>}</pre><p>ProductServiceImpl class:</p><pre>@Service<br>@Slf4j<br>public class ProductServiceImpl implements ProductService {<br><br>    private final ProductRepository productRepository;<br>    private final ProductEventProducer productEventProducer;<br><br>    public ProductServiceImpl(ProductRepository productRepository, ProductEventProducer productEventProducer) {<br>        this.productRepository = productRepository;<br>        this.productEventProducer = productEventProducer;<br>    }<br><br><br>    @Override<br>    @Transactional<br>    public Product addProduct(ProductDto product){<br>        final Product newProduct = new Product();<br>        newProduct.setStock(product.getStock());<br>        newProduct.setName(product.getName());<br>        newProduct.setPrice(product.getPrice());<br>        productEventProducer.sendMessage(newProduct);<br>        return  productRepository.save(newProduct);<br>    }<br><br>    @Override<br>    public List&lt;Product&gt; getAllProducts() {<br>        return productRepository.findAll();<br>    }<br><br>    @Override<br>    public Product updateProduct(long productId, Product updatedProduct) {<br>        final Product currentProduct = productRepository.findById(productId).orElseThrow(()-&gt; new RuntimeException(&quot;No currentProduct with id&quot;));<br>        currentProduct.setName(updatedProduct.getName());<br>        currentProduct.setPrice(updatedProduct.getPrice());<br>        currentProduct.setStock(updatedProduct.getStock());<br>        return productRepository.save(currentProduct);<br>    }<br><br>}</pre><p>debezium connector requests</p><pre>curl --location &#39;localhost:8083/connectors&#39; \<br>--header &#39;Accept: application/json&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--header &#39;Cookie: csrftoken=M7jtiBvQrP5MVhm9kN1nbq8hNFgi0lRS; csrftoken=M7jtiBvQrP5MVhm9kN1nbq8hNFgi0lRS&#39; \<br>--data &#39;{<br>    &quot;name&quot;: &quot;product-connector&quot;,<br>    &quot;config&quot;: {<br>        &quot;connector.class&quot;: &quot;io.debezium.connector.postgresql.PostgresConnector&quot;,<br>        &quot;tasks.max&quot;: &quot;1&quot;,<br>        &quot;database.history.kafka.bootstrap.servers&quot;: &quot;kafka:9092&quot;,<br>        &quot;database.hostname&quot;: &quot;db&quot;, <br>        &quot;database.port&quot;: &quot;5432&quot;,<br>        &quot;database.user&quot;: &quot;postgres&quot;,<br>        &quot;database.password&quot;: &quot;example&quot;,<br>        &quot;database.dbname&quot;: &quot;debezium_demo&quot;,<br>        &quot;database.server.name&quot;: &quot;postgres&quot;,<br>        &quot;tombstones.on.delete&quot; : false,    <br>        &quot;topic.prefix&quot; : &quot;product&quot;,<br>        &quot;table.inclde.list&quot; : &quot;public.product&quot;,<br>        &quot;heartbeat.interval.ms&quot; : &quot;5000&quot;,<br>        &quot;key.converter&quot;: &quot;org.apache.kafka.connect.json.JsonConverter&quot;,<br>        &quot;key.converter.schemas.enable&quot;: false,<br>        &quot;value.converter&quot;: &quot;org.apache.kafka.connect.json.JsonConverter&quot;,<br>        &quot;value.converter.schemas.enable&quot;: false,<br>        &quot;plugin.name&quot; : &quot;pgoutput&quot;,<br>        &quot;slot.name&quot;: &quot;unique_slot_name&quot;<br>        <br>    }<br>}&#39;</pre><ul><li>connector.class : Specifies the class for the PostgreSQL connector.</li><li>tasks.max : Defines the maximum number of tasks to create for this connector.</li><li>database.hostname, database.port, database.user, database.password, database.dbname : Connection details for PostgreSQL.</li><li>database.server.name: A unique identifier for the connector instance. Server&#39;s name can be found in properties for database</li><li>slot.name : The replication slot name used by the connector. Make sure it&#39;s unique for each connector.</li><li>plugin.name : Specifies the Debezium plugin to use for capturing changes.</li><li>schema.include, table.include.list: Specify the schema and tables to include in the CDC.</li><li>snapshot.mode : Defines how the initial snapshot of data should be taken.</li><li>heartbeat.interval.ms : Interval for sending heartbeat messages to PostgreSQL.</li><li>heartbeat.action.query : SQL query used for heartbeat messages.</li><li>snapshot.lock.timeout.ms : Timeout for acquiring locks during the snapshot.</li><li>snapshot.select.statement.overrides : Overrides the default SELECT statement used during the snapshot.</li><li>database.history.kafka.bootstrap.servers&quot;: &quot;kafka:9092&quot; : Kafka broker information</li><li>&quot;key.converter&quot;: &quot;org.apache.kafka.connect.json.JsonConverter&quot; and &quot;value.converter&quot;: &quot;org.apache.kafka.connect.json.JsonConverter&quot; : Kafka serializing configs</li><li>Create a connector to connect postgresql and kafka</li><li>Debezium topics will be created</li></ul><p>Send product create request</p><pre>curl --location &#39;localhost:8080/api/v1/product/add-product&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--header &#39;Cookie: csrftoken=M7jtiBvQrP5MVhm9kN1nbq8hNFgi0lRS&#39; \<br>--data &#39;{<br>    &quot;name&quot; : &quot;testProduct&quot;,<br>    &quot;price&quot; : 150,<br>    &quot;stock&quot; : 4<br>}&#39;</pre><p>Product’s event can be seen in product.public.product topic</p><pre>{<br> &quot;before&quot;: null,<br> &quot;after&quot;: {<br>  &quot;id&quot;: 27,<br>  &quot;name&quot;: &quot;testProduct&quot;,<br>  &quot;price&quot;: &quot;Opg=&quot;,<br>  &quot;stock&quot;: 4<br> },<br> &quot;source&quot;: {<br>  &quot;version&quot;: &quot;2.5.0.Final&quot;,<br>  &quot;connector&quot;: &quot;postgresql&quot;,<br>  &quot;name&quot;: &quot;product&quot;,<br>  &quot;ts_ms&quot;: 1710687476938,<br>  &quot;snapshot&quot;: &quot;false&quot;,<br>  &quot;db&quot;: &quot;debezium_demo&quot;,<br>  &quot;sequence&quot;: &quot;[\&quot;25664360\&quot;,\&quot;25664752\&quot;]&quot;,<br>  &quot;schema&quot;: &quot;public&quot;,<br>  &quot;table&quot;: &quot;product&quot;,<br>  &quot;txId&quot;: 773,<br>  &quot;lsn&quot;: 25664752,<br>  &quot;xmin&quot;: null<br> },<br> &quot;op&quot;: &quot;c&quot;,<br> &quot;ts_ms&quot;: 1710687477419,<br> &quot;transaction&quot;: null<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VHdbXes1m--8oXSURXNu6A.png" /><figcaption>kafka-ui</figcaption></figure><h3>Listening changing data events</h3><p>Mapping object</p><pre>@Data<br>@AllArgsConstructor<br>@NoArgsConstructor<br>@JsonIgnoreProperties(ignoreUnknown = true)<br>public class ProductMessage {<br><br>    @JsonProperty(&quot;before&quot;)<br>    private Before before = null;<br><br>    @JsonProperty(&quot;after&quot;)<br>    private After after;<br><br>    @JsonProperty(&quot;source&quot;)<br>    private Source source;<br><br>    @JsonProperty(&quot;op&quot;)<br>    private String op;<br><br>    @JsonProperty(&quot;ts_ms&quot;)<br>    private String ts_ms;<br><br>    @JsonProperty(&quot;transaction&quot;)<br>    private Object transaction;<br><br>}</pre><p>Creating deserializer for kafka</p><pre>public class ProductMessageDeserializer implements Deserializer&lt;ProductMessage&gt; {<br>    private final ObjectMapper objectMapper = new ObjectMapper();<br><br>    @Override<br>    public void configure(Map&lt;String, ?&gt; configs, boolean isKey) {<br>        Deserializer.super.configure(configs, isKey);<br>    }<br><br>    @Override<br>    public ProductMessage deserialize(String topic, byte[] data) {<br>        try {<br>            return objectMapper.readValue(data, ProductMessage.class);<br>        }catch (Exception e){<br>            throw new RuntimeException(e);<br>        }<br>    }<br><br>    @Override<br>    public ProductMessage deserialize(String topic, Headers headers, byte[]data){<br>        return Deserializer.super.deserialize(topic, headers, data);<br>    }<br>    <br>    @Override<br>    public void close() {<br>        Deserializer.super.close();<br>    }<br>    <br>}</pre><p>SpringBoot configuration</p><pre>@Configuration<br>public class KafkaProductConsumerConfig {<br><br>    @Bean<br>    public ConcurrentKafkaListenerContainerFactory&lt;String, Product&gt; kafkaListenerContainerFactory(ConsumerFactory&lt;String, Product&gt; consumerFactory){<br>        ConcurrentKafkaListenerContainerFactory&lt;String, Product&gt; factory = new ConcurrentKafkaListenerContainerFactory&lt;&gt;();<br>        factory.setConsumerFactory(consumerFactory);<br>        return factory;<br>    }<br><br><br>    @Bean<br>    public ConsumerFactory&lt;String, Product&gt; consumerFactory(){<br>        Map&lt;String, Object&gt; props = new HashMap&lt;&gt;();<br>        props.put(&quot;bootstrap.servers&quot;, &quot;localhost:9092&quot;);<br>        props.put(&quot;auto.offset.reset&quot;, &quot;earliest&quot;);<br>        props.put(ConsumerConfig.GROUP_ID_CONFIG, &quot;product-group&quot;);<br>        props.put(&quot;key.deserializer&quot;, StringDeserializer.class.getName());<br>        props.put(&quot;value.deserializer&quot;, ProductMessageDeserializer.class.getName());<br>        return new DefaultKafkaConsumerFactory&lt;&gt;(props);<br>    }<br><br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a877d14e9414" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SocketIO — SpringBoot Integration]]></title>
            <link>https://musticode.medium.com/socketio-springboot-integration-12ecc542da8c?source=rss-b8a56f7c387c------2</link>
            <guid isPermaLink="false">https://medium.com/p/12ecc542da8c</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[springboot-3]]></category>
            <dc:creator><![CDATA[Mustafa Karataş]]></dc:creator>
            <pubDate>Mon, 06 May 2024 08:58:23 GMT</pubDate>
            <atom:updated>2024-05-06T08:58:23.457Z</atom:updated>
            <content:encoded><![CDATA[<h3>SocketIO — SpringBoot Integration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CXIzGE98vydaY5Jl" /><figcaption>Photo by <a href="https://unsplash.com/@remgodet?utm_source=medium&amp;utm_medium=referral">Remi Godet</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Socket io enables <strong>low-latency</strong>, <strong>bidirectional</strong> and <strong>event-based</strong> communication between a client and a server.</p><p>dependency:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.corundumstudio.socketio&lt;/groupId&gt;<br>    &lt;artifactId&gt;netty-socketio&lt;/artifactId&gt;<br>    &lt;version&gt;2.0.3&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>config class:</p><pre>@CrossOrigin<br>@Configuration<br>public class SocketIOConfig {<br><br>    @Value(&quot;${socket-server.host}&quot;)<br>    private String SOCKET_HOST;<br><br>    @Value(&quot;${socket-server.port}&quot;)<br>    private int SOCKET_PORT;<br>    <br>    private SocketIOServer server;<br><br>    @Bean<br>    public SocketIOServer socketIOServer() {<br>        com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();<br>        config.setHostname(SOCKET_HOST);<br>        config.setPort(SOCKET_PORT);<br>        server = new SocketIOServer(config);<br>        server.start();<br><br>        return server;<br>    }<br><br>    @PreDestroy<br>    public void stopSocketIOServer() {<br>        this.server.stop();<br>    }<br><br>}</pre><p>@Value(&quot;{socket-server.host}&quot;) and @Value(&quot;{socket-server.port}&quot;) are configured in properties yml file</p><pre>socket-server:<br>  port: 8085<br>  host: localhost</pre><ul><li>Hostname and port is set</li><li>Server is starting when SocketIOServer bean is called</li><li>Before application is stopped server is stopped</li></ul><h4>Listener Classes</h4><p>When we start the socket server, listeners will listen the events that we will create next.</p><p>Connect listener</p><pre>@Service<br>@Slf4j<br>public class ChatConnectListener implements ConnectListener {<br><br>    @Override<br>    public void onConnect(SocketIOClient client) {<br>        log.info(&quot;Connected user : {}&quot;,client.getSessionId().toString());<br>    }<br><br>}</pre><p>Connect listener interface has onConnect method to override. In this method SocketIOClient is passing as parameter to method. Clients have session ids when they are connected to the server</p><p>Disconnect Listener</p><pre>@Service<br>@Slf4j<br>public class ChatDisconnectListener implements DisconnectListener {<br><br>    @Override<br>    public void onDisconnect(SocketIOClient client) {<br>        log.info(&quot;Disconnected user : {}&quot;,client.getSessionId().toString());<br>    }<br><br>}</pre><p>DisconnectListener interface has onDisconnectmethod to override. This method listen client’s disconnection.</p><p>Data Listeners</p><p>When a data wanted to be listened, we should implement the model classes to handle data</p><pre>@Data<br>public class Message {<br>    private String username;<br>    private String content;<br>    private String targetUsername;<br>}</pre><p>Data listener class</p><pre>@Service<br>@Slf4j<br>public class PrivateChatMessageListener implements DataListener&lt;Message&gt; {<br><br>    private final SocketIOServer server;<br><br>    public PrivateChatMessageListener(SocketIOServer server) {<br>        this.server = server;<br>    }<br><br>    @Override<br>    public void onData(SocketIOClient client, Message message, AckRequest ackRequest){<br>        log.info(&quot;User : {}&quot;,client.getSessionId().toString());<br><br>        // Broadcast the message to all connected clients<br>        server.getBroadcastOperations().sendEvent(&quot;privateChatMessage&quot;, message);<br>    }<br><br>}</pre><p>DataListener interface has a method name onData, this method must be overridden with Message type by our listener class. This onData method will work when Message event is sent. This method will send the event to privateChatMessage topic, users are listening this topic will get the event</p><p>There can be many data listeners to handle our operations in server.</p><p>Service</p><pre>@Service<br>@Slf4j<br>public class ChatService {<br><br>    private final SocketIOServer socketIOServer;<br>    private final ChatConnectListener connectListener;<br>    private final ChatDisconnectListener disconnectListener;<br>    private final PrivateChatMessageListener privateChatMessageListener;<br><br>    public ChatService(SocketIOServer socketIOServer, ChatConnectListener connectListener, ChatDisconnectListener disconnectListener, PrivateChatMessageListener privateChatMessageListener) {<br>        this.socketIOServer = socketIOServer;<br>        this.connectListener = connectListener;<br>        this.disconnectListener = disconnectListener;<br>        this.privateChatMessageListener = privateChatMessageListener;<br>    }<br><br>    @PostConstruct<br>    private void init(){<br>        socketIOServer.addConnectListener(connectListener);<br>        socketIOServer.addDisconnectListener(disconnectListener);<br>        socketIOServer.addEventListener(&quot;privateChatMessage&quot;, Message.class, privateChatMessageListener);<br>    }<br><br>}</pre><ul><li>connectListener is added to server’s connect listener</li><li>disconnectListener is added to server’s disconnect listener</li><li>privateChatMessageListener is added to server’s event listener. When a client sent event to privateChatMessage topic, sent event will trigger our data listener’s onData method. Clients are listening the privateChatMessage topic will receive event data. If there is more event listener, these event listeners should be added server’s event listeners</li></ul><h4>Namespaces</h4><p>A Namespace is a communication channel that allows you to split the logic of your application over a single shared connection. Each namespace has its own event handlers, rooms, middlewares. There can be many namespaces and each’s logic can be different from each others.</p><h4>Broadcasting</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*xhTdkQY44_2f3bBccS426A.png" /></figure><p>Events can be sent to all connected clients. Clients that are currently disconnected (or in the process of reconnecting) won’t receive the event. Storing the event somewhere is up to us, can be stored in database or etc.</p><h4>Rooms</h4><p>A room is an arbitrary channel that socket clients can join and leave. It can be used to broadcast events to a subset of clients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*zjreXZ7IIk5slWoVbPXtiQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12ecc542da8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redis — SpringBoot Integration | Configuration | Implementation]]></title>
            <link>https://musticode.medium.com/redis-springboot-integration-configuration-implementation-e27bfae48a9b?source=rss-b8a56f7c387c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e27bfae48a9b</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Mustafa Karataş]]></dc:creator>
            <pubDate>Sun, 05 May 2024 20:01:41 GMT</pubDate>
            <atom:updated>2024-11-02T14:44:55.903Z</atom:updated>
            <content:encoded><![CDATA[<h3>Redis — SpringBoot Integration | Configuration | Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qBSQjKRCZWWUUo5i" /><figcaption>Photo by <a href="https://unsplash.com/@timgarifov?utm_source=medium&amp;utm_medium=referral">Timur Garifov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Redis (Remote Dictionary Server) is an open-source, in-memory data structure store widely used as a database, cache, and message broker. Known for its exceptional speed, Redis can serve millions of requests per second, making it popular for high-performance applications. It’s built to handle various data types like strings, hashes, lists, sets, and sorted sets, which makes it versatile for a range of use cases. Since it stores data in memory, Redis enables incredibly low latency, making it ideal for real-time applications where response speed is critical.</p><h3>Why use Redis</h3><p>Redis shines in scenarios that require fast, reliable access to data. By storing data in memory, Redis provides rapid read and write capabilities, which makes it suitable for applications needing high throughput and minimal latency. It’s also incredibly flexible, serving as both a simple key-value store and a more complex data structure server. Additionally, Redis supports persistence through snapshots and logs, so data can be stored on disk and restored on restart, balancing the need for speed with durability. This makes Redis valuable for a range of use cases, from caching and session management to real-time analytics and message queuing.</p><h3>Use cases</h3><h4>Caching</h4><p>One of the most common uses for Redis is as a caching layer to reduce database load and improve application performance. By caching frequently accessed data in Redis, applications can retrieve data in milliseconds instead of querying a slower database. This is particularly beneficial for high-traffic applications and reduces the overall response time for end-users.</p><h4>Session Storage</h4><p>Redis is widely used to store user sessions, especially in web applications where fast access to session data is essential. Since Redis is in-memory and offers automatic data expiration, it’s ideal for session management, ensuring quick access to user-specific information while freeing up memory once sessions expire.</p><h4>Message Queueing</h4><p>Redis can also function as a lightweight message broker. By using lists and the pub/sub (publish/subscribe) messaging pattern, Redis enables applications to communicate asynchronously and process jobs in the background. This is valuable for applications that require scalable task management, like sending notifications or processing media uploads.</p><h3>SpringBoot configuration &amp; implementation</h3><p>Here is the basic docker-compose redis configuration</p><pre>services:<br>    redis:<br>    image: redis:latest<br>    restart: always<br>    ports:<br>      - &quot;6379:6379&quot;<br>    environment:<br>      - REDIS_PASSWORD=my-password<br>      - REDIS_PORT=6379<br>      - REDIS_DATABASES=16</pre><h4>Maven dependency</h4><pre>&lt;dependency&gt;<br> &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-boot-starter-data-redis&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>In application yml file, cache type and redis host, port informations are defined.</p><pre>spring:<br>  cache:<br>    type: redis<br>    redis:<br>      host: localhost<br>      port: 6379<br><br>cache:<br>  config:<br>    entryTtl: 60<br>    jwtToken:<br>      entryTtl: 30</pre><p>Redis config class</p><pre>@Configuration<br>@EnableCaching<br>@Slf4j<br>public class RedisConfig {<br><br>    @Value(&quot;${spring.cache.redis.host}&quot;)<br>    private String redisHost;<br><br>    @Value(&quot;${spring.cache.redis.port}&quot;)<br>    private int redisPort;<br><br>    @Bean<br>    public LettuceConnectionFactory redisConnectionFactory() {<br>        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(redisHost, redisPort);<br>        configuration.setPassword(&quot;my-password&quot;);<br>        log.info(&quot;Connected to : {} {}&quot;, redisHost, redisPort);<br><br>        return new LettuceConnectionFactory(configuration);<br>    }<br><br>    @Bean<br>    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {<br>        return RedisCacheManager.create(connectionFactory);<br>    }<br>    <br>    @Bean<br>    public RedisTemplate&lt;String, Object&gt; redisTemplate(){<br>        final RedisTemplate&lt;String, Object&gt; redisTemplate = new RedisTemplate&lt;&gt;();<br>        redisTemplate.setKeySerializer(new StringRedisSerializer());<br>        redisTemplate.setHashKeySerializer(new GenericToStringSerializer&lt;Object&gt;(Object.class));<br>        redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());<br>        redisTemplate.setValueSerializer(new StringRedisSerializer());<br>        redisTemplate.setConnectionFactory(redisConnectionFactory());<br>        return redisTemplate;<br>    }<br>}</pre><p>To enable caching in your application, you can use the @EnableCaching annotation and then annotate methods that should be cached with @Cacheable, @CachePut, and @CacheEvict.</p><pre>@GetMapping(&quot;/product/{id}&quot;)  <br>@Cacheable(value = &quot;product&quot;, key = &quot;#id&quot;)<br>public Product getProductById(@PathVariable long id) {...}</pre><p>1. <strong>@Cacheable </strong>is employed to fetch data from the database, storing it in the cache. Upon future invocations, the method retrieves the cached value directly, eliminating the need to execute the method again.</p><p>The value attribute establishes a cache with a specific name, while the key attribute permits the use of Spring Expression Language to compute the key dynamically. Consequently, the method result is stored in the &#39;product&#39; cache, where respective &#39;product_id&#39; serves as the unique key. This approach optimizes caching by associating each result with a distinct key.</p><p><strong>2. </strong><strong>@CachePut</strong> is used to update data in the cache when there is any update in the source database.</p><pre>@PutMapping(&quot;/product/{id}&quot;)<br>@CachePut(cacheNames = &quot;product&quot;, key = &quot;#id&quot;)<br>public Product editProduct(@PathVariable long id, @RequestBody Product product) {...}</pre><p>The cacheNames attribute is an alias for value, and can be used in a similar manner.</p><p><strong>3. </strong><strong>@CacheEvict</strong> is used for removing stale or unused data from the cache.</p><p>We use cacheName and key to remove specific data from the cache. The beforeInvocation attribute allows us to control the eviction process, enabling us to choose whether the eviction should occur before or after the method execution.</p><pre>@DeleteMapping(&quot;/product/{id}&quot;)<br>@CacheEvict(cacheNames = &quot;product&quot;, key = &quot;#id&quot;, beforeInvocation = true)<br>public String removeProductById(@PathVariable long id) {...}</pre><p>Alternatively, all the data can also be removed for a given cache by using the allEntries attribute as true. The annotation allows us to clear data for multiple caches as well by providing multiple values as cacheName.</p><p><strong>4. </strong><strong>@Caching</strong>is used for multiple nested caching on the same method.</p><pre>@PutMapping(&quot;/{id}&quot;)<br>@Caching(<br>     evict = {@CacheEvict(value = &quot;productList&quot;, allEntries = true)},<br>     put = {@CachePut(value = &quot;product&quot;, key = &quot;#id&quot;)}<br>)<br>public Product editProduct(@PathVariable long id, @RequestBody Product product) {...}</pre><p>As Java doesn’t allow multiple annotations of the same type to be declared for a method, doing so will generate a compilation error. We can group different annotations into Caching, as shown.</p><p><strong>5. </strong><strong>@CacheConfig</strong>is used for centralized configuration.</p><pre>@CacheConfig(cacheNames = &quot;product&quot;)<br>public class ProductController {...}</pre><h4>Working with RedisTemplate</h4><p>You can use the RedisTemplate to interact with Redis. For example, to save data in Redis:</p><pre>@Autowired<br>private RedisTemplate&lt;String, Object&gt; redisTemplate;<br><br>public void saveData(String key, Object data) {<br>    redisTemplate.opsForValue().set(key, data);<br>}</pre><p>Retrive data from Redis:</p><pre>public Object getData(String key) {<br>    return redisTemplate.opsForValue().get(key);<br>}</pre><p>Example service class with redis template</p><pre><br>@Service<br>public class CacheTokenService {<br><br>    private final StringRedisTemplate stringRedisTemplate;<br>    private final RedisTemplate&lt;String, Object&gt; redisTemplate;<br><br>    public CacheTokenService(StringRedisTemplate stringRedisTemplate, RedisTemplate&lt;String, Object&gt; redisTemplate) {<br>        this.stringRedisTemplate = stringRedisTemplate;<br>        this.redisTemplate = redisTemplate;<br>    }<br><br>    public void saveData(String key, Object data) {<br>        redisTemplate.opsForValue().set(key, data);<br>    }<br><br>    public Object getData(String key) {<br>        return redisTemplate.opsForValue().get(key);<br>    }<br><br>    public void cacheToken(String username, String token) {<br>        stringRedisTemplate<br>        .opsForValue()<br>        .set(&quot;token:&quot; + username, token, Duration.ofMinutes(60));<br>    }<br><br>    public String getCachedToken(String username) {<br>        // Retrieve the token from Redis cache<br>        return stringRedisTemplate<br>        .opsForValue()<br>        .get(&quot;token:&quot; + username);<br>    }<br><br>}</pre><h4>PUB/SUB Messaging</h4><p>Adding configurations like:</p><pre>    @Bean<br>    public ChannelTopic channelTopic(){<br>        return new ChannelTopic(&quot;channel_topic&quot;);<br>    }<br><br>    @Bean<br>    public RedisMessageListenerContainer redisMessageListenerContainer(){<br>        RedisMessageListenerContainer container = new RedisMessageListenerContainer();<br>        container.setConnectionFactory(redisConnectionFactory());<br>        container.addMessageListener(messageListener(), channelTopic());<br>        return container;<br>    }<br><br>    @Bean<br>    public MessageListenerAdapter messageListener( ) {<br>        return new MessageListenerAdapter(redisMessageHandler);<br>    }</pre><p>Last seen of config class:</p><pre>@Configuration<br>@EnableCaching<br>@Slf4j<br>public class RedisConfig {<br><br>    @Value(&quot;${spring.cache.redis.host}&quot;)<br>    private String redisHost;<br><br>    @Value(&quot;${spring.cache.redis.port}&quot;)<br>    private int redisPort;<br><br><br>    private final RedisMessageHandler redisMessageHandler;<br><br>    public RedisConfig(RedisMessageHandler redisMessageHandler) {<br>        this.redisMessageHandler = redisMessageHandler;<br>    }<br><br>    @Bean<br>    public LettuceConnectionFactory redisConnectionFactory() {<br>        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(redisHost, redisPort);<br>        configuration.setPassword(&quot;my-password&quot;);<br>        log.info(&quot;Connected to : {} {}&quot;, redisHost, redisPort);<br><br><br>        return new LettuceConnectionFactory(configuration);<br>    }<br><br>    @Bean<br>    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {<br>        return RedisCacheManager.create(connectionFactory);<br>    }<br>    @Bean<br>    public RedisTemplate&lt;String, Object&gt; redisTemplate(){<br>        final RedisTemplate&lt;String, Object&gt; redisTemplate = new RedisTemplate&lt;&gt;();<br>        redisTemplate.setKeySerializer(new StringRedisSerializer());<br>        redisTemplate.setHashKeySerializer(new GenericToStringSerializer&lt;Object&gt;(Object.class));<br>        redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());<br>        redisTemplate.setValueSerializer(new StringRedisSerializer());<br>        redisTemplate.setConnectionFactory(redisConnectionFactory());<br>        return redisTemplate;<br>    }<br><br>    @Bean<br>    public ChannelTopic channelTopic(){<br>        return new ChannelTopic(&quot;channel_topic&quot;);<br>    }<br><br>    @Bean<br>    public RedisMessageListenerContainer redisMessageListenerContainer(){<br>        RedisMessageListenerContainer container = new RedisMessageListenerContainer();<br>        container.setConnectionFactory(redisConnectionFactory());<br>        container.addMessageListener(messageListener(), channelTopic());<br>        return container;<br>    }<br><br>    @Bean<br>    public MessageListenerAdapter messageListener( ) {<br>        return new MessageListenerAdapter(redisMessageHandler);<br>    }<br>}</pre><p>Publisher interface:</p><pre>public interface MessagePublisher {<br>    void publish(String message);<br>}</pre><p>Publisher service class:</p><pre>import org.springframework.data.redis.core.RedisTemplate;<br>import org.springframework.data.redis.listener.ChannelTopic;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>@Slf4j<br>public class RedisMessagePublisher implements MessagePublisher{<br><br>    private final RedisTemplate&lt;String, Object&gt; redisTemplate;<br>    private final ChannelTopic topic;<br><br>    public RedisMessagePublisher(RedisTemplate&lt;String, Object&gt; redisTemplate, ChannelTopic topic) {<br>        this.redisTemplate = redisTemplate;<br>        this.topic = topic;<br>    }<br><br>    @Override<br>    public void publish(String message) {<br>        redisTemplate.convertAndSend(topic.getTopic(), message);<br>        log.info(&quot;Published : {}&quot;, topic.getTopic());<br>    }<br><br>}</pre><p>RedisMessageHandler class is the listener class and shown belove:</p><pre>@Service<br>@Slf4j<br>public class RedisMessageHandler implements MessageListener {<br><br>    @Override<br>    public void onMessage(Message message, byte[] pattern) {<br>        log.info(&quot;Message : {}, from channel : {}&quot;, message, message.getChannel());<br>        // message handle logic<br>    }<br>    <br>}</pre><p><strong>Usage</strong>: after injecting redisMessagePublisher messages can be published</p><pre>redisMessagePublisher.publish(&quot;test-message&quot;);</pre><h4>Redis GUI : RedisInsight</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*YoI96mTffUi89eSG" /></figure><p>Download link : <a href="https://redis.io/insight/">https://redis.io/insight/</a></p><p><em>Originally published at </em><a href="https://musticode.gitbook.io/springboot-configurations"><em>https://musticode.gitbook.io</em></a><em> on May 5, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e27bfae48a9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reading property files at ease]]></title>
            <link>https://musticode.medium.com/reading-property-files-at-ease-745b1c418bbe?source=rss-b8a56f7c387c------2</link>
            <guid isPermaLink="false">https://medium.com/p/745b1c418bbe</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[properties-file]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Mustafa Karataş]]></dc:creator>
            <pubDate>Sat, 23 Mar 2024 13:18:59 GMT</pubDate>
            <atom:updated>2024-03-23T13:18:59.527Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yzAQyUkpYEj2Ez4i" /></figure><p>Owner API’s take the method of defining a Java interface linked to a properties file. Reducing the amount of code needed to manage application configuration via Java properties files is the aim of the Owner API</p><h4>Simple example</h4><p>Suppose that we have a application.properties file as:</p><pre>timeout.duration=30<br>server.host.name=localhost</pre><p>aeonbits owner maven dependency</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.aeonbits.owner&lt;/groupId&gt;<br>    &lt;artifactId&gt;owner&lt;/artifactId&gt;<br>    &lt;version&gt;1.0.8&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>Our config reading interface</p><pre>import org.aeonbits.owner.Config;<br><br>@org.aeonbits.owner.Config.Sources({<br>        &quot;file:./src/test/resources/application.properties&quot;}<br>)<br>public interface TestPropertyConfig extends Config {<br><br>    @Key(&quot;timeout.duration&quot;)<br>    @DefaultValue(&quot;40&quot;)<br>    int timeOutDuration();<br><br><br>    @Key(&quot;server.host.name&quot;)<br>    String serverHostName();<br><br>}</pre><ul><li>@Sources : Specifies the source from which to load the properties file. It has to be specified in a URI string format</li><li>@Key : The key used for lookup for the property</li><li>@DefaultValue : If no property is identified, the default value will be used</li></ul><h3>Testing and usage of config interface</h3><pre>TestPropertyConfig config = ConfigFactory.create(TestPropertyConfig.class);<br><br>System.out.println(config.timeOutDuration());<br>System.out.println(config.serverHostName())</pre><h4>For detailed information and documentation</h4><ul><li><a href="https://matteobaccan.github.io/owner/">OWNER</a></li><li><a href="https://github.com/matteobaccan/owner/tree/master">GitHub - matteobaccan/owner: Get rid of the boilerplate code in properties based configuration.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=745b1c418bbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka — SpringBoot Integration]]></title>
            <link>https://musticode.medium.com/kafka-springboot-integration-34bc6cdb0e06?source=rss-b8a56f7c387c------2</link>
            <guid isPermaLink="false">https://medium.com/p/34bc6cdb0e06</guid>
            <category><![CDATA[zookeeper]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Mustafa Karataş]]></dc:creator>
            <pubDate>Sun, 29 Oct 2023 14:59:20 GMT</pubDate>
            <atom:updated>2023-10-29T14:59:20.956Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kafka — SpringBoot Integration</h3><p>docker-compose.yml for kafka and zookeeper</p><pre>version: &#39;3&#39;<br>services:<br>  zookeeper:<br>    image: confluentinc/cp-zookeeper:7.0.1<br>    container_name: zookeeper<br>    environment:<br>      ZOOKEEPER_CLIENT_PORT: 2181<br>      ZOOKEEPER_TICK_TIME: 2000<br>  broker:<br>    image: confluentinc/cp-kafka:7.0.1<br>    container_name: broker<br>    ports:<br>      - &quot;9092:9092&quot;<br>    depends_on:<br>      - zookeeper<br>    environment:<br>      KAFKA_BROKER_ID: 1<br>      KAFKA_ZOOKEEPER_CONNECT: &#39;zookeeper:2181&#39;<br>      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_INTERNAL:PLAINTEXT<br>      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092,PLAINTEXT_INTERNAL://broker:29092<br>      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br>      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1<br>      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1</pre><p>pom.xml dependencies</p><h3>Producer Application</h3><p>application properties</p><pre>spring.kafka.topic.name=order_topics<br><br>spring.kafka.consumer.bootstrap-servers=localhost:9092<br>spring.kafka.consumer.group-id=stock<br>spring.kafka.consumer.auto-offset-reset=earliest<br>spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer<br>spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer<br>spring.kafka.consumer.properties.spring.json.trusted.packages=*<br><br>spring.kafka.producer.bootstrap-servers=localhost:9092<br>spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer<br>spring.kafka.producer.value-serializer=org.springframework.kafka.support.serializer.JsonSerializer</pre><p>KafkaTopicConfig.class</p><pre>@Configuration<br>public class KafkaTopicConfig {<br><br>    @Value(&quot;${spring.kafka.topic.name}&quot;)<br>    private String topicName;<br><br>    @Bean<br>    public NewTopic topic(){<br>        return TopicBuilder.name(topicName)<br>                .build();<br>    }<br><br>}</pre><blockquote><em>There should be a OrderEvent class to send message as an object</em></blockquote><pre>public class OrderEvent {<br>    private String message;<br>    private String status;<br>    private Order order;<br>    //constructor<br>    //setters and getters<br>}</pre><p>OrderProducer.class</p><p>We should pass OrderEvent object to sendMessage method, event is set as payload.withPayload(event).<br>topic name is set as header .setHeader(KafkaHeaders.TOPIC, topic.name())</p><pre>@Service<br>@Slf4j<br>public class OrderProducer {<br><br>    private final NewTopic topic;<br>    private final KafkaTemplate&lt;String, OrderEvent&gt; kafkaTemplate;<br><br>    private OrderProducer(NewTopic topic, KafkaTemplate&lt;String, OrderEvent&gt; kafkaTemplate){<br>        this.topic = topic;<br>        this.kafkaTemplate = kafkaTemplate;<br>    }<br><br>    public void sendMessage(OrderEvent event){<br>        // create message<br>        Message&lt;OrderEvent&gt; message = MessageBuilder<br>                .withPayload(event)<br>                .setHeader(KafkaHeaders.TOPIC, topic.name())<br>                .build();<br><br>        kafkaTemplate.send(message);<br>    }<br><br>}</pre><p>OrderService.class</p><p>OrderProducer is autowired to OrderService.class to send message</p><pre>@Service<br>@RequiredArgsConstructor<br>public class OrderService {<br><br>    private final OrderProducer orderProducer;<br><br>    public String placeOrder(Order order){<br><br>        order.setOrderId(UUID.randomUUID().toString());<br><br>        OrderEvent orderEvent = new OrderEvent();<br>        orderEvent.setStatus(&quot;PENDING&quot;);<br>        orderEvent.setMessage(&quot;Order is pending state&quot;);<br>        orderEvent.setOrder(order);<br><br>        orderProducer.sendMessage(orderEvent);<br><br>        return &quot;Order placed...&quot;;<br>    }<br><br>}</pre><h3>Consumer Application</h3><p>consumer properties can be just deserializer, but I want to give deserializer and serializers</p><p>application.properties</p><pre>spring.kafka.topic.name=order_topics<br><br>spring.kafka.consumer.bootstrap-servers=localhost:9092<br>spring.kafka.consumer.group-id=stock<br>spring.kafka.consumer.auto-offset-reset=earliest<br>spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer<br>spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer<br>spring.kafka.consumer.properties.spring.json.trusted.packages=*<br><br>spring.kafka.producer.bootstrap-servers=localhost:9092<br>spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer<br>spring.kafka.producer.value-serializer=org.springframework.kafka.support.serializer.JsonSerializer</pre><p>OrderConsumer.class</p><p>OrderConsumer is a service, @KafkaListener annotation should be used for consume method. OrderEvent should be passed to consume method.</p><pre>@Service<br>public class OrderConsumer {<br><br><br>    @KafkaListener(<br>            topics = &quot;${spring.kafka.topic.name}&quot;,<br>            groupId = &quot;${spring.kafka.consumer.group-id}&quot;<br>    )<br>    public void consume(OrderEvent orderEvent){<br>        System.out.println(orderEvent.getOrder().getOrderId());<br>        System.out.println(orderEvent.getOrder().getName());<br>        System.out.println(orderEvent.getOrder().getQty());<br>    }<br><br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34bc6cdb0e06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jenkins-Docker Selenium Hub Integration]]></title>
            <link>https://musticode.medium.com/jenkins-docker-selenium-hub-integration-c306704bbdb8?source=rss-b8a56f7c387c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c306704bbdb8</guid>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[selenium-test-automation]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[selenium-grid]]></category>
            <category><![CDATA[selenium]]></category>
            <dc:creator><![CDATA[Mustafa Karataş]]></dc:creator>
            <pubDate>Thu, 08 Jun 2023 12:37:08 GMT</pubDate>
            <atom:updated>2023-10-29T14:53:38.605Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Selenium Grid</strong></h3><p>Selenium Grid allows the execution of WebDriver scripts on remote machines by routing commands sent by the client to remote browser instances.</p><ul><li>Provide an easy way to run tests in parallel on multiple machines</li><li>Allow testing on different browser versions</li><li>Enable cross platform testing</li></ul><p>Need of Selenium Grid</p><ol><li>What if you want to execute your test cases for different Operating Systems?</li><li>How to run your test cases in the different version of the same browser?</li><li>How to run your test cases in multiple browsers?</li><li>Why should a scenario wait for the execution of other test cases even if it does not depend upon any test cases?</li></ol><h3><strong>Installing Docker on Ubuntu</strong></h3><p>Update the apt package index and install packages to allow apt to use a repository over HTTPS:</p><pre>sudo apt-get update<br>sudo apt-get install \<br>    ca-certificates \<br>    curl \<br>    gnupg \<br>    lsb-release</pre><p>Add Docker’s official GPG key:</p><pre>sudo mkdir -p /etc/apt/keyrings<br>curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg</pre><p>Use the following command to set up the repository:</p><pre>echo \<br>  &quot;deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \<br>  $(lsb_release -cs) stable&quot; | sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null</pre><h3>Install Docker Engine</h3><ol><li>Update the apt package index:</li></ol><pre>sudo apt-get update</pre><p>2.Install Docker Engine, containerd, and Docker Compose.</p><pre>sudo apt-get install docker-ce docker-ce-cli containerd.io docker-compose-plugin</pre><p>Docker installed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T1cacna-Tb-vBMx4GrYFMQ.png" /><figcaption>docker desktop on ubuntu</figcaption></figure><p><a href="https://docs.docker.com/engine/install/ubuntu/"></a></p><p>Also we can install Docker desktop Debian package on Ubuntu machine</p><p><a href="https://docs.docker.com/desktop/install/ubuntu/">Install Docker Desktop on Ubuntu</a></p><h3><strong>Install Jenkins on Ubuntu</strong></h3><h4>Installation of Java</h4><p>Jenkins requires Java in order to run, yet certain distributions don’t include this by default and <a href="https://www.jenkins.io/doc/administration/requirements/java/">some Java versions are incompatible</a> with Jenkins.</p><p>There are multiple Java implementations which you can use. <a href="https://openjdk.java.net/">OpenJDK</a> is the most popular one at the moment, we will use it in this guide.</p><p>Update the Debian apt repositories, install OpenJDK 11, and check the installation with the commands:</p><pre>$ sudo apt update<br>$ sudo apt install openjdk-11-jre<br>$ java -version<br>openjdk version &quot;11.0.12&quot; 2021-07-20<br>OpenJDK Runtime Environment (build 11.0.12+7-post-Debian-2)<br>OpenJDK 64-Bit Server VM (build 11.0.12+7-post-Debian-2, mixed mode, sharing)</pre><h4>Debian/Ubuntu</h4><p>On Debian and Debian-based distributions like Ubuntu you can install Jenkins through apt.</p><pre>curl -fsSL https://pkg.jenkins.io/debian-stable/jenkins.io.key | sudo tee \<br>  /usr/share/keyrings/jenkins-keyring.asc &gt; /dev/null<br>echo deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc] \<br>  https://pkg.jenkins.io/debian-stable binary/ | sudo tee \<br>  /etc/apt/sources.list.d/jenkins.list &gt; /dev/null<br>sudo apt-get update<br>sudo apt-get install jenkins</pre><h4>Start Jenkins</h4><p>We can enable the Jenkins service to start at boot with the command:</p><pre>sudo systemctl enable jenkins</pre><p>Starting Jenkins</p><pre>sudo systemctl start jenkins</pre><p>Checking Jenkins status</p><pre>sudo systemctl status jenkins</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*O3APjWV78LydE8XI-5ASYA.png" /><figcaption>jenkins status</figcaption></figure><p>Jenkins is running on 8080 port</p><p>Initial Admin Password can be found:</p><pre>sudo cat  /var/lib/jenkins/secrets/initialAdminPassword</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*s0AfWbQOtL4i3CEYdyJ96w.png" /><figcaption>admin password</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lOOEv2Hm24TMxOp0LjhfJg.png" /></figure><p>Customize plugins:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MS31PL0YSKxeY-y5k0s1SQ.png" /><figcaption>plugin install</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7DMOoLVNXA0u1eS38jee5Q.png" /><figcaption>getting started</figcaption></figure><p>We should manage configurations</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pQvjZnUBQ35xk3kwbRJwAg.png" /></figure><p>Dashboard → Manage Jenkins → Global Tool Configuration</p><h4>Java Configuration:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0-eZEFpfinxQNfUxhDKJ4w.png" /></figure><p>We will download jdk from binary archive. Otherwise JAVA_HOME should be referred</p><p>Download URL for binary archive</p><pre>https://download.java.net/java/GA/jdk11/13/GPL/openjdk-11.0.1_linux-x64_bin.tar.gz</pre><p>Subdirectory of extracted archive</p><pre>jdk-11.0.1</pre><p>Label</p><pre>openjdk-11</pre><p>Git should be installed on your machine, otherwise git should be installed automatically</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xWkjglK-sypJShXfgy4pGQ.png" /></figure><h4>Maven Configuration</h4><p>We will install maven automatically</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*THqphYSgGVzPqQLTBxMYkw.png" /></figure><h4>Java Selenium Test Application</h4><p>Creating very basic Java maven test application</p><p>Our pom.xml file:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;<br>         xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>         xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;<br>    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br><br>    &lt;groupId&gt;com.demo&lt;/groupId&gt;<br>    &lt;artifactId&gt;demo-test-project&lt;/artifactId&gt;<br>    &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;<br>    &lt;name&gt;demo-test-project&lt;/name&gt;<br><br>    &lt;properties&gt;<br>        &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;<br>        &lt;maven.compiler.target&gt;11&lt;/maven.compiler.target&gt;<br>        &lt;maven.compiler.source&gt;11&lt;/maven.compiler.source&gt;<br>        &lt;aspectj.version&gt;1.9.9.1&lt;/aspectj.version&gt;<br>        &lt;allure.version&gt;2.19.0&lt;/allure.version&gt;<br>    &lt;/properties&gt;<br><br>    &lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.seleniumhq.selenium&lt;/groupId&gt;<br>            &lt;artifactId&gt;selenium-java&lt;/artifactId&gt;<br>            &lt;version&gt;4.4.0&lt;/version&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;io.qameta.allure&lt;/groupId&gt;<br>            &lt;artifactId&gt;allure-testng&lt;/artifactId&gt;<br>            &lt;version&gt;${allure.version}&lt;/version&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;io.github.bonigarcia&lt;/groupId&gt;<br>            &lt;artifactId&gt;webdrivermanager&lt;/artifactId&gt;<br>            &lt;version&gt;5.3.0&lt;/version&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.hamcrest&lt;/groupId&gt;<br>            &lt;artifactId&gt;hamcrest&lt;/artifactId&gt;<br>            &lt;version&gt;2.2&lt;/version&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.assertj&lt;/groupId&gt;<br>            &lt;artifactId&gt;assertj-core&lt;/artifactId&gt;<br>            &lt;version&gt;3.23.1&lt;/version&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.testng&lt;/groupId&gt;<br>            &lt;artifactId&gt;testng&lt;/artifactId&gt;<br>            &lt;version&gt;7.6.1&lt;/version&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.slf4j&lt;/groupId&gt;<br>            &lt;artifactId&gt;slf4j-simple&lt;/artifactId&gt;<br>            &lt;version&gt;1.7.30&lt;/version&gt;<br>            &lt;scope&gt;test&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br>    &lt;build&gt;<br>        &lt;plugins&gt;<br>            &lt;plugin&gt;<br>                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>                &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;<br>                &lt;version&gt;2.22.2&lt;/version&gt;<br>                &lt;configuration&gt;<br>                    &lt;testFailureIgnore&gt;true&lt;/testFailureIgnore&gt;<br>                    &lt;argLine&gt;<br>                        -javaagent:&quot;${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar&quot;<br>                    &lt;/argLine&gt;<br>                    &lt;systemProperties&gt;<br>                        &lt;property&gt;<br>                            &lt;name&gt;allure.results.directory&lt;/name&gt;<br>                            &lt;value&gt;${project.build.directory}/allure-results&lt;/value&gt;<br>                        &lt;/property&gt;<br>                    &lt;/systemProperties&gt;<br>                    &lt;suiteXmlFiles&gt;<br>                        &lt;suiteXmlFile&gt;<br>                            TestNG.xml<br>                        &lt;/suiteXmlFile&gt;<br>                    &lt;/suiteXmlFiles&gt;<br>                &lt;/configuration&gt;<br>                &lt;dependencies&gt;<br>                    &lt;dependency&gt;<br>                        &lt;groupId&gt;org.aspectj&lt;/groupId&gt;<br>                        &lt;artifactId&gt;aspectjweaver&lt;/artifactId&gt;<br>                        &lt;version&gt;${aspectj.version}&lt;/version&gt;<br>                    &lt;/dependency&gt;<br>                &lt;/dependencies&gt;<br>            &lt;/plugin&gt;<br>            &lt;plugin&gt;<br>                &lt;groupId&gt;io.qameta.allure&lt;/groupId&gt;<br>                &lt;artifactId&gt;allure-maven&lt;/artifactId&gt;<br>                &lt;version&gt;2.11.2&lt;/version&gt;<br>            &lt;/plugin&gt;<br>        &lt;/plugins&gt;<br>    &lt;/build&gt;<br>&lt;/project&gt;</pre><p>We will configurate our tests via TestNG.xml file.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE suite SYSTEM &quot;http://testng.org/testng-1.0.dtd&quot;&gt;<br>&lt;suite name=&quot;Practice Suite&quot;&gt;<br>    &lt;test name=&quot;Test Basics 1&quot;&gt;<br>        &lt;parameter name=&quot;browserName&quot; value=&quot;firefox-grid&quot;/&gt;<br>        &lt;classes&gt;<br>            &lt;class name=&quot;com.demo.demotestproject.test.GoogleTest&quot;&gt;&lt;/class&gt;<br>        &lt;/classes&gt;<br>    &lt;/test&gt;<br>&lt;/suite&gt;</pre><p>Our BasePage class</p><pre>public class BasePage {<br><br>    public WebDriver driver;<br>    public WebDriverWait wait;<br><br><br>    JavascriptExecutor js;<br><br><br><br>    public BasePage(WebDriver driver){<br>        this.driver = driver;<br>        wait = new WebDriverWait(driver, Duration.ofSeconds(20));<br>        js = (JavascriptExecutor)driver;<br>    }<br><br>    public void waitForLocator(By locator){<br>        wait.until(ExpectedConditions.elementToBeClickable(locator));<br>    }<br><br>    public WebElement findBy(By locator){<br>        return driver.findElement(locator);<br>    }<br><br><br>    public void alertAccept(){<br>        driver.switchTo().alert().accept();<br>    }<br><br>    public void clearCookies(){<br>        driver.manage().deleteAllCookies();<br>    }<br>    public void maximizeWindow(){<br>        driver.manage().window().maximize();<br>    }<br><br>    public void click(By locator){<br>        waitForLocator(locator);<br>        findBy(locator).click();<br>    }<br><br>    public void setText(By locator, String text){<br>        waitForLocator(locator);<br>        findBy(locator).clear();<br>        findBy(locator).sendKeys(text);<br>    }<br><br>    public String getText(By locator){<br>        waitForLocator(locator);<br>        return findBy(locator).getText();<br>    }<br><br>    public boolean isAt(By locator){<br>       return findBy(locator).isDisplayed();<br>    }<br><br>}</pre><p>We have implemented basic Selenium driver functions</p><p>Basic page object</p><pre>public class GooglePage extends BasePage{<br>    private final String GOOGLE_URL = &quot;https://www.google.com/&quot;;<br><br>    private By searchInputLocator = By.cssSelector(&quot;input[title=&#39;Ara&#39;]&quot;);<br><br>    public GooglePage(WebDriver driver) {<br>        super(driver);<br>    }<br><br>    public void getGooglePage(){<br>        driver.get(GOOGLE_URL);<br>    }<br><br>    public boolean googlePageOpened(){<br>        return isAt(searchInputLocator);<br>    }<br><br>}</pre><p>We should implement DriverManager and DriverOptions classes. When we send requests, selenium grid will understand our driver via driver options.</p><p>DriverOptions class:</p><pre>public class DriverOptions {<br>    private ChromeOptions chromeOptions;<br>    private FirefoxOptions firefoxOptions;<br>    private FirefoxProfile firefoxProfile;<br><br>    public void setFirefoxOptions(){<br>        firefoxOptions = new FirefoxOptions();<br>        firefoxProfile = new FirefoxProfile();<br>        //Accept Untrusted Certificates<br>        firefoxProfile.setAcceptUntrustedCertificates(true);<br>        firefoxProfile.setAssumeUntrustedCertificateIssuer(false);<br>        //Use No Proxy Settings<br>        firefoxProfile.setPreference(&quot;network.proxy.type&quot;, 0);<br>        //Set Firefox profile to capabilities<br><br>        //options.setCapability(FirefoxDriver.PROFILE, profile);<br>    }<br><br>    public FirefoxOptions getFirefoxOptions(){<br>        setFirefoxOptions();<br>        return firefoxOptions;<br>    }<br><br><br><br>    public void setChromeOptions(){<br>        chromeOptions = new ChromeOptions();<br>        chromeOptions.addArguments(&quot;start-maximized&quot;);<br>        chromeOptions.addArguments(&quot;ignore-certificate-errors&quot;);<br>        chromeOptions.addArguments(&quot;--disable-dev-shm-usage&quot;);<br>        chromeOptions.addArguments(&quot;--no-sandbox&quot;);<br>        chromeOptions.addArguments(&quot;--disable-popup-blocking&quot;);<br>    }<br><br>    public ChromeOptions getChrome(){<br>        setChromeOptions();<br>        return chromeOptions;<br>    }<br><br>}</pre><p>DriverManager class</p><pre>public class DriverManager {<br>    public WebDriver driver;<br>    public DriverOptions driverOptions;<br><br>    public void setDriver(String browserName) throws MalformedURLException {<br>        driverOptions = new DriverOptions();<br><br>        if (browserName != null){<br><br>            switch (browserName){<br>                case &quot;chrome-local&quot;:<br>                    WebDriverManager.chromedriver().setup();<br>                    driver = new ChromeDriver();<br>                    break;<br><br>                case &quot;firefox-local&quot;:<br>                    WebDriverManager.firefoxdriver().setup();<br>                    driver = new FirefoxDriver();<br>                    break;<br><br>                case &quot;chrome-grid&quot;:<br>                    driver = new RemoteWebDriver(new URL(&quot;http://localhost:4444/wd/hub&quot;), driverOptions.getChrome());<br>                    break;<br><br>                case &quot;firefox-grid&quot;:<br>                    driver = new RemoteWebDriver(new URL(&quot;http://localhost:4444/wd/hub&quot;), driverOptions.getFirefoxOptions());<br>                    break;<br><br>            }<br><br>        }<br><br>    }<br><br><br>    public void tearDown(){<br>        if(driver != null ){<br>            driver.quit();<br>        }<br>    }<br><br>}</pre><p>We have used also WebDriverManager for local test runs. WebDriverManager will handle drivers via installing before test runs. This functions can be used for rapid test runs in your local machine.</p><p>If we want to use Grid we can just change parameters in TestNG.xml file, when no parameters found, test will be started automatically in our local machine.</p><p>BaseTest class</p><pre><br>public class BaseTest extends DriverManager {<br><br><br>    @BeforeTest<br>    @Parameters(value = {&quot;browserName&quot;} )<br>    public void initializeBrowser(@Optional String browserName) throws MalformedURLException {<br><br>        if(browserName == null){<br>            setDriver(&quot;chrome-local&quot;);<br><br>            System.out.println(&quot;Local Chrome driver is started&quot;);<br>            driver.manage().window().maximize();<br><br>        }else{<br>            setDriver(browserName);<br>            System.out.println(&quot;Browser is opened: &quot;+ browserName);<br>        }<br>    }<br><br><br>    @AfterTest<br>    public void terminateBrowser(){<br>        tearDown();<br>        System.out.println(&quot;Driver is removed&quot;);<br>    }<br><br><br>}<br></pre><p>Basic scenario test class</p><pre>public class GoogleTest extends BaseTest {<br>    GooglePage googlePage;<br><br>    @Test<br>    public void googleTest() throws InterruptedException {<br>        googlePage = new GooglePage(driver);<br>        googlePage.getGooglePage();<br>        Assert.assertEquals(googlePage.googlePageOpened(), true, &quot;Google is not opened&quot;);<br>    }<br><br>}</pre><p>We will use Selenium Hub on docker</p><p>docker-compose.yml file can be found in selenium docker github page</p><p><a href="https://github.com/SeleniumHQ/docker-selenium">GitHub - SeleniumHQ/docker-selenium: Provides a simple way to run Selenium Grid with Chrome, Firefox, and Edge using Docker, making it easier to perform browser automation</a></p><p>Docker selenium hub official image</p><p><a href="https://hub.docker.com/r/selenium/hub">Docker</a></p><p>We should add docker-compose.yml file in our source code</p><pre># To execute this docker-compose yml file use `docker-compose -f docker-compose-v3.yml up`<br># Add the `-d` flag at the end for detached execution<br># To stop the execution, hit Ctrl+C, and then `docker-compose -f docker-compose-v3.yml down`<br>version: &quot;3&quot;<br>services:<br>  chrome:<br>    image: selenium/node-chrome:4.1.3-20220405<br>    shm_size: 2gb<br>    depends_on:<br>      - selenium-hub<br>    environment:<br>      - SE_EVENT_BUS_HOST=selenium-hub<br>      - SE_EVENT_BUS_PUBLISH_PORT=4442<br>      - SE_EVENT_BUS_SUBSCRIBE_PORT=4443<br><br>  edge:<br>    image: selenium/node-edge:4.1.3-20220405<br>    shm_size: 2gb<br>    depends_on:<br>      - selenium-hub<br>    environment:<br>      - SE_EVENT_BUS_HOST=selenium-hub<br>      - SE_EVENT_BUS_PUBLISH_PORT=4442<br>      - SE_EVENT_BUS_SUBSCRIBE_PORT=4443<br><br>  firefox:<br>    image: selenium/node-firefox:4.1.3-20220405<br>    shm_size: 2gb<br>    depends_on:<br>      - selenium-hub<br>    environment:<br>      - SE_EVENT_BUS_HOST=selenium-hub<br>      - SE_EVENT_BUS_PUBLISH_PORT=4442<br>      - SE_EVENT_BUS_SUBSCRIBE_PORT=4443<br><br>  selenium-hub:<br>    image: selenium/hub:4.1.3-20220405<br>    container_name: selenium-hub<br>    ports:<br>      - &quot;4442:4442&quot;<br>      - &quot;4443:4443&quot;<br>      - &quot;4444:4444&quot;</pre><p>We will start container</p><pre>sudo docker-compose up -d</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*-na7W_xvchNe0sQDnVh1Cg.png" /><figcaption>docker selenium hub started</figcaption></figure><p>in 4444 port</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5wcfxM6C5wqtGSU4tV65Og.png" /><figcaption>selenium grid docker ui</figcaption></figure><p>Now Jenkins and Selenium Hub are ready to test. We will create a pipeline. Our tests in pipeline will trigger selenium grid on docker. Source codes will be installed from Github. Tests will be ran on selenium docker image.</p><p>If we want to scale up the browser services and we can change the parameters in docker-compose file.</p><h4>Create a New Item in Jenkins</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z67TVxksr_6pJ9uVLL8rvQ.png" /><figcaption>new item</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2kcIy_WY2UAGZ215y6_tMQ.png" /><figcaption>pipeline</figcaption></figure><p>Pipeline:</p><pre>pipeline {<br>    agent any<br><br>    tools {<br>        // Install the Maven version configured as &quot;M3&quot; and add it to the path.<br>        maven &quot;M3&quot;<br>    }<br><br>    stages {<br>        stage(&#39;Build&#39;) {<br>            steps {<br>                // Get some code from a GitHub repository<br>                git &#39;https://github.com/musticode/demo-test-project.git&#39;<br><br>                sh &quot;mvn clean test&quot;<br>             <br><br>            }<br><br>        }<br>        <br>        stage(&#39;Reports&#39;) {<br>            steps {<br>                script {<br>                        allure([<br>                                includeProperties: false,<br>                                jdk: &#39;&#39;,<br>                                properties: [],<br>                                reportBuildPolicy: &#39;ALWAYS&#39;,<br>                                results: [[path: &#39;target/allure-results&#39;]]<br>                        ])<br>                }<br>            }<br>}<br>        <br>    }<br>}</pre><p>Build now</p><p>Firefox node:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*-8fJUD9vmxm_YqkHcLadng.png" /></figure><p>Session</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T4kSuVE8KLqyQ2KfHF5PWg.png" /><figcaption>sessions tab</figcaption></figure><p>Live VNC</p><p>Password: secret</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-K42n7E76aImDQTiOwuUIw.png" /><figcaption>test live</figcaption></figure><p>Build history</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_Y3hGQ_9gPJSKypaelgrg.png" /><figcaption>builds</figcaption></figure><p>Build console output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_r9bi-GyoZn93tn1MjCbA.png" /><figcaption>build console output</figcaption></figure><p>Allure reports</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Sj07cD_APVfCflbjKOWXQ.png" /><figcaption>allure reports</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c306704bbdb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>