2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2018-2019 Samsung Electronics Co., Ltd.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.common.endpoints.event.comm.bus.internal;
24 import java.io.IOException;
25 import java.net.MalformedURLException;
26 import java.util.UUID;
28 import org.onap.policy.common.endpoints.event.comm.FilterableTopicSource;
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.event.comm.bus.internal.BusConsumer.FilterableBusConsumer;
32 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
33 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
34 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
35 import org.onap.policy.common.utils.network.NetworkUtil;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
40 * This topic source implementation specializes in reading messages over a bus topic source and
41 * notifying its listeners.
43 public abstract class SingleThreadedBusTopicSource extends BusTopicBase
44 implements Runnable, BusTopicSource, FilterableTopicSource {
47 * Not to be converted to PolicyLogger. This will contain all instract /out traffic and only
48 * that in a single file in a concise format.
50 private static Logger logger = LoggerFactory.getLogger(SingleThreadedBusTopicSource.class);
55 protected final String consumerGroup;
58 * Bus consumer instance.
60 protected final String consumerInstance;
65 protected final int fetchTimeout;
70 protected final int fetchLimit;
73 * Message Bus Consumer.
75 protected BusConsumer consumer;
78 * Independent thread reading message over my topic.
80 protected Thread busPollerThread;
86 * @param busTopicParams topic parameters
88 * @throws IllegalArgumentException An invalid parameter passed in
90 public SingleThreadedBusTopicSource(BusTopicParams busTopicParams) {
92 super(busTopicParams);
94 if (busTopicParams.isConsumerGroupInvalid()) {
95 this.consumerGroup = UUID.randomUUID().toString();
97 this.consumerGroup = busTopicParams.getConsumerGroup();
100 if (busTopicParams.isConsumerInstanceInvalid()) {
101 this.consumerInstance = NetworkUtil.getHostname();
103 this.consumerInstance = busTopicParams.getConsumerInstance();
106 if (busTopicParams.getFetchTimeout() <= 0) {
107 this.fetchTimeout = PolicyEndPointProperties.NO_TIMEOUT_MS_FETCH;
109 this.fetchTimeout = busTopicParams.getFetchTimeout();
112 if (busTopicParams.getFetchLimit() <= 0) {
113 this.fetchLimit = PolicyEndPointProperties.NO_LIMIT_FETCH;
115 this.fetchLimit = busTopicParams.getFetchLimit();
121 * Initialize the Bus client.
123 public abstract void init() throws MalformedURLException;
126 public void register(TopicListener topicListener) {
128 super.register(topicListener);
131 if (!alive && !locked) {
134 logger.info("{}: register: start not attempted", this);
136 } catch (Exception e) {
137 logger.warn("{}: cannot start after registration of because of: {}", this, topicListener, e);
142 public void unregister(TopicListener topicListener) {
144 synchronized (this) {
145 super.unregister(topicListener);
146 stop = this.topicListeners.isEmpty();
155 public boolean start() {
156 logger.info("{}: starting", this);
158 synchronized (this) {
165 throw new IllegalStateException(this + " is locked.");
168 if (this.busPollerThread == null || !this.busPollerThread.isAlive() || this.consumer == null) {
173 this.busPollerThread = makePollerThread();
174 this.busPollerThread.setName(this.getTopicCommInfrastructure() + "-source-" + this.getTopic());
175 busPollerThread.start();
177 } catch (Exception e) {
178 throw new IllegalStateException(this + ": cannot start", e);
187 * Makes a new thread to be used for polling.
189 * @return a new Thread
191 protected Thread makePollerThread() {
192 return new Thread(this);
196 public boolean stop() {
197 logger.info("{}: stopping", this);
199 synchronized (this) {
200 BusConsumer consumerCopy = this.consumer;
203 this.consumer = null;
205 if (consumerCopy != null) {
207 consumerCopy.close();
208 } catch (Exception e) {
209 logger.warn("{}: stop failed because of {}", this, e.getMessage(), e);
220 * Run thread method for the Bus Reader.
227 } catch (IOException | RuntimeException e) {
228 logger.error("{}: cannot fetch because of ", this, e.getMessage(), e);
232 logger.info("{}: exiting thread", this);
235 private void fetchAllMessages() throws IOException {
236 for (String event : this.consumer.fetch()) {
237 synchronized (this) {
238 this.recentEvents.add(event);
241 NetLoggerUtil.log(EventType.IN, this.getTopicCommInfrastructure(), this.topic, event);
252 public boolean offer(String event) {
254 throw new IllegalStateException(this + " is not alive.");
257 synchronized (this) {
258 this.recentEvents.add(event);
261 NetLoggerUtil.log(EventType.IN, this.getTopicCommInfrastructure(), this.topic, event);
263 return broadcast(event);
268 public void setFilter(String filter) {
269 if (consumer instanceof FilterableBusConsumer) {
270 ((FilterableBusConsumer) consumer).setFilter(filter);
273 throw new UnsupportedOperationException("no server-side filtering for topic " + topic);
278 public String toString() {
279 return "SingleThreadedBusTopicSource [consumerGroup=" + consumerGroup + ", consumerInstance=" + consumerInstance
280 + ", fetchTimeout=" + fetchTimeout + ", fetchLimit=" + fetchLimit + ", consumer=" + this.consumer
281 + ", alive=" + alive + ", locked=" + locked + ", uebThread=" + busPollerThread + ", topicListeners="
282 + topicListeners.size() + ", toString()=" + super.toString() + "]";
286 public String getConsumerGroup() {
287 return consumerGroup;
291 public String getConsumerInstance() {
292 return consumerInstance;
296 public void shutdown() {
298 this.topicListeners.clear();
302 public int getFetchTimeout() {
307 public int getFetchLimit() {