2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019 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);
116 while (result == ConsumerGroupData.UNREADABLE_LIST);
124 * Writes messages to the queues of every consumer group.
126 * @param messages messages to be written to the queues
127 * @return the number of messages enqueued
129 public int write(List<Object> messages) {
130 List<String> list = convertMessagesToStrings(messages);
133 * We don't care if a consumer group is deleted from the map while we're adding
134 * messages to it, as those messages will simply be ignored (and discarded by the
135 * garbage collector).
137 for (ConsumerGroupData data : group2data.values()) {
145 * Converts a list of message objects to a list of message strings. If a message
146 * cannot be converted for some reason, then it is not added to the result list, thus
147 * the result list may be shorted than the original input list.
149 * @param messages objects to be converted
150 * @return a list of message strings
152 protected List<String> convertMessagesToStrings(List<Object> messages) {
153 Coder coder = new StandardCoder();
154 List<String> list = new ArrayList<>(messages.size());
156 for (Object msg : messages) {
157 String str = convertMessageToString(msg, coder);
167 * Converts a message object to a message string.
169 * @param message message to be converted
170 * @param coder used to encode the message as a string
171 * @return the message string, or {@code null} if it cannot be converted
173 protected String convertMessageToString(Object message, Coder coder) {
174 if (message == null) {
178 if (message instanceof String) {
179 return message.toString();
183 return coder.encode(message);
184 } catch (CoderException e) {
185 logger.warn("cannot encode {}", message, e);
190 // this may be overridden by junit tests
193 * Makes data for a consumer group.
195 * @param consumerGroup name of the consumer group to make
196 * @return new consumer group data
198 protected ConsumerGroupData makeData(String consumerGroup) {
199 return new ConsumerGroupData(topicName, consumerGroup);