blob: df7bf9b31eec17c51b78a68c815f9f268ef1b488 [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;
20import java.util.function.Consumer;
21
22import org.onosproject.store.service.AsyncAtomicValue;
23import org.onosproject.store.service.AtomicValueEventListener;
24import org.onosproject.store.service.DistributedPrimitive;
25import org.onosproject.store.service.Topic;
26
27import com.google.common.collect.Maps;
28
29/**
30 * Default implementation of {@link Topic}.
31 *
32 * @param <T> topic message type.
33 */
34public class DefaultDistributedTopic<T> implements Topic<T> {
35
36 private final AsyncAtomicValue<T> atomicValue;
37 private final Map<Consumer<T>, AtomicValueEventListener<T>> callbacks = Maps.newIdentityHashMap();
38
39 DefaultDistributedTopic(AsyncAtomicValue<T> atomicValue) {
40 this.atomicValue = atomicValue;
41 }
42
43 @Override
44 public String name() {
45 return atomicValue.name();
46 }
47
48 @Override
49 public Type primitiveType() {
50 return DistributedPrimitive.Type.TOPIC;
51 }
52
53 @Override
54 public CompletableFuture<Void> destroy() {
55 return atomicValue.destroy();
56 }
57
58 @Override
59 public CompletableFuture<Void> publish(T message) {
60 return atomicValue.set(message);
61 }
62
63 @Override
64 public CompletableFuture<Void> subscribe(Consumer<T> callback) {
65 AtomicValueEventListener<T> valueListener = event -> callback.accept(event.newValue());
66 if (callbacks.putIfAbsent(callback, valueListener) == null) {
67 return atomicValue.addListener(valueListener);
68 }
69 return CompletableFuture.completedFuture(null);
70 }
71
72 @Override
73 public CompletableFuture<Void> unsubscribe(Consumer<T> callback) {
74 AtomicValueEventListener<T> valueListener = callbacks.remove(callback);
75 if (valueListener != null) {
76 return atomicValue.removeListener(valueListener);
77 }
78 return CompletableFuture.completedFuture(null);
79 }
80}