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;
34 import org.onap.policy.drools.utils.NetworkUtil;
37 * This topic source implementation specializes in reading messages
38 * over a bus topic source and notifying its listeners
40 public abstract class SingleThreadedBusTopicSource
42 implements Runnable, BusTopicSource, FilterableTopicSource {
45 * Not to be converted to PolicyLogger.
46 * This will contain all instract /out traffic and only that in a single file in a concise format.
48 private static Logger logger = LoggerFactory.getLogger(InlineBusTopicSink.class);
49 private static final Logger netLogger = LoggerFactory.getLogger(NETWORK_LOGGER);
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;
78 * reflects invocation of start()/stop()
79 * !locked & start() => alive
82 protected volatile boolean alive = false;
85 * Independent thread reading message over my topic
87 protected Thread busPollerThread;
90 * All my subscribers for new message notifications
92 protected final ArrayList<TopicListener> topicListeners = new ArrayList<>();
97 * @param servers Bus servers
98 * @param topic Bus Topic to be monitored
99 * @param apiKey Bus API Key (optional)
100 * @param apiSecret Bus API Secret (optional)
101 * @param consumerGroup Bus Reader Consumer Group
102 * @param consumerInstance Bus Reader Instance
103 * @param fetchTimeout Bus fetch timeout
104 * @param fetchLimit Bus fetch limit
105 * @param useHttps does the bus use https
106 * @param allowSelfSignedCerts are self-signed certificates allowed
107 * @throws IllegalArgumentException An invalid parameter passed in
109 public SingleThreadedBusTopicSource(List<String> servers,
113 String consumerGroup,
114 String consumerInstance,
118 boolean allowSelfSignedCerts)
119 throws IllegalArgumentException {
121 super(servers, topic, apiKey, apiSecret, useHttps, allowSelfSignedCerts);
123 if (consumerGroup == null || consumerGroup.isEmpty()) {
124 this.consumerGroup = UUID.randomUUID ().toString();
126 this.consumerGroup = consumerGroup;
129 if (consumerInstance == null || consumerInstance.isEmpty()) {
130 this.consumerInstance = NetworkUtil.getHostname();
132 this.consumerInstance = consumerInstance;
135 if (fetchTimeout <= 0) {
136 this.fetchTimeout = NO_TIMEOUT_MS_FETCH;
138 this.fetchTimeout = fetchTimeout;
141 if (fetchLimit <= 0) {
142 this.fetchLimit = NO_LIMIT_FETCH;
144 this.fetchLimit = fetchLimit;
150 * Initialize the Bus client
152 public abstract void init() throws MalformedURLException;
155 public void register(TopicListener topicListener)
156 throws IllegalArgumentException {
158 super.register(topicListener);
161 if (!alive && !locked)
164 logger.info("{}: register: start not attempted", this);
165 } catch (Exception e) {
166 logger.warn("{}: cannot start after registration of because of: {}",
167 this, topicListener, e.getMessage(), e);
172 public void unregister(TopicListener topicListener) {
174 synchronized (this) {
175 super.unregister(topicListener);
176 stop = this.topicListeners.isEmpty();
185 public boolean start() throws IllegalStateException {
186 logger.info("{}: starting", this);
194 throw new IllegalStateException(this + " is locked.");
196 if (this.busPollerThread == null ||
197 !this.busPollerThread.isAlive() ||
198 this.consumer == null) {
203 this.busPollerThread = new Thread(this);
204 this.busPollerThread.setName(this.getTopicCommInfrastructure() + "-source-" + this.getTopic());
205 busPollerThread.start();
206 } catch (Exception e) {
207 logger.warn("{}: cannot start because of {}", this, e.getMessage(), e);
208 throw new IllegalStateException(e);
217 public boolean stop() {
218 logger.info("{}: stopping", this);
221 BusConsumer consumerCopy = this.consumer;
224 this.consumer = null;
226 if (consumerCopy != null) {
228 consumerCopy.close();
229 } catch (Exception e) {
230 logger.warn("{}: stop failed because of {}", this, e.getMessage(), e);
241 * Run thread method for the Bus Reader
247 for (String event: this.consumer.fetch()) {
248 synchronized (this) {
249 this.recentEvents.add(event);
252 netLogger.info("[IN|{}|{}]{}{}",
253 this.getTopicCommInfrastructure(), this.topic,
254 System.lineSeparator(), event);
261 } catch (Exception e) {
262 logger.error("{}: cannot fetch because of ", this, e.getMessage(), e);
266 logger.info("{}: exiting thread", this);
273 public boolean offer(String event) {
275 throw new IllegalStateException(this + " is not alive.");
278 synchronized (this) {
279 this.recentEvents.add(event);
282 netLogger.info("[IN|{}|{}]{}{}",this.getTopicCommInfrastructure(),this.topic,
283 System.lineSeparator(), event);
286 return broadcast(event);
291 public void setFilter(String filter) {
292 if(consumer instanceof FilterableBusConsumer) {
293 ((FilterableBusConsumer) consumer).setFilter(filter);
296 throw new UnsupportedOperationException("no server-side filtering for topic " + topic);
301 public String toString() {
302 StringBuilder builder = new StringBuilder();
303 builder.append("SingleThreadedBusTopicSource [consumerGroup=").append(consumerGroup)
304 .append(", consumerInstance=").append(consumerInstance).append(", fetchTimeout=").append(fetchTimeout)
305 .append(", fetchLimit=").append(fetchLimit)
306 .append(", consumer=").append(this.consumer).append(", alive=")
307 .append(alive).append(", locked=").append(locked).append(", uebThread=").append(busPollerThread)
308 .append(", topicListeners=").append(topicListeners.size()).append(", toString()=").append(super.toString())
310 return builder.toString();
317 public boolean isAlive() {
325 public String getConsumerGroup() {
326 return consumerGroup;
333 public String getConsumerInstance() {
334 return consumerInstance;
341 public void shutdown() throws IllegalStateException {
343 this.topicListeners.clear();
350 public int getFetchTimeout() {
358 public int getFetchLimit() {