2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2018-2019 Samsung Electronics Co., Ltd.
7 * Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.common.endpoints.event.comm.bus.internal;
25 import java.io.IOException;
26 import java.net.MalformedURLException;
27 import java.util.UUID;
29 import org.onap.policy.common.endpoints.event.comm.TopicListener;
30 import org.onap.policy.common.endpoints.event.comm.bus.BusTopicSource;
31 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
32 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
33 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
34 import org.onap.policy.common.utils.network.NetworkUtil;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
39 * This topic source implementation specializes in reading messages over a bus topic source and
40 * notifying its listeners.
42 public abstract class SingleThreadedBusTopicSource extends BusTopicBase
43 implements Runnable, BusTopicSource {
46 * Not to be converted to PolicyLogger. This will contain all instract /out traffic and only
47 * that in a single file in a concise format.
49 private static Logger logger = LoggerFactory.getLogger(SingleThreadedBusTopicSource.class);
55 protected final String consumerGroup;
58 * Bus consumer instance.
61 protected final String consumerInstance;
67 protected final int fetchTimeout;
73 protected final int fetchLimit;
76 * Message Bus Consumer.
78 protected BusConsumer consumer;
81 * Independent thread reading message over my topic.
83 protected Thread busPollerThread;
89 * @param busTopicParams topic parameters
91 * @throws IllegalArgumentException An invalid parameter passed in
93 protected SingleThreadedBusTopicSource(BusTopicParams busTopicParams) {
95 super(busTopicParams);
97 if (busTopicParams.isConsumerGroupInvalid() && busTopicParams.isConsumerInstanceInvalid()) {
98 this.consumerGroup = UUID.randomUUID().toString();
99 this.consumerInstance = NetworkUtil.getHostname();
101 } else if (busTopicParams.isConsumerGroupInvalid()) {
102 this.consumerGroup = UUID.randomUUID().toString();
103 this.consumerInstance = busTopicParams.getConsumerInstance();
105 } else if (busTopicParams.isConsumerInstanceInvalid()) {
106 this.consumerGroup = busTopicParams.getConsumerGroup();
107 this.consumerInstance = UUID.randomUUID().toString();
110 this.consumerGroup = busTopicParams.getConsumerGroup();
111 this.consumerInstance = busTopicParams.getConsumerInstance();
114 if (busTopicParams.getFetchTimeout() <= 0) {
115 this.fetchTimeout = PolicyEndPointProperties.NO_TIMEOUT_MS_FETCH;
117 this.fetchTimeout = busTopicParams.getFetchTimeout();
120 if (busTopicParams.getFetchLimit() <= 0) {
121 this.fetchLimit = PolicyEndPointProperties.NO_LIMIT_FETCH;
123 this.fetchLimit = busTopicParams.getFetchLimit();
129 * Initialize the Bus client.
131 public abstract void init() throws MalformedURLException;
134 public void register(TopicListener topicListener) {
136 super.register(topicListener);
139 if (!alive && !locked) {
142 logger.info("{}: register: start not attempted", this);
144 } catch (Exception e) {
145 logger.warn("{}: cannot start after registration of because of: {}", this, topicListener, e);
150 public void unregister(TopicListener topicListener) {
152 synchronized (this) {
153 super.unregister(topicListener);
154 stop = this.topicListeners.isEmpty();
163 public boolean start() {
164 logger.info("{}: starting", this);
166 synchronized (this) {
173 throw new IllegalStateException(this + " is locked.");
176 if (this.busPollerThread == null || !this.busPollerThread.isAlive() || this.consumer == null) {
181 this.busPollerThread = makePollerThread();
182 this.busPollerThread.setName(this.getTopicCommInfrastructure() + "-source-" + this.getTopic());
183 busPollerThread.start();
185 } catch (Exception e) {
186 throw new IllegalStateException(this + ": cannot start", e);
195 * Makes a new thread to be used for polling.
197 * @return a new Thread
199 protected Thread makePollerThread() {
200 return new Thread(this);
204 public boolean stop() {
205 logger.info("{}: stopping", this);
207 synchronized (this) {
208 BusConsumer consumerCopy = this.consumer;
211 this.consumer = null;
213 if (consumerCopy != null) {
215 consumerCopy.close();
216 } catch (Exception e) {
217 logger.warn("{}: stop failed because of {}", this, e.getMessage(), e);
228 * Run thread method for the Bus Reader.
235 } catch (IOException | RuntimeException e) {
236 logger.error("{}: cannot fetch", this, e);
240 logger.info("{}: exiting thread", this);
243 private void fetchAllMessages() throws IOException {
244 for (String event : this.consumer.fetch()) {
245 synchronized (this) {
246 this.recentEvents.add(event);
249 NetLoggerUtil.log(EventType.IN, this.getTopicCommInfrastructure(), this.topic, event);
260 public boolean offer(String event) {
262 throw new IllegalStateException(this + " is not alive.");
265 synchronized (this) {
266 this.recentEvents.add(event);
269 NetLoggerUtil.log(EventType.IN, this.getTopicCommInfrastructure(), this.topic, event);
271 return broadcast(event);
275 public String toString() {
276 return "SingleThreadedBusTopicSource [consumerGroup=" + consumerGroup + ", consumerInstance=" + consumerInstance
277 + ", fetchTimeout=" + fetchTimeout + ", fetchLimit=" + fetchLimit + ", consumer=" + this.consumer
278 + ", alive=" + alive + ", locked=" + locked + ", uebThread=" + busPollerThread + ", topicListeners="
279 + topicListeners.size() + ", toString()=" + super.toString() + "]";
283 public void shutdown() {
285 this.topicListeners.clear();