Refactor NBINotification & add ServiceListener tests
[transportpce.git] / nbinotifications / src / main / java / org / opendaylight / transportpce / nbinotifications / producer / Publisher.java
1 /*
2  * Copyright © 2020 Orange, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.transportpce.nbinotifications.producer;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import java.util.Properties;
12 import org.apache.kafka.clients.producer.KafkaProducer;
13 import org.apache.kafka.clients.producer.Producer;
14 import org.apache.kafka.clients.producer.ProducerConfig;
15 import org.apache.kafka.clients.producer.ProducerRecord;
16 import org.apache.kafka.common.serialization.StringSerializer;
17 import org.opendaylight.transportpce.common.converter.JsonStringConverter;
18 import org.opendaylight.transportpce.nbinotifications.serialization.ConfigConstants;
19 import org.opendaylight.transportpce.nbinotifications.utils.NbiNotificationsUtils;
20 import org.opendaylight.yangtools.yang.binding.DataObject;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23
24 public class Publisher<T extends DataObject> {
25     private static final Logger LOG = LoggerFactory.getLogger(Publisher.class);
26
27     private final String id;
28     private final Producer<String, T> producer;
29
30     public Publisher(String id, String publisherServer, JsonStringConverter<T> serializer, Class<?> serializerConf) {
31         Properties properties = NbiNotificationsUtils.loadProperties("publisher.properties");
32         properties.put(ProducerConfig.CLIENT_ID_CONFIG, id);
33         if (publisherServer != null && !publisherServer.isBlank()) {
34             properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, publisherServer);
35         }
36         properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
37         properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG , serializerConf);
38         properties.put(ConfigConstants.CONVERTER , serializer);
39         LOG.info("Creation publisher for id {} with properties {}", id, properties);
40         producer = new KafkaProducer<>(properties);
41         this.id = id;
42     }
43
44     @VisibleForTesting Publisher(String id, Producer<String, T> producer) {
45         this.producer = producer;
46         this.id = id;
47     }
48
49     public void close() {
50         producer.close();
51     }
52
53     public void sendEvent(T notification, String topic) {
54         LOG.info("SendEvent request to topic '{}' ", topic);
55         producer.send(new ProducerRecord<>(topic, id, notification));
56         producer.flush();
57     }
58 }