Use BidirectionalTopicClient from policy-common
[policy/models.git] / models-interactions / model-actors / actorServiceProvider / src / main / java / org / onap / policy / controlloop / actorserviceprovider / topic / Forwarder.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.controlloop.actorserviceprovider.topic;
22
23 import java.util.ArrayList;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.function.BiConsumer;
28 import org.onap.policy.common.utils.coder.StandardCoderObject;
29 import org.onap.policy.controlloop.actorserviceprovider.Util;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 /**
34  * Forwarder that selectively forwards message to listeners based on the content of the
35  * message. Each forwarder is associated with a single set of selector keys. Listeners are
36  * then registered with that forwarder for a particular set of values for the given keys.
37  */
38 public class Forwarder {
39     private static final Logger logger = LoggerFactory.getLogger(Forwarder.class);
40
41     /**
42      * Maps a set of field values to one or more listeners.
43      */
44     // @formatter:off
45     private final Map<List<String>, Map<BiConsumer<String, StandardCoderObject>, String>>
46                 values2listeners = new ConcurrentHashMap<>();
47     // @formatter:on
48
49     /**
50      * Keys used to extract the field values from the {@link StandardCoderObject}.
51      */
52     private final List<SelectorKey> keys;
53
54     /**
55      * Constructs the object.
56      *
57      * @param keys keys used to extract the field's value from the
58      *        {@link StandardCoderObject}
59      */
60     public Forwarder(List<SelectorKey> keys) {
61         this.keys = keys;
62     }
63
64     /**
65      * Registers a listener for messages containing the given field values.
66      *
67      * @param values field values of interest, in one-to-one correspondence with the keys
68      * @param listener listener to register
69      */
70     public void register(List<String> values, BiConsumer<String, StandardCoderObject> listener) {
71         if (keys.size() != values.size()) {
72             throw new IllegalArgumentException("key/value mismatch");
73         }
74
75         values2listeners.compute(values, (key, listeners) -> {
76             Map<BiConsumer<String, StandardCoderObject>, String> map = listeners;
77             if (map == null) {
78                 map = new ConcurrentHashMap<>();
79             }
80
81             map.put(listener, "");
82             return map;
83         });
84     }
85
86     /**
87      * Unregisters a listener for messages containing the given field values.
88      *
89      * @param values field values of interest, in one-to-one correspondence with the keys
90      * @param listener listener to unregister
91      */
92     public void unregister(List<String> values, BiConsumer<String, StandardCoderObject> listener) {
93         values2listeners.computeIfPresent(values, (key, listeners) -> {
94             listeners.remove(listener);
95             return (listeners.isEmpty() ? null : listeners);
96         });
97     }
98
99     /**
100      * Processes a message, forwarding it to the appropriate listeners, if any.
101      *
102      * @param textMessage original text message that was received
103      * @param scoMessage decoded text message
104      */
105     public void onMessage(String textMessage, StandardCoderObject scoMessage) {
106         // extract the key values from the message
107         List<String> values = new ArrayList<>(keys.size());
108         for (SelectorKey key : keys) {
109             String value = key.extractField(scoMessage);
110             if (value == null) {
111                 /*
112                  * No value for this field, so this message is not relevant to this
113                  * forwarder.
114                  */
115                 return;
116             }
117
118             values.add(value);
119         }
120
121         // get the listeners for this set of values
122         Map<BiConsumer<String, StandardCoderObject>, String> listeners = values2listeners.get(values);
123         if (listeners == null) {
124             // no listeners for this particular list of values
125             return;
126         }
127
128
129         // forward the message to each listener
130         for (BiConsumer<String, StandardCoderObject> listener : listeners.keySet()) {
131             try {
132                 listener.accept(textMessage, scoMessage);
133             } catch (RuntimeException e) {
134                 logger.warn("exception thrown by listener {}", Util.ident(listener), e);
135             }
136         }
137     }
138 }