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;
27 import org.onap.policy.common.endpoints.event.comm.FilterableTopicSource;
28 import org.onap.policy.common.endpoints.event.comm.TopicListener;
29 import org.onap.policy.common.endpoints.event.comm.bus.BusTopicSource;
30 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusConsumer.FilterableBusConsumer;
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, FilterableTopicSource {
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);
54 protected final String consumerGroup;
57 * Bus consumer instance.
59 protected final String consumerInstance;
64 protected final int fetchTimeout;
69 protected final int fetchLimit;
72 * Message Bus Consumer.
74 protected BusConsumer consumer;
77 * Independent thread reading message over my topic.
79 protected Thread busPollerThread;
85 * @param busTopicParams topic parameters
87 * @throws IllegalArgumentException An invalid parameter passed in
89 public SingleThreadedBusTopicSource(BusTopicParams busTopicParams) {
91 super(busTopicParams);
93 if (busTopicParams.isConsumerGroupInvalid()) {
94 this.consumerGroup = UUID.randomUUID().toString();
96 this.consumerGroup = busTopicParams.getConsumerGroup();
99 if (busTopicParams.isConsumerInstanceInvalid()) {
100 this.consumerInstance = NetworkUtil.getHostname();
102 this.consumerInstance = busTopicParams.getConsumerInstance();
105 if (busTopicParams.getFetchTimeout() <= 0) {
106 this.fetchTimeout = PolicyEndPointProperties.NO_TIMEOUT_MS_FETCH;
108 this.fetchTimeout = busTopicParams.getFetchTimeout();
111 if (busTopicParams.getFetchLimit() <= 0) {
112 this.fetchLimit = PolicyEndPointProperties.NO_LIMIT_FETCH;
114 this.fetchLimit = busTopicParams.getFetchLimit();
120 * Initialize the Bus client.
122 public abstract void init() throws MalformedURLException;
125 public void register(TopicListener topicListener) {
127 super.register(topicListener);
130 if (!alive && !locked) {
133 logger.info("{}: register: start not attempted", this);
135 } catch (Exception e) {
136 logger.warn("{}: cannot start after registration of because of: {}", this, topicListener, e);
141 public void unregister(TopicListener topicListener) {
143 synchronized (this) {
144 super.unregister(topicListener);
145 stop = this.topicListeners.isEmpty();
154 public boolean start() {
155 logger.info("{}: starting", this);
157 synchronized (this) {
164 throw new IllegalStateException(this + " is locked.");
167 if (this.busPollerThread == null || !this.busPollerThread.isAlive() || this.consumer == null) {
172 this.busPollerThread = makePollerThread();
173 this.busPollerThread.setName(this.getTopicCommInfrastructure() + "-source-" + this.getTopic());
174 busPollerThread.start();
176 } catch (Exception e) {
177 throw new IllegalStateException(this + ": cannot start", e);
186 * Makes a new thread to be used for polling.
188 * @return a new Thread
190 protected Thread makePollerThread() {
191 return new Thread(this);
195 public boolean stop() {
196 logger.info("{}: stopping", this);
198 synchronized (this) {
199 BusConsumer consumerCopy = this.consumer;
202 this.consumer = null;
204 if (consumerCopy != null) {
206 consumerCopy.close();
207 } catch (Exception e) {
208 logger.warn("{}: stop failed because of {}", this, e.getMessage(), e);
219 * Run thread method for the Bus Reader.
226 } catch (IOException | RuntimeException e) {
227 logger.error("{}: cannot fetch", this, e);
231 logger.info("{}: exiting thread", this);
234 private void fetchAllMessages() throws IOException {
235 for (String event : this.consumer.fetch()) {
236 synchronized (this) {
237 this.recentEvents.add(event);
240 NetLoggerUtil.log(EventType.IN, this.getTopicCommInfrastructure(), this.topic, event);
251 public boolean offer(String event) {
253 throw new IllegalStateException(this + " is not alive.");
256 synchronized (this) {
257 this.recentEvents.add(event);
260 NetLoggerUtil.log(EventType.IN, this.getTopicCommInfrastructure(), this.topic, event);
262 return broadcast(event);
267 public void setFilter(String filter) {
268 if (consumer instanceof FilterableBusConsumer) {
269 ((FilterableBusConsumer) consumer).setFilter(filter);
272 throw new UnsupportedOperationException("no server-side filtering for topic " + topic);
277 public String toString() {
278 return "SingleThreadedBusTopicSource [consumerGroup=" + consumerGroup + ", consumerInstance=" + consumerInstance
279 + ", fetchTimeout=" + fetchTimeout + ", fetchLimit=" + fetchLimit + ", consumer=" + this.consumer
280 + ", alive=" + alive + ", locked=" + locked + ", uebThread=" + busPollerThread + ", topicListeners="
281 + topicListeners.size() + ", toString()=" + super.toString() + "]";
285 public String getConsumerGroup() {
286 return consumerGroup;
290 public String getConsumerInstance() {
291 return consumerInstance;
295 public void shutdown() {
297 this.topicListeners.clear();
301 public int getFetchTimeout() {
306 public int getFetchLimit() {