2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.models.sim.dmaap.provider;
23 import java.util.ArrayList;
24 import java.util.Iterator;
25 import java.util.List;
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;
37 * Data associated with a topic.
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.
44 public class TopicData {
45 private static final Logger logger = LoggerFactory.getLogger(TopicData.class);
48 * Name of the topic with which this data is associated.
50 private final String topicName;
53 * Maps a consumer group name to its associated data.
55 private final Map<String, ConsumerGroupData> group2data = new ConcurrentHashMap<>();
59 * Constructs the object.
61 * @param topicName name of the topic with which this object is associated
63 public TopicData(String topicName) {
64 logger.info("Topic {}: added", topicName);
65 this.topicName = topicName;
69 * Removes idle consumers from the topic. This is typically called once during each
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()) {
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().
84 logger.info("Topic {}: removed consumer group: {}", topicName, ent.getKey());
90 * Reads from a particular consumer group's queue.
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
100 public List<String> read(String consumerGroup, int maxRead, long waitMs) throws InterruptedException {
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.
106 Function<String, ConsumerGroupData> maker = this::makeData;
108 // loop until we get a readable list
114 result = group2data.computeIfAbsent(consumerGroup, maker).read(maxRead, waitMs);
115 } while (result == ConsumerGroupData.UNREADABLE_LIST);
123 * Writes messages to the queues of every consumer group.
125 * @param messages messages to be written to the queues
126 * @return the number of messages enqueued
128 public int write(List<Object> messages) {
129 List<String> list = convertMessagesToStrings(messages);
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).
136 for (ConsumerGroupData data : group2data.values()) {
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.
148 * @param messages objects to be converted
149 * @return a list of message strings
151 protected List<String> convertMessagesToStrings(List<Object> messages) {
152 Coder coder = new StandardCoder();
153 List<String> list = new ArrayList<>(messages.size());
155 for (Object msg : messages) {
156 var str = convertMessageToString(msg, coder);
166 * Converts a message object to a message string.
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
172 protected String convertMessageToString(Object message, Coder coder) {
173 if (message == null) {
177 if (message instanceof String) {
178 return message.toString();
182 return coder.encode(message);
183 } catch (CoderException e) {
184 logger.warn("cannot encode {}", message, e);
189 // this may be overridden by junit tests
192 * Makes data for a consumer group.
194 * @param consumerGroup name of the consumer group to make
195 * @return new consumer group data
197 protected ConsumerGroupData makeData(String consumerGroup) {
198 return new ConsumerGroupData(topicName, consumerGroup);