eb998746f9a1f25349f49d097921c008579ffa2a
[transportpce.git] / nbinotifications / src / main / java / org / opendaylight / transportpce / nbinotifications / serialization / NotificationServiceSerializer.java
1 /*
2  * Copyright © 2021 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.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.rev201130.NotificationService;
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 NotificationServiceSerializer implements Serializer<NotificationService> {
22     private static final Logger LOG = LoggerFactory.getLogger(NotificationServiceSerializer.class);
23     private JsonStringConverter<NotificationService> 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<NotificationService>) configs.get(ConfigConstants.CONVERTER);
32         }
33     }
34
35     @Override
36     public byte[] serialize(String topic, NotificationService 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             return new byte[0];
43         }
44         try {
45             InstanceIdentifier<NotificationService> iid = InstanceIdentifier.builder(NotificationService.class).build();
46             String serialized = converter.createJsonStringFromDataObject(iid, data, JSONCodecFactorySupplier.RFC7951);
47             LOG.info("Serialized event {}", serialized);
48             return serialized.getBytes(StandardCharsets.UTF_8);
49         } catch (IOException e) {
50             return new byte[0];
51         }
52     }
53 }