2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2018 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.net.MalformedURLException;
25 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.utils.network.NetworkUtil;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
36 * This topic source implementation specializes in reading messages over a bus topic source and
37 * notifying its listeners.
39 public abstract class SingleThreadedBusTopicSource extends BusTopicBase
40 implements Runnable, BusTopicSource, FilterableTopicSource {
43 * Not to be converted to PolicyLogger. This will contain all instract /out traffic and only
44 * that in a single file in a concise format.
46 private static Logger logger = LoggerFactory.getLogger(InlineBusTopicSink.class);
47 private static final Logger netLogger = LoggerFactory.getLogger(NETWORK_LOGGER);
52 protected final String consumerGroup;
55 * Bus consumer instance.
57 protected final String consumerInstance;
62 protected final int fetchTimeout;
67 protected final int fetchLimit;
70 * Message Bus Consumer.
72 protected BusConsumer consumer;
75 * Independent thread reading message over my topic.
77 protected Thread busPollerThread;
83 * @param busTopicParams topic parameters
85 * @throws IllegalArgumentException An invalid parameter passed in
87 public SingleThreadedBusTopicSource(BusTopicParams busTopicParams) {
89 super(busTopicParams);
91 if (busTopicParams.isConsumerGroupInvalid()) {
92 this.consumerGroup = UUID.randomUUID().toString();
94 this.consumerGroup = busTopicParams.getConsumerGroup();
97 if (busTopicParams.isConsumerInstanceInvalid()) {
98 this.consumerInstance = NetworkUtil.getHostname();
100 this.consumerInstance = busTopicParams.getConsumerInstance();
103 if (busTopicParams.getFetchTimeout() <= 0) {
104 this.fetchTimeout = NO_TIMEOUT_MS_FETCH;
106 this.fetchTimeout = busTopicParams.getFetchTimeout();
109 if (busTopicParams.getFetchLimit() <= 0) {
110 this.fetchLimit = NO_LIMIT_FETCH;
112 this.fetchLimit = busTopicParams.getFetchLimit();
118 * Initialize the Bus client.
120 public abstract void init() throws MalformedURLException;
123 public void register(TopicListener topicListener) {
125 super.register(topicListener);
128 if (!alive && !locked) {
131 logger.info("{}: register: start not attempted", this);
133 } catch (Exception e) {
134 logger.warn("{}: cannot start after registration of because of: {}", this, topicListener, e.getMessage(),
140 public void unregister(TopicListener topicListener) {
142 synchronized (this) {
143 super.unregister(topicListener);
144 stop = this.topicListeners.isEmpty();
153 public boolean start() {
154 logger.info("{}: starting", this);
156 synchronized (this) {
163 throw new IllegalStateException(this + " is locked.");
166 if (this.busPollerThread == null || !this.busPollerThread.isAlive() || this.consumer == null) {
171 this.busPollerThread = makePollerThread();
172 this.busPollerThread.setName(this.getTopicCommInfrastructure() + "-source-" + this.getTopic());
173 busPollerThread.start();
174 } catch (Exception e) {
175 logger.warn("{}: cannot start because of {}", this, e.getMessage(), e);
176 throw new IllegalStateException(e);
185 * Makes a new thread to be used for polling.
187 * @return a new Thread
189 protected Thread makePollerThread() {
190 return new Thread(this);
194 public boolean stop() {
195 logger.info("{}: stopping", this);
197 synchronized (this) {
198 BusConsumer consumerCopy = this.consumer;
201 this.consumer = null;
203 if (consumerCopy != null) {
205 consumerCopy.close();
206 } catch (Exception e) {
207 logger.warn("{}: stop failed because of {}", this, e.getMessage(), e);
218 * Run thread method for the Bus Reader.
224 for (String event : this.consumer.fetch()) {
225 synchronized (this) {
226 this.recentEvents.add(event);
229 netLogger.info("[IN|{}|{}]{}{}", this.getTopicCommInfrastructure(), this.topic,
230 System.lineSeparator(), event);
238 } catch (Exception e) {
239 logger.error("{}: cannot fetch because of ", this, e.getMessage(), e);
243 logger.info("{}: exiting thread", this);
247 public boolean offer(String event) {
249 throw new IllegalStateException(this + " is not alive.");
252 synchronized (this) {
253 this.recentEvents.add(event);
256 netLogger.info("[IN|{}|{}]{}{}", this.getTopicCommInfrastructure(), this.topic, System.lineSeparator(), event);
259 return broadcast(event);
264 public void setFilter(String filter) {
265 if (consumer instanceof FilterableBusConsumer) {
266 ((FilterableBusConsumer) consumer).setFilter(filter);
269 throw new UnsupportedOperationException("no server-side filtering for topic " + topic);
274 public String toString() {
275 return "SingleThreadedBusTopicSource [consumerGroup=" + consumerGroup + ", consumerInstance=" + consumerInstance
276 + ", fetchTimeout=" + fetchTimeout + ", fetchLimit=" + fetchLimit + ", consumer=" + this.consumer
277 + ", alive=" + alive + ", locked=" + locked + ", uebThread=" + busPollerThread + ", topicListeners="
278 + topicListeners.size() + ", toString()=" + super.toString() + "]";
282 public String getConsumerGroup() {
283 return consumerGroup;
287 public String getConsumerInstance() {
288 return consumerInstance;
292 public void shutdown() {
294 this.topicListeners.clear();
298 public int getFetchTimeout() {
303 public int getFetchLimit() {