Introduce restconf.server.{api,spi,mdsal}
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / server / mdsal / streams / notif / AbstractNotificationSource.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.server.mdsal.streams.notif;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.collect.ImmutableMap;
13 import java.time.Instant;
14 import org.opendaylight.mdsal.dom.api.DOMEvent;
15 import org.opendaylight.mdsal.dom.api.DOMNotification;
16 import org.opendaylight.mdsal.dom.api.DOMNotificationListener;
17 import org.opendaylight.restconf.server.spi.RestconfStream.EncodingName;
18 import org.opendaylight.restconf.server.spi.RestconfStream.Sink;
19 import org.opendaylight.restconf.server.spi.RestconfStream.Source;
20 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextProvider;
21
22 /**
23  * Abstract base class for functionality shared between {@link DOMNotification}-based sources.
24  */
25 public abstract class AbstractNotificationSource extends Source<DOMNotification> {
26     protected static final class Listener implements DOMNotificationListener {
27         private final Sink<DOMNotification> sink;
28         private final EffectiveModelContextProvider modelContext;
29
30         public Listener(final Sink<DOMNotification> sink, final EffectiveModelContextProvider modelContext) {
31             this.sink = requireNonNull(sink);
32             this.modelContext = requireNonNull(modelContext);
33         }
34
35         @Override
36         public void onNotification(final DOMNotification notification) {
37             sink.publish(modelContext.getEffectiveModelContext(), notification,
38                 notification instanceof DOMEvent domEvent ? domEvent.getEventInstant() : Instant.now());
39         }
40     }
41
42     private static final ImmutableMap<EncodingName, NotificationFormatterFactory> ENCODINGS = ImmutableMap.of(
43         EncodingName.RFC8040_JSON, JSONNotificationFormatter.FACTORY,
44         EncodingName.RFC8040_XML, XMLNotificationFormatter.FACTORY);
45
46     protected AbstractNotificationSource() {
47         super(ENCODINGS);
48     }
49 }