2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.drools.event.comm.bus.internal;
23 import java.net.MalformedURLException;
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.UUID;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
31 import org.onap.policy.drools.event.comm.TopicListener;
32 import org.onap.policy.drools.event.comm.bus.BusTopicSource;
35 * This topic source implementation specializes in reading messages
36 * over a bus topic source and notifying its listeners
38 public abstract class SingleThreadedBusTopicSource
40 implements Runnable, BusTopicSource {
43 * Not to be converted to PolicyLogger.
44 * This will contain all instract /out traffic and only 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;
76 * reflects invocation of start()/stop()
77 * !locked & start() => alive
80 protected volatile boolean alive = false;
83 * Independent thread reading message over my topic
85 protected Thread busPollerThread;
88 * All my subscribers for new message notifications
90 protected final ArrayList<TopicListener> topicListeners = new ArrayList<TopicListener>();
95 * @param servers Bus servers
96 * @param topic Bus Topic to be monitored
97 * @param apiKey Bus API Key (optional)
98 * @param apiSecret Bus API Secret (optional)
99 * @param consumerGroup Bus Reader Consumer Group
100 * @param consumerInstance Bus Reader Instance
101 * @param fetchTimeout Bus fetch timeout
102 * @param fetchLimit Bus fetch limit
103 * @param useHttps does the bus use https
104 * @param allowSelfSignedCerts are self-signed certificates allowed
105 * @throws IllegalArgumentException An invalid parameter passed in
107 public SingleThreadedBusTopicSource(List<String> servers,
111 String consumerGroup,
112 String consumerInstance,
116 boolean allowSelfSignedCerts)
117 throws IllegalArgumentException {
119 super(servers, topic, apiKey, apiSecret, useHttps, allowSelfSignedCerts);
121 if (consumerGroup == null || consumerGroup.isEmpty()) {
122 this.consumerGroup = UUID.randomUUID ().toString();
124 this.consumerGroup = consumerGroup;
127 if (consumerInstance == null || consumerInstance.isEmpty()) {
128 this.consumerInstance = DEFAULT_CONSUMER_INSTANCE;
130 this.consumerInstance = consumerInstance;
133 if (fetchTimeout <= 0) {
134 this.fetchTimeout = NO_TIMEOUT_MS_FETCH;
136 this.fetchTimeout = fetchTimeout;
139 if (fetchLimit <= 0) {
140 this.fetchLimit = NO_LIMIT_FETCH;
142 this.fetchLimit = fetchLimit;
148 * Initialize the Bus client
150 public abstract void init() throws MalformedURLException;
153 public void register(TopicListener topicListener)
154 throws IllegalArgumentException {
156 super.register(topicListener);
159 if (!alive && !locked)
162 logger.info("{}: register: start not attempted", this);
163 } catch (Exception e) {
164 logger.warn("{}: cannot start after registration of because of: {}",
165 this, topicListener, e.getMessage(), e);
170 public void unregister(TopicListener topicListener) {
171 boolean stop = false;
172 synchronized (this) {
173 super.unregister(topicListener);
174 stop = (this.topicListeners.isEmpty());
183 public boolean start() throws IllegalStateException {
184 logger.info("{}: starting", this);
192 throw new IllegalStateException(this + " is locked.");
194 if (this.busPollerThread == null ||
195 !this.busPollerThread.isAlive() ||
196 this.consumer == null) {
201 this.busPollerThread = new Thread(this);
202 this.busPollerThread.setName(this.getTopicCommInfrastructure() + "-source-" + this.getTopic());
203 busPollerThread.start();
204 } catch (Exception e) {
205 logger.warn("{}: cannot start because of {}", this, e.getMessage(), e);
206 throw new IllegalStateException(e);
215 public boolean stop() {
216 logger.info("{}: stopping", this);
219 BusConsumer consumerCopy = this.consumer;
222 this.consumer = null;
224 if (consumerCopy != null) {
226 consumerCopy.close();
227 } catch (Exception e) {
228 logger.warn("{}: stop failed because of {}", this, e.getMessage(), e);
239 * Run thread method for the Bus Reader
245 for (String event: this.consumer.fetch()) {
246 synchronized (this) {
247 this.recentEvents.add(event);
250 netLogger.info("[IN|{}|{}]{}{}",
251 this.getTopicCommInfrastructure(), this.topic,
252 System.lineSeparator(), event);
259 } catch (Exception e) {
260 logger.error("{}: cannot fetch because of ", this, e.getMessage(), e);
264 logger.info("{}: exiting thread", this);
271 public boolean offer(String event) {
273 throw new IllegalStateException(this + " is not alive.");
276 synchronized (this) {
277 this.recentEvents.add(event);
280 netLogger.info("[IN|{}|{}]{}{}",this.getTopicCommInfrastructure(),this.topic,
281 System.lineSeparator(), event);
284 return broadcast(event);
289 public String toString() {
290 StringBuilder builder = new StringBuilder();
291 builder.append("SingleThreadedBusTopicSource [consumerGroup=").append(consumerGroup)
292 .append(", consumerInstance=").append(consumerInstance).append(", fetchTimeout=").append(fetchTimeout)
293 .append(", fetchLimit=").append(fetchLimit)
294 .append(", consumer=").append(this.consumer).append(", alive=")
295 .append(alive).append(", locked=").append(locked).append(", uebThread=").append(busPollerThread)
296 .append(", topicListeners=").append(topicListeners.size()).append(", toString()=").append(super.toString())
298 return builder.toString();
305 public boolean isAlive() {
313 public String getConsumerGroup() {
314 return consumerGroup;
321 public String getConsumerInstance() {
322 return consumerInstance;
329 public void shutdown() throws IllegalStateException {
331 this.topicListeners.clear();
338 public int getFetchTimeout() {
346 public int getFetchLimit() {