8e5cf24ccbe1ef14205095e0279b256ab3404f4e
[policy/models.git] / models-sim / models-sim-dmaap / src / main / java / org / onap / policy / models / sim / dmaap / provider / TopicData.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Models
4  * ================================================================================
5  * Copyright (C) 2019, 2021 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.models.sim.dmaap.provider;
22
23 import java.util.ArrayList;
24 import java.util.Iterator;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Map.Entry;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.function.Function;
30 import org.onap.policy.common.utils.coder.Coder;
31 import org.onap.policy.common.utils.coder.CoderException;
32 import org.onap.policy.common.utils.coder.StandardCoder;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 /**
37  * Data associated with a topic.
38  *
39  * <p/>
40  * Note: for ease of implementation, this adds a topic when a consumer polls it rather
41  * than when a publisher writes to it. This is the opposite of how the real DMaaP works.
42  * As a result, this will never return a topic-not-found message to the consumer.
43  */
44 public class TopicData {
45     private static final Logger logger = LoggerFactory.getLogger(TopicData.class);
46
47     /**
48      * Name of the topic with which this data is associated.
49      */
50     private final String topicName;
51
52     /**
53      * Maps a consumer group name to its associated data.
54      */
55     private final Map<String, ConsumerGroupData> group2data = new ConcurrentHashMap<>();
56
57
58     /**
59      * Constructs the object.
60      *
61      * @param topicName name of the topic with which this object is associated
62      */
63     public TopicData(String topicName) {
64         logger.info("Topic {}: added", topicName);
65         this.topicName = topicName;
66     }
67
68     /**
69      * Removes idle consumers from the topic. This is typically called once during each
70      * sweep cycle.
71      */
72     public void removeIdleConsumers() {
73         Iterator<Entry<String, ConsumerGroupData>> iter = group2data.entrySet().iterator();
74         while (iter.hasNext()) {
75             Entry<String, ConsumerGroupData> ent = iter.next();
76             if (ent.getValue().shouldRemove()) {
77                 /*
78                  * We want the minimum amount of time to elapse between invoking
79                  * shouldRemove() and iter.remove(), thus all other statements (e.g.,
80                  * logging) should be done AFTER iter.remove().
81                  */
82                 iter.remove();
83
84                 logger.info("Topic {}: removed consumer group: {}", topicName, ent.getKey());
85             }
86         }
87     }
88
89     /**
90      * Reads from a particular consumer group's queue.
91      *
92      * @param consumerGroup name of the consumer group from which to read
93      * @param maxRead maximum number of messages to read
94      * @param waitMs time to wait, in milliseconds, if the queue is currently empty
95      * @return a list of messages read from the queue, empty if no messages became
96      *         available before the wait time elapsed
97      * @throws InterruptedException if this thread was interrupted while waiting for the
98      *         first message
99      */
100     public List<String> read(String consumerGroup, int maxRead, long waitMs) throws InterruptedException {
101         /*
102          * It's possible that this thread may spin several times while waiting for
103          * removeIdleConsumers() to complete its call to iter.remove(), thus we create
104          * this closure once, rather than each time through the loop.
105          */
106         Function<String, ConsumerGroupData> maker = this::makeData;
107
108         // loop until we get a readable list
109         List<String> result;
110
111         // @formatter:off
112
113         do {
114             result = group2data.computeIfAbsent(consumerGroup, maker).read(maxRead, waitMs);
115         } while (result == ConsumerGroupData.UNREADABLE_LIST);
116
117         // @formatter:on
118
119         return result;
120     }
121
122     /**
123      * Writes messages to the queues of every consumer group.
124      *
125      * @param messages messages to be written to the queues
126      * @return the number of messages enqueued
127      */
128     public int write(List<Object> messages) {
129         List<String> list = convertMessagesToStrings(messages);
130
131         /*
132          * We don't care if a consumer group is deleted from the map while we're adding
133          * messages to it, as those messages will simply be ignored (and discarded by the
134          * garbage collector).
135          */
136         for (ConsumerGroupData data : group2data.values()) {
137             data.write(list);
138         }
139
140         return list.size();
141     }
142
143     /**
144      * Converts a list of message objects to a list of message strings. If a message
145      * cannot be converted for some reason, then it is not added to the result list, thus
146      * the result list may be shorted than the original input list.
147      *
148      * @param messages objects to be converted
149      * @return a list of message strings
150      */
151     protected List<String> convertMessagesToStrings(List<Object> messages) {
152         Coder coder = new StandardCoder();
153         List<String> list = new ArrayList<>(messages.size());
154
155         for (Object msg : messages) {
156             var str = convertMessageToString(msg, coder);
157             if (str != null) {
158                 list.add(str);
159             }
160         }
161
162         return list;
163     }
164
165     /**
166      * Converts a message object to a message string.
167      *
168      * @param message message to be converted
169      * @param coder used to encode the message as a string
170      * @return the message string, or {@code null} if it cannot be converted
171      */
172     protected String convertMessageToString(Object message, Coder coder) {
173         if (message == null) {
174             return null;
175         }
176
177         if (message instanceof String) {
178             return message.toString();
179         }
180
181         try {
182             return coder.encode(message);
183         } catch (CoderException e) {
184             logger.warn("cannot encode {}", message, e);
185             return null;
186         }
187     }
188
189     // this may be overridden by junit tests
190
191     /**
192      * Makes data for a consumer group.
193      *
194      * @param consumerGroup name of the consumer group to make
195      * @return new consumer group data
196      */
197     protected ConsumerGroupData makeData(String consumerGroup) {
198         return new ConsumerGroupData(topicName, consumerGroup);
199     }
200 }