blob: d5399923685b90e9fca152c32813bcd533252c1d [file] [log] [blame]
Madan Jampani13f65152016-08-17 13:14:53 -07001/*
2 * Copyright 2016-present Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.store.primitives.impl;
17
18import java.util.Map;
19import java.util.concurrent.CompletableFuture;
Madan Jampani03fb8b22016-08-22 09:08:42 -070020import java.util.concurrent.Executor;
Madan Jampani13f65152016-08-17 13:14:53 -070021import java.util.function.Consumer;
22
23import org.onosproject.store.service.AsyncAtomicValue;
24import org.onosproject.store.service.AtomicValueEventListener;
25import org.onosproject.store.service.DistributedPrimitive;
26import org.onosproject.store.service.Topic;
27
28import com.google.common.collect.Maps;
29
30/**
31 * Default implementation of {@link Topic}.
32 *
33 * @param <T> topic message type.
34 */
35public class DefaultDistributedTopic<T> implements Topic<T> {
36
37 private final AsyncAtomicValue<T> atomicValue;
38 private final Map<Consumer<T>, AtomicValueEventListener<T>> callbacks = Maps.newIdentityHashMap();
39
40 DefaultDistributedTopic(AsyncAtomicValue<T> atomicValue) {
41 this.atomicValue = atomicValue;
42 }
43
44 @Override
45 public String name() {
46 return atomicValue.name();
47 }
48
49 @Override
50 public Type primitiveType() {
51 return DistributedPrimitive.Type.TOPIC;
52 }
53
54 @Override
55 public CompletableFuture<Void> destroy() {
56 return atomicValue.destroy();
57 }
58
59 @Override
60 public CompletableFuture<Void> publish(T message) {
61 return atomicValue.set(message);
62 }
63
64 @Override
Madan Jampani03fb8b22016-08-22 09:08:42 -070065 public CompletableFuture<Void> subscribe(Consumer<T> callback, Executor executor) {
66 AtomicValueEventListener<T> valueListener =
67 event -> executor.execute(() -> callback.accept(event.newValue()));
Madan Jampani13f65152016-08-17 13:14:53 -070068 if (callbacks.putIfAbsent(callback, valueListener) == null) {
69 return atomicValue.addListener(valueListener);
70 }
71 return CompletableFuture.completedFuture(null);
72 }
73
74 @Override
75 public CompletableFuture<Void> unsubscribe(Consumer<T> callback) {
76 AtomicValueEventListener<T> valueListener = callbacks.remove(callback);
77 if (valueListener != null) {
78 return atomicValue.removeListener(valueListener);
79 }
80 return CompletableFuture.completedFuture(null);
81 }
82}