2737f455ba30f95c89d1d249e402ed28a5e9562e
[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 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         }
116         while (result == ConsumerGroupData.UNREADABLE_LIST);
117
118         // @formatter:on
119
120         return result;
121     }
122
123     /**
124      * Writes messages to the queues of every consumer group.
125      *
126      * @param messages messages to be written to the queues
127      * @return the number of messages enqueued
128      */
129     public int write(List<Object> messages) {
130         List<String> list = convertMessagesToStrings(messages);
131
132         /*
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).
136          */
137         for (ConsumerGroupData data : group2data.values()) {
138             data.write(list);
139         }
140
141         return list.size();
142     }
143
144     /**
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.
148      *
149      * @param messages objects to be converted
150      * @return a list of message strings
151      */
152     protected List<String> convertMessagesToStrings(List<Object> messages) {
153         Coder coder = new StandardCoder();
154         List<String> list = new ArrayList<>(messages.size());
155
156         for (Object msg : messages) {
157             String str = convertMessageToString(msg, coder);
158             if (str != null) {
159                 list.add(str);
160             }
161         }
162
163         return list;
164     }
165
166     /**
167      * Converts a message object to a message string.
168      *
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
172      */
173     protected String convertMessageToString(Object message, Coder coder) {
174         if (message == null) {
175             return null;
176         }
177
178         if (message instanceof String) {
179             return message.toString();
180         }
181
182         try {
183             return coder.encode(message);
184         } catch (CoderException e) {
185             logger.warn("cannot encode {}", message, e);
186             return null;
187         }
188     }
189
190     // this may be overridden by junit tests
191
192     /**
193      * Makes data for a consumer group.
194      *
195      * @param consumerGroup name of the consumer group to make
196      * @return new consumer group data
197      */
198     protected ConsumerGroupData makeData(String consumerGroup) {
199         return new ConsumerGroupData(topicName, consumerGroup);
200     }
201 }