Split Restconf implementations (draft02 and RFC) - Prepare modules
[netconf.git] / restconf / restconf-nb-bierman02 / src / main / java / org / opendaylight / netconf / sal / streams / listeners / Notificator.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, 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.netconf.sal.streams.listeners;
9
10 import java.util.ArrayList;
11 import java.util.List;
12 import java.util.Map;
13 import java.util.Set;
14 import java.util.concurrent.ConcurrentHashMap;
15 import java.util.concurrent.locks.Lock;
16 import java.util.concurrent.locks.ReentrantLock;
17 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
19 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
20 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
23
24 /**
25  * {@link Notificator} is responsible to create, remove and find
26  * {@link ListenerAdapter} listener.
27  */
28 public class Notificator {
29
30     private static Map<String, ListenerAdapter> dataChangeListener = new ConcurrentHashMap<>();
31     private static Map<String, List<NotificationListenerAdapter>> notificationListenersByStreamName =
32             new ConcurrentHashMap<>();
33
34     private static final Logger LOG = LoggerFactory.getLogger(Notificator.class);
35     private static final Lock LOCK = new ReentrantLock();
36
37     private Notificator() {
38     }
39
40     /**
41      * Returns list of all stream names.
42      */
43     public static Set<String> getStreamNames() {
44         return dataChangeListener.keySet();
45     }
46
47     /**
48      * Gets {@link ListenerAdapter} specified by stream name.
49      *
50      * @param streamName
51      *            The name of the stream.
52      * @return {@link ListenerAdapter} specified by stream name.
53      */
54     public static ListenerAdapter getListenerFor(final String streamName) {
55         return dataChangeListener.get(streamName);
56     }
57
58     /**
59      * Checks if the listener specified by {@link YangInstanceIdentifier} path exist.
60      *
61      * @param streamName    name of the stream
62      * @return True if the listener exist, false otherwise.
63      */
64     public static boolean existListenerFor(final String streamName) {
65         return dataChangeListener.containsKey(streamName);
66     }
67
68     /**
69      * Creates new {@link ListenerAdapter} listener from
70      * {@link YangInstanceIdentifier} path and stream name.
71      *
72      * @param path
73      *            Path to data in data repository.
74      * @param streamName
75      *            The name of the stream.
76      * @param outputType
77      *             Spcific type of output for notifications - XML or JSON
78      * @return New {@link ListenerAdapter} listener from
79      *         {@link YangInstanceIdentifier} path and stream name.
80      */
81     public static ListenerAdapter createListener(final YangInstanceIdentifier path, final String streamName,
82             final NotificationOutputType outputType) {
83         final ListenerAdapter listener = new ListenerAdapter(path, streamName, outputType);
84         try {
85             LOCK.lock();
86             dataChangeListener.put(streamName, listener);
87         } finally {
88             LOCK.unlock();
89         }
90         return listener;
91     }
92
93     /**
94      * Looks for listener determined by {@link YangInstanceIdentifier} path and removes it.
95      * Creates String representation of stream name from URI. Removes slash from URI in start and end position.
96      *
97      * @param uri
98      *            URI for creation stream name.
99      * @return String representation of stream name.
100      */
101     public static String createStreamNameFromUri(final String uri) {
102         if (uri == null) {
103             return null;
104         }
105         String result = uri;
106         if (result.startsWith("/")) {
107             result = result.substring(1);
108         }
109         if (result.endsWith("/")) {
110             result = result.substring(0, result.length() - 1);
111         }
112         return result;
113     }
114
115     /**
116      * Removes all listeners.
117      */
118     @SuppressWarnings("checkstyle:IllegalCatch")
119     public static void removeAllListeners() {
120         for (final ListenerAdapter listener : dataChangeListener.values()) {
121             try {
122                 listener.close();
123             } catch (final Exception e) {
124                 LOG.error("Failed to close listener", e);
125             }
126         }
127         try {
128             LOCK.lock();
129             dataChangeListener = new ConcurrentHashMap<>();
130         } finally {
131             LOCK.unlock();
132         }
133     }
134
135     /**
136      * Delete {@link ListenerAdapter} listener specified in parameter.
137      *
138      * @param <T>
139      *
140      * @param listener
141      *            ListenerAdapter
142      */
143     @SuppressWarnings("checkstyle:IllegalCatch")
144     private static <T extends BaseListenerInterface> void deleteListener(final T listener) {
145         if (listener != null) {
146             try {
147                 listener.close();
148             } catch (final Exception e) {
149                 LOG.error("Failed to close listener", e);
150             }
151             try {
152                 LOCK.lock();
153                 dataChangeListener.remove(listener.getStreamName());
154             } finally {
155                 LOCK.unlock();
156             }
157         }
158     }
159
160     /**
161      * Check if the listener specified by qnames of request exist.
162      *
163      * @param streamName
164      *             name of stream
165      * @return True if the listener exist, false otherwise.
166      */
167     public static boolean existNotificationListenerFor(final String streamName) {
168         return notificationListenersByStreamName.containsKey(streamName);
169     }
170
171     /**
172      * Prepare listener for notification ({@link NotificationDefinition}).
173      *
174      * @param paths
175      *             paths of notifications
176      * @param streamName
177      *             name of stream (generated by paths)
178      * @param outputType
179      *             type of output for onNotification - XML or JSON
180      * @return List of {@link NotificationListenerAdapter} by paths
181      */
182     public static List<NotificationListenerAdapter> createNotificationListener(final List<SchemaPath> paths,
183             final String streamName, final String outputType) {
184         final List<NotificationListenerAdapter> listListeners = new ArrayList<>();
185         for (final SchemaPath path : paths) {
186             final NotificationListenerAdapter listener = new NotificationListenerAdapter(path, streamName, outputType);
187             listListeners.add(listener);
188         }
189         try {
190             LOCK.lock();
191             notificationListenersByStreamName.put(streamName, listListeners);
192         } finally {
193             LOCK.unlock();
194         }
195         return listListeners;
196     }
197
198     public static <T extends BaseListenerInterface> void removeListenerIfNoSubscriberExists(final T listener) {
199         if (!listener.hasSubscribers()) {
200             if (listener instanceof NotificationListenerAdapter) {
201                 deleteNotificationListener(listener);
202             } else {
203                 deleteListener(listener);
204             }
205         }
206     }
207
208     @SuppressWarnings("checkstyle:IllegalCatch")
209     private static <T extends BaseListenerInterface> void deleteNotificationListener(final T listener) {
210         if (listener != null) {
211             try {
212                 listener.close();
213             } catch (final Exception e) {
214                 LOG.error("Failed to close listener", e);
215             }
216             try {
217                 LOCK.lock();
218                 notificationListenersByStreamName.remove(listener.getStreamName());
219             } finally {
220                 LOCK.unlock();
221             }
222         }
223     }
224
225     public static List<NotificationListenerAdapter> getNotificationListenerFor(final String streamName) {
226         return notificationListenersByStreamName.get(streamName);
227     }
228 }