2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 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;
30 import org.onap.policy.drools.event.comm.FilterableTopicSource;
31 import org.onap.policy.drools.event.comm.TopicListener;
32 import org.onap.policy.drools.event.comm.bus.BusTopicSource;
33 import org.onap.policy.drools.event.comm.bus.internal.BusConsumer.FilterableBusConsumer;
36 * This topic source implementation specializes in reading messages
37 * over a bus topic source and notifying its listeners
39 public abstract class SingleThreadedBusTopicSource
41 implements Runnable, BusTopicSource, FilterableTopicSource {
44 * Not to be converted to PolicyLogger.
45 * This will contain all instract /out traffic and only that in a single file in a concise format.
47 private static Logger logger = LoggerFactory.getLogger(InlineBusTopicSink.class);
48 private static final Logger netLogger = LoggerFactory.getLogger(NETWORK_LOGGER);
53 protected final String consumerGroup;
56 * Bus consumer instance
58 protected final String consumerInstance;
63 protected final int fetchTimeout;
68 protected final int fetchLimit;
71 * Message Bus Consumer
73 protected BusConsumer consumer;
77 * reflects invocation of start()/stop()
78 * !locked & start() => alive
81 protected volatile boolean alive = false;
84 * Independent thread reading message over my topic
86 protected Thread busPollerThread;
89 * All my subscribers for new message notifications
91 protected final ArrayList<TopicListener> topicListeners = new ArrayList<>();
96 * @param servers Bus servers
97 * @param topic Bus Topic to be monitored
98 * @param apiKey Bus API Key (optional)
99 * @param apiSecret Bus API Secret (optional)
100 * @param consumerGroup Bus Reader Consumer Group
101 * @param consumerInstance Bus Reader Instance
102 * @param fetchTimeout Bus fetch timeout
103 * @param fetchLimit Bus fetch limit
104 * @param useHttps does the bus use https
105 * @param allowSelfSignedCerts are self-signed certificates allowed
106 * @throws IllegalArgumentException An invalid parameter passed in
108 public SingleThreadedBusTopicSource(List<String> servers,
112 String consumerGroup,
113 String consumerInstance,
117 boolean allowSelfSignedCerts)
118 throws IllegalArgumentException {
120 super(servers, topic, apiKey, apiSecret, useHttps, allowSelfSignedCerts);
122 if (consumerGroup == null || consumerGroup.isEmpty()) {
123 this.consumerGroup = UUID.randomUUID ().toString();
125 this.consumerGroup = consumerGroup;
128 if (consumerInstance == null || consumerInstance.isEmpty()) {
129 this.consumerInstance = DEFAULT_CONSUMER_INSTANCE;
131 this.consumerInstance = consumerInstance;
134 if (fetchTimeout <= 0) {
135 this.fetchTimeout = NO_TIMEOUT_MS_FETCH;
137 this.fetchTimeout = fetchTimeout;
140 if (fetchLimit <= 0) {
141 this.fetchLimit = NO_LIMIT_FETCH;
143 this.fetchLimit = fetchLimit;
149 * Initialize the Bus client
151 public abstract void init() throws MalformedURLException;
154 public void register(TopicListener topicListener)
155 throws IllegalArgumentException {
157 super.register(topicListener);
160 if (!alive && !locked)
163 logger.info("{}: register: start not attempted", this);
164 } catch (Exception e) {
165 logger.warn("{}: cannot start after registration of because of: {}",
166 this, topicListener, e.getMessage(), e);
171 public void unregister(TopicListener topicListener) {
173 synchronized (this) {
174 super.unregister(topicListener);
175 stop = this.topicListeners.isEmpty();
184 public boolean start() throws IllegalStateException {
185 logger.info("{}: starting", this);
193 throw new IllegalStateException(this + " is locked.");
195 if (this.busPollerThread == null ||
196 !this.busPollerThread.isAlive() ||
197 this.consumer == null) {
202 this.busPollerThread = new Thread(this);
203 this.busPollerThread.setName(this.getTopicCommInfrastructure() + "-source-" + this.getTopic());
204 busPollerThread.start();
205 } catch (Exception e) {
206 logger.warn("{}: cannot start because of {}", this, e.getMessage(), e);
207 throw new IllegalStateException(e);
216 public boolean stop() {
217 logger.info("{}: stopping", this);
220 BusConsumer consumerCopy = this.consumer;
223 this.consumer = null;
225 if (consumerCopy != null) {
227 consumerCopy.close();
228 } catch (Exception e) {
229 logger.warn("{}: stop failed because of {}", this, e.getMessage(), e);
240 * Run thread method for the Bus Reader
246 for (String event: this.consumer.fetch()) {
247 synchronized (this) {
248 this.recentEvents.add(event);
251 netLogger.info("[IN|{}|{}]{}{}",
252 this.getTopicCommInfrastructure(), this.topic,
253 System.lineSeparator(), event);
260 } catch (Exception e) {
261 logger.error("{}: cannot fetch because of ", this, e.getMessage(), e);
265 logger.info("{}: exiting thread", this);
272 public boolean offer(String event) {
274 throw new IllegalStateException(this + " is not alive.");
277 synchronized (this) {
278 this.recentEvents.add(event);
281 netLogger.info("[IN|{}|{}]{}{}",this.getTopicCommInfrastructure(),this.topic,
282 System.lineSeparator(), event);
285 return broadcast(event);
290 public void setFilter(String filter) {
291 if(consumer instanceof FilterableBusConsumer) {
292 ((FilterableBusConsumer) consumer).setFilter(filter);
295 throw new UnsupportedOperationException("no server-side filtering for topic " + topic);
300 public String toString() {
301 StringBuilder builder = new StringBuilder();
302 builder.append("SingleThreadedBusTopicSource [consumerGroup=").append(consumerGroup)
303 .append(", consumerInstance=").append(consumerInstance).append(", fetchTimeout=").append(fetchTimeout)
304 .append(", fetchLimit=").append(fetchLimit)
305 .append(", consumer=").append(this.consumer).append(", alive=")
306 .append(alive).append(", locked=").append(locked).append(", uebThread=").append(busPollerThread)
307 .append(", topicListeners=").append(topicListeners.size()).append(", toString()=").append(super.toString())
309 return builder.toString();
316 public boolean isAlive() {
324 public String getConsumerGroup() {
325 return consumerGroup;
332 public String getConsumerInstance() {
333 return consumerInstance;
340 public void shutdown() throws IllegalStateException {
342 this.topicListeners.clear();
349 public int getFetchTimeout() {
357 public int getFetchLimit() {