66a928677415995de5ba554e2cdce9d803a7fc12
[policy/apex-pdp.git] / testsuites / integration / integration-uservice-test / src / test / java / org / onap / policy / apex / testsuites / integration / uservice / adapt / kafka / KafkaEventProducer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019-2020 Nordix Foundation.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.testsuites.integration.uservice.adapt.kafka;
23
24 import com.salesforce.kafka.test.junit4.SharedKafkaTestResource;
25
26 import java.time.Duration;
27
28 import org.apache.kafka.clients.producer.Producer;
29 import org.apache.kafka.clients.producer.ProducerRecord;
30 import org.apache.kafka.common.serialization.StringSerializer;
31 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
32 import org.onap.policy.apex.testsuites.integration.uservice.adapt.events.EventGenerator;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 /**
37  * The Class KafkaEventProducer.
38  *
39  * @author Liam Fallon (liam.fallon@ericsson.com)
40  */
41 public class KafkaEventProducer implements Runnable {
42     // Get a reference to the logger
43     private static final Logger LOGGER = LoggerFactory.getLogger(KafkaEventProducer.class);
44
45     private final String topic;
46     private final SharedKafkaTestResource sharedKafkaTestResource;
47     private final int eventCount;
48     private final boolean xmlEvents;
49     private final long eventInterval;
50     private long eventsSentCount = 0;
51
52     private final Thread producerThread;
53     private boolean sendEventsFlag = false;
54     private volatile boolean stopFlag = false;
55
56     /**
57      * Instantiates a new kafka event producer.
58      *
59      * @param topic the topic
60      * @param sharedKafkaTestResource the kafka server address
61      * @param eventCount the event count
62      * @param xmlEvents the xml events
63      * @param eventInterval the event interval
64      */
65     public KafkaEventProducer(final String topic, final SharedKafkaTestResource sharedKafkaTestResource,
66         final int eventCount, final boolean xmlEvents, final long eventInterval) {
67         this.topic = topic;
68         this.sharedKafkaTestResource = sharedKafkaTestResource;
69         this.eventCount = eventCount;
70         this.xmlEvents = xmlEvents;
71         this.eventInterval = eventInterval;
72
73         producerThread = new Thread(this);
74         producerThread.start();
75     }
76
77     /**
78      * {@inheritDoc}.
79      */
80     @Override
81     public void run() {
82         final Producer<String, String> producer = sharedKafkaTestResource.getKafkaTestUtils()
83             .getKafkaProducer(StringSerializer.class, StringSerializer.class);
84
85         while (producerThread.isAlive() && !stopFlag) {
86             ThreadUtilities.sleep(50);
87
88             if (sendEventsFlag) {
89                 sendEventsToTopic(producer);
90                 sendEventsFlag = false;
91             }
92         }
93
94         producer.close(Duration.ofMillis(1000));
95     }
96
97     /**
98      * Send events.
99      */
100     public void sendEvents() {
101         sendEventsFlag = true;
102     }
103
104     /**
105      * Send events to topic.
106      *
107      * @param producer the producer
108      */
109     private void sendEventsToTopic(final Producer<String, String> producer) {
110         LOGGER.debug("{} : sending events to Kafka server, event count {}, xmlEvents {}",
111             KafkaEventProducer.class.getName(), eventCount, xmlEvents);
112
113         for (int i = 0; i < eventCount; i++) {
114             LOGGER.debug("{} : waiting {} milliseconds before sending next event", KafkaEventProducer.class.getName(),
115                 eventInterval);
116             ThreadUtilities.sleep(eventInterval);
117
118             String eventString = null;
119             if (xmlEvents) {
120                 eventString = EventGenerator.xmlEvent();
121             } else {
122                 eventString = EventGenerator.jsonEvent();
123             }
124             producer.send(new ProducerRecord<String, String>(topic, "Event" + i + "Of" + eventCount, eventString));
125             producer.flush();
126             eventsSentCount++;
127             LOGGER.debug("****** Sent event No. {} ******\n{}", eventsSentCount, eventString);
128         }
129         LOGGER.debug("{}: completed", KafkaEventProducer.class.getName());
130     }
131
132     /**
133      * Gets the events sent count.
134      *
135      * @return the events sent count
136      */
137     public long getEventsSentCount() {
138         return eventsSentCount;
139     }
140
141     /**
142      * Shutdown.
143      */
144     public void shutdown() {
145         LOGGER.debug("{} : stopping", KafkaEventProducer.class.getName());
146
147         stopFlag = true;
148
149         while (producerThread.isAlive()) {
150             ThreadUtilities.sleep(10);
151         }
152
153         LOGGER.debug("{} : stopped", KafkaEventProducer.class.getName());
154     }
155
156     public boolean isAlive() {
157         return producerThread.isAlive();
158     }
159 }