e8af6c23b3b79729789f467a26b4ff50c6abea21
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / streams / AbstractNotificationStream.java
1 /*
2  * Copyright (c) 2022 PANTHEON.tech, s.r.o. 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.restconf.nb.rfc8040.streams;
9
10 import java.time.Instant;
11 import org.eclipse.jdt.annotation.NonNull;
12 import org.opendaylight.mdsal.dom.api.DOMEvent;
13 import org.opendaylight.mdsal.dom.api.DOMNotification;
14 import org.opendaylight.mdsal.dom.api.DOMNotificationListener;
15 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev231103.NotificationOutputTypeGrouping.NotificationOutputType;
16 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
19
20 /**
21  * Abstract base class for functionality shared between {@link NotificationStream} and
22  * {@link DeviceNotificationStream}.
23  */
24 abstract class AbstractNotificationStream extends RestconfStream<DOMNotification> implements DOMNotificationListener {
25     private static final Logger LOG = LoggerFactory.getLogger(AbstractNotificationStream.class);
26
27     AbstractNotificationStream(final ListenersBroker listenersBroker, final String name,
28             final NotificationOutputType outputType) {
29         super(listenersBroker, name, outputType, switch (outputType) {
30             case JSON -> JSONNotificationFormatter.FACTORY;
31             case XML -> XMLNotificationFormatter.FACTORY;
32         });
33     }
34
35     @Override
36     @SuppressWarnings("checkstyle:IllegalCatch")
37     public final void onNotification(final DOMNotification notification) {
38         final var eventInstant = notification instanceof DOMEvent domEvent ? domEvent.getEventInstant() : Instant.now();
39         final String data;
40         try {
41             data = formatter().eventData(effectiveModel(), notification, eventInstant);
42         } catch (Exception e) {
43             LOG.error("Failed to process notification {}", notification, e);
44             return;
45         }
46         if (data != null) {
47             post(data);
48         }
49     }
50
51     abstract @NonNull EffectiveModelContext effectiveModel();
52 }