Expose streams with all supported encodings
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / streams / 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.nb.rfc8040.streams;
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.nb.rfc8040.streams.RestconfStream.EncodingName;
18 import org.opendaylight.restconf.nb.rfc8040.streams.RestconfStream.Sink;
19 import org.opendaylight.restconf.nb.rfc8040.streams.RestconfStream.Source;
20 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextProvider;
21
22 /**
23  * Abstract base class for functionality shared between {@link NotificationSource} and
24  * {@link DeviceNotificationSource}.
25  */
26 abstract class AbstractNotificationSource extends Source<DOMNotification> {
27     static final class Listener implements DOMNotificationListener {
28         private final Sink<DOMNotification> sink;
29         private final EffectiveModelContextProvider modelContext;
30
31         Listener(final Sink<DOMNotification> sink, final EffectiveModelContextProvider modelContext) {
32             this.sink = requireNonNull(sink);
33             this.modelContext = requireNonNull(modelContext);
34         }
35
36         @Override
37         public void onNotification(final DOMNotification notification) {
38             sink.publish(modelContext.getEffectiveModelContext(), notification,
39                 notification instanceof DOMEvent domEvent ? domEvent.getEventInstant() : Instant.now());
40         }
41     }
42
43     private static final ImmutableMap<EncodingName, NotificationFormatterFactory> ENCODINGS = ImmutableMap.of(
44         EncodingName.RFC8040_JSON, JSONNotificationFormatter.FACTORY,
45         EncodingName.RFC8040_XML, XMLNotificationFormatter.FACTORY);
46
47     AbstractNotificationSource() {
48         super(ENCODINGS);
49     }
50 }