Improve performance of updateDataLeaves
[cps.git] / cps-ncmp-service / src / main / java / org / onap / cps / ncmp / api / impl / events / EventsPublisher.java
1 /*
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2022-2023 Nordix Foundation
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *       http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.ncmp.api.impl.events;
22
23 import io.cloudevents.CloudEvent;
24 import java.util.Map;
25 import lombok.RequiredArgsConstructor;
26 import lombok.extern.slf4j.Slf4j;
27 import org.apache.kafka.clients.producer.ProducerRecord;
28 import org.apache.kafka.common.header.Headers;
29 import org.apache.kafka.common.header.internals.RecordHeaders;
30 import org.springframework.kafka.core.KafkaTemplate;
31 import org.springframework.kafka.support.SendResult;
32 import org.springframework.stereotype.Service;
33 import org.springframework.util.SerializationUtils;
34 import org.springframework.util.concurrent.ListenableFuture;
35 import org.springframework.util.concurrent.ListenableFutureCallback;
36
37 /**
38  * EventsPublisher to publish events.
39  */
40
41 @Slf4j
42 @Service
43 @RequiredArgsConstructor
44 public class EventsPublisher<T> {
45
46     /** Once all cps events will be modified to cloud compliant, will remove legacyKafkaEventTemplate with
47      it's java configuration file KafkaTemplateConfig. **/
48     @Deprecated(forRemoval = true)
49     private final KafkaTemplate<String, T> legacyKafkaEventTemplate;
50
51     private final KafkaTemplate<String, CloudEvent> cloudEventKafkaTemplate;
52
53     /**
54      * Generic CloudEvent publisher.
55      *
56      * @param topicName valid topic name
57      * @param eventKey  message key
58      * @param event     message payload
59      */
60     public void publishCloudEvent(final String topicName, final String eventKey, final CloudEvent event) {
61         final ListenableFuture<SendResult<String, CloudEvent>> eventFuture
62                 = cloudEventKafkaTemplate.send(topicName, eventKey, event);
63         eventFuture.addCallback(handleCallback(topicName));
64     }
65
66     /**
67      * Generic Event publisher.
68      *
69      * @param topicName valid topic name
70      * @param eventKey  message key
71      * @param event     message payload
72      * @deprecated This method is not needed anymore since the use of headers will be in place.
73      */
74     @Deprecated
75     public void publishEvent(final String topicName, final String eventKey, final T event) {
76         final ListenableFuture<SendResult<String, T>> eventFuture
77                 = legacyKafkaEventTemplate.send(topicName, eventKey, event);
78         eventFuture.addCallback(handleCallback(topicName));
79     }
80
81     /**
82      * Generic Event Publisher with headers.
83      *
84      * @param topicName    valid topic name
85      * @param eventKey     message key
86      * @param eventHeaders event headers
87      * @param event        message payload
88      */
89     public void publishEvent(final String topicName, final String eventKey, final Headers eventHeaders, final T event) {
90
91         final ProducerRecord<String, T> producerRecord =
92                 new ProducerRecord<>(topicName, null, eventKey, event, eventHeaders);
93         final ListenableFuture<SendResult<String, T>> eventFuture = legacyKafkaEventTemplate.send(producerRecord);
94         eventFuture.addCallback(handleCallback(topicName));
95     }
96
97     /**
98      * Generic Event Publisher with headers.
99      *
100      * @param topicName    valid topic name
101      * @param eventKey     message key
102      * @param eventHeaders map of event headers
103      * @param event        message payload
104      */
105     public void publishEvent(final String topicName, final String eventKey, final Map<String, Object> eventHeaders,
106             final T event) {
107
108         publishEvent(topicName, eventKey, convertToKafkaHeaders(eventHeaders), event);
109     }
110
111     private ListenableFutureCallback<SendResult<String, ?>> handleCallback(final String topicName) {
112         return new ListenableFutureCallback<>() {
113             @Override
114             public void onFailure(final Throwable throwable) {
115                 log.error("Unable to publish event to topic : {} due to {}", topicName, throwable.getMessage());
116             }
117
118             @Override
119             public void onSuccess(final SendResult<String, ?> sendResult) {
120                 log.debug("Successfully published event to topic : {} , Event : {}",
121                         sendResult.getRecordMetadata().topic(), sendResult.getProducerRecord().value());
122             }
123         };
124     }
125
126     private Headers convertToKafkaHeaders(final Map<String, Object> eventMessageHeaders) {
127         final Headers eventHeaders = new RecordHeaders();
128         eventMessageHeaders.forEach((key, value) -> eventHeaders.add(key, SerializationUtils.serialize(value)));
129         return eventHeaders;
130     }
131
132 }