f2aced4f6b7a340e21c5ee4918b66c889357e248
[transportpce.git] / nbinotifications / src / main / java / org / opendaylight / transportpce / nbinotifications / serialization / TapiNotificationSerializer.java
1 /*
2  * Copyright © 2021 Nokia, 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.serialization;
9
10 import java.io.IOException;
11 import java.nio.charset.StandardCharsets;
12 import java.util.Map;
13 import org.apache.kafka.common.serialization.Serializer;
14 import org.opendaylight.transportpce.common.converter.JsonStringConverter;
15 import org.opendaylight.yang.gen.v1.nbi.notifications.rev230726.NotificationTapiService;
16 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
17 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20
21 public class TapiNotificationSerializer implements Serializer<NotificationTapiService> {
22     private static final Logger LOG = LoggerFactory.getLogger(TapiNotificationSerializer.class);
23     private JsonStringConverter<NotificationTapiService> converter;
24
25     @SuppressWarnings("unchecked")
26     @Override
27     public void configure(Map<String, ?> configs, boolean isKey) {
28         LOG.info("Deserializer configuration {}", configs);
29         if (configs.containsKey(ConfigConstants.CONVERTER)
30                 && configs.get(ConfigConstants.CONVERTER) instanceof JsonStringConverter<?>) {
31             converter = (JsonStringConverter<NotificationTapiService>) configs.get(ConfigConstants.CONVERTER);
32         }
33     }
34
35     @Override
36     public byte[] serialize(String topic, NotificationTapiService data) {
37         if (converter == null) {
38             throw new IllegalArgumentException(
39                     "Converter should be configured through configure method of serializer");
40         }
41         if (data == null) {
42             LOG.error("Notification data is empty");
43             return new byte[0];
44         }
45         try {
46             InstanceIdentifier<NotificationTapiService> iid = InstanceIdentifier.builder(NotificationTapiService.class)
47                 .build();
48             String serialized = converter.createJsonStringFromDataObject(iid, data, JSONCodecFactorySupplier.RFC7951);
49             LOG.info("Serialized event {}", serialized);
50             return serialized.getBytes(StandardCharsets.UTF_8);
51         } catch (IOException e) {
52             LOG.error("Event couldnt be serialized", e);
53             return new byte[0];
54         }
55     }
56 }