c3746df5974f754cda8a1d8fd6ffd803354d977e
[netconf.git] / restconf / sal-rest-connector / 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
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     public static void removeAllListeners() {
119         for (final ListenerAdapter listener : dataChangeListener.values()) {
120             try {
121                 listener.close();
122             } catch (final Exception e) {
123                 LOG.error("Failed to close listener", e);
124             }
125         }
126         try {
127             lock.lock();
128             dataChangeListener = new ConcurrentHashMap<>();
129         } finally {
130             lock.unlock();
131         }
132     }
133
134     /**
135      * Checks if listener has at least one subscriber. In case it doesn't have any, delete listener.
136      *
137      * @param listener
138      *            ListenerAdapter
139      */
140     public static void removeListenerIfNoSubscriberExists(final ListenerAdapter listener) {
141         if (!listener.hasSubscribers()) {
142             deleteListener(listener);
143         }
144     }
145
146     /**
147      * Delete {@link ListenerAdapter} listener specified in parameter.
148      *
149      * @param listener
150      *            ListenerAdapter
151      */
152     private static void deleteListener(final ListenerAdapter listener) {
153         if (listener != null) {
154             try {
155                 listener.close();
156             } catch (final Exception e) {
157                 LOG.error("Failed to close listener", e);
158             }
159             try {
160                 lock.lock();
161                 dataChangeListener.remove(listener.getStreamName());
162             } finally {
163                 lock.unlock();
164             }
165         }
166     }
167
168     /**
169      * Check if the listener specified by qnames of request exist.
170      *
171      * @param streamName
172      *            - name of stream
173      * @return True if the listener exist, false otherwise.
174      */
175     public static boolean existNotificationListenerFor(final String streamName) {
176         return notificationListenersByStreamName.containsKey(streamName);
177
178     }
179
180     /**
181      * Prepare listener for notification ({@link NotificationDefinition})
182      *
183      * @param paths
184      *            - paths of notifications
185      * @param streamName
186      *            - name of stream (generated by paths)
187      * @param outputType
188      *            - type of output for onNotification - XML or JSON
189      * @return List of {@link NotificationListenerAdapter} by paths
190      */
191     public static List<NotificationListenerAdapter> createNotificationListener(final List<SchemaPath> paths,
192             final String streamName, final String outputType) {
193         final List<NotificationListenerAdapter> listListeners = new ArrayList<>();
194         for (final SchemaPath path : paths) {
195             final NotificationListenerAdapter listener = new NotificationListenerAdapter(path, streamName, outputType);
196             listListeners.add(listener);
197         }
198         try {
199             lock.lock();
200             notificationListenersByStreamName.put(streamName, listListeners);
201         } finally {
202             lock.unlock();
203         }
204         return listListeners;
205     }
206
207     public static void removeNotificationListenerIfNoSubscriberExists(final NotificationListenerAdapter listener) {
208         if (!listener.hasSubscribers()) {
209             deleteNotificationListener(listener);
210         }
211     }
212
213     private static void deleteNotificationListener(final NotificationListenerAdapter listener) {
214         if (listener != null) {
215             try {
216                 listener.close();
217             } catch (final Exception e) {
218                 LOG.error("Failed to close listener", e);
219             }
220             try {
221                 lock.lock();
222                 notificationListenersByStreamName.remove(listener.getStreamName());
223             } finally {
224                 lock.unlock();
225             }
226         }
227     }
228
229     public static List<NotificationListenerAdapter> getNotificationListenerFor(final String streamName) {
230         return notificationListenersByStreamName.get(streamName);
231     }
232 }