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.common.endpoints.event.comm.bus.internal;
23 import java.net.MalformedURLException;
24 import java.util.List;
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.utils.network.NetworkUtil;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
35 * This topic source implementation specializes in reading messages over a bus topic source and
36 * notifying its listeners
38 public abstract class SingleThreadedBusTopicSource extends BusTopicBase
39 implements Runnable, BusTopicSource, FilterableTopicSource {
42 * Not to be converted to PolicyLogger. This will contain all instract /out traffic and only
43 * that in a single file in a concise format.
45 private static Logger logger = LoggerFactory.getLogger(InlineBusTopicSink.class);
46 private static final Logger netLogger = LoggerFactory.getLogger(NETWORK_LOGGER);
51 protected final String consumerGroup;
54 * Bus consumer instance
56 protected final String consumerInstance;
61 protected final int fetchTimeout;
66 protected final int fetchLimit;
69 * Message Bus Consumer
71 protected BusConsumer consumer;
74 * Independent thread reading message over my topic
76 protected Thread busPollerThread;
81 * @param servers Bus servers
82 * @param topic Bus Topic to be monitored
83 * @param apiKey Bus API Key (optional)
84 * @param apiSecret Bus API Secret (optional)
85 * @param consumerGroup Bus Reader Consumer Group
86 * @param consumerInstance Bus Reader Instance
87 * @param fetchTimeout Bus fetch timeout
88 * @param fetchLimit Bus fetch limit
89 * @param useHttps does the bus use https
90 * @param allowSelfSignedCerts are self-signed certificates allowed
91 * @throws IllegalArgumentException An invalid parameter passed in
93 public SingleThreadedBusTopicSource(List<String> servers, String topic, String apiKey, String apiSecret,
94 String consumerGroup, String consumerInstance, int fetchTimeout, int fetchLimit, boolean useHttps,
95 boolean allowSelfSignedCerts) {
97 super(servers, topic, apiKey, apiSecret, useHttps, allowSelfSignedCerts);
99 if (consumerGroup == null || consumerGroup.isEmpty()) {
100 this.consumerGroup = UUID.randomUUID().toString();
102 this.consumerGroup = consumerGroup;
105 if (consumerInstance == null || consumerInstance.isEmpty()) {
106 this.consumerInstance = NetworkUtil.getHostname();
108 this.consumerInstance = consumerInstance;
111 if (fetchTimeout <= 0) {
112 this.fetchTimeout = NO_TIMEOUT_MS_FETCH;
114 this.fetchTimeout = fetchTimeout;
117 if (fetchLimit <= 0) {
118 this.fetchLimit = NO_LIMIT_FETCH;
120 this.fetchLimit = fetchLimit;
126 * Initialize the Bus client
128 public abstract void init() throws MalformedURLException;
131 public void register(TopicListener topicListener) {
133 super.register(topicListener);
136 if (!alive && !locked) {
139 logger.info("{}: register: start not attempted", this);
141 } catch (Exception e) {
142 logger.warn("{}: cannot start after registration of because of: {}", this, topicListener, e.getMessage(),
148 public void unregister(TopicListener topicListener) {
150 synchronized (this) {
151 super.unregister(topicListener);
152 stop = this.topicListeners.isEmpty();
161 public boolean start() {
162 logger.info("{}: starting", this);
164 synchronized (this) {
171 throw new IllegalStateException(this + " is locked.");
174 if (this.busPollerThread == null || !this.busPollerThread.isAlive() || this.consumer == null) {
179 this.busPollerThread = new Thread(this);
180 this.busPollerThread.setName(this.getTopicCommInfrastructure() + "-source-" + this.getTopic());
181 busPollerThread.start();
182 } catch (Exception e) {
183 logger.warn("{}: cannot start because of {}", this, e.getMessage(), e);
184 throw new IllegalStateException(e);
193 public boolean stop() {
194 logger.info("{}: stopping", this);
196 synchronized (this) {
197 BusConsumer consumerCopy = this.consumer;
200 this.consumer = null;
202 if (consumerCopy != null) {
204 consumerCopy.close();
205 } catch (Exception e) {
206 logger.warn("{}: stop failed because of {}", this, e.getMessage(), e);
217 * Run thread method for the Bus Reader
223 for (String event : this.consumer.fetch()) {
224 synchronized (this) {
225 this.recentEvents.add(event);
228 netLogger.info("[IN|{}|{}]{}{}", this.getTopicCommInfrastructure(), this.topic,
229 System.lineSeparator(), event);
237 } catch (Exception e) {
238 logger.error("{}: cannot fetch because of ", this, e.getMessage(), e);
242 logger.info("{}: exiting thread", this);
249 public boolean offer(String event) {
251 throw new IllegalStateException(this + " is not alive.");
254 synchronized (this) {
255 this.recentEvents.add(event);
258 netLogger.info("[IN|{}|{}]{}{}", this.getTopicCommInfrastructure(), this.topic, System.lineSeparator(), event);
261 return broadcast(event);
266 public void setFilter(String filter) {
267 if (consumer instanceof FilterableBusConsumer) {
268 ((FilterableBusConsumer) consumer).setFilter(filter);
271 throw new UnsupportedOperationException("no server-side filtering for topic " + topic);
276 public String toString() {
277 return "SingleThreadedBusTopicSource [consumerGroup=" + consumerGroup + ", consumerInstance=" + consumerInstance
278 + ", fetchTimeout=" + fetchTimeout + ", fetchLimit=" + fetchLimit + ", consumer=" + this.consumer
279 + ", alive=" + alive + ", locked=" + locked + ", uebThread=" + busPollerThread + ", topicListeners="
280 + topicListeners.size() + ", toString()=" + super.toString() + "]";
287 public String getConsumerGroup() {
288 return consumerGroup;
295 public String getConsumerInstance() {
296 return consumerInstance;
303 public void shutdown() {
305 this.topicListeners.clear();
312 public int getFetchTimeout() {
320 public int getFetchLimit() {