2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd.
7 * Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
8 * Copyright (C) 2022 Nordix Foundation.
9 * ================================================================================
10 * Licensed under the Apache License, Version 2.0 (the "License");
11 * you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
14 * http://www.apache.org/licenses/LICENSE-2.0
16 * Unless required by applicable law or agreed to in writing, software
17 * distributed under the License is distributed on an "AS IS" BASIS,
18 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 * See the License for the specific language governing permissions and
20 * limitations under the License.
21 * ============LICENSE_END=========================================================
24 package org.onap.policy.common.endpoints.event.comm.bus.internal;
26 import com.att.nsa.apiClient.http.HttpClient.ConnectionType;
27 import com.att.nsa.cambria.client.CambriaBatchingPublisher;
28 import com.att.nsa.cambria.client.CambriaClientBuilders;
29 import java.net.MalformedURLException;
30 import java.security.GeneralSecurityException;
31 import java.util.ArrayList;
32 import java.util.List;
34 import java.util.Properties;
35 import java.util.Random;
36 import java.util.concurrent.TimeUnit;
37 import org.apache.commons.lang3.StringUtils;
38 import org.apache.kafka.clients.producer.KafkaProducer;
39 import org.apache.kafka.clients.producer.ProducerConfig;
40 import org.apache.kafka.clients.producer.ProducerRecord;
41 import org.apache.kafka.common.record.CompressionType;
42 import org.onap.dmaap.mr.client.impl.MRSimplerBatchPublisher;
43 import org.onap.dmaap.mr.client.response.MRPublisherResponse;
44 import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants;
45 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
46 import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
50 public interface BusPublisher {
55 * @param partitionId id
56 * @param message the message
57 * @return true if success, false otherwise
58 * @throws IllegalArgumentException if no message provided
60 public boolean send(String partitionId, String message);
63 * closes the publisher.
68 * Cambria based library publisher.
70 public static class CambriaPublisherWrapper implements BusPublisher {
72 private static Logger logger = LoggerFactory.getLogger(CambriaPublisherWrapper.class);
75 * The actual Cambria publisher.
78 protected CambriaBatchingPublisher publisher;
83 * @param busTopicParams topic parameters
85 public CambriaPublisherWrapper(BusTopicParams busTopicParams) {
87 var builder = new CambriaClientBuilders.PublisherBuilder();
89 builder.usingHosts(busTopicParams.getServers()).onTopic(busTopicParams.getTopic());
91 // Set read timeout to 30 seconds (TBD: this should be configurable)
92 builder.withSocketTimeout(30000);
94 if (busTopicParams.isUseHttps()) {
95 if (busTopicParams.isAllowSelfSignedCerts()) {
96 builder.withConnectionType(ConnectionType.HTTPS_NO_VALIDATION);
98 builder.withConnectionType(ConnectionType.HTTPS);
103 if (busTopicParams.isApiKeyValid() && busTopicParams.isApiSecretValid()) {
104 builder.authenticatedBy(busTopicParams.getApiKey(), busTopicParams.getApiSecret());
107 if (busTopicParams.isUserNameValid() && busTopicParams.isPasswordValid()) {
108 builder.authenticatedByHttp(busTopicParams.getUserName(), busTopicParams.getPassword());
112 this.publisher = builder.build();
113 } catch (MalformedURLException | GeneralSecurityException e) {
114 throw new IllegalArgumentException(e);
119 public boolean send(String partitionId, String message) {
120 if (message == null) {
121 throw new IllegalArgumentException("No message provided");
125 this.publisher.send(partitionId, message);
126 } catch (Exception e) {
127 logger.warn("{}: SEND of {} cannot be performed because of {}", this, message, e.getMessage(), e);
134 public void close() {
135 logger.info("{}: CLOSE", this);
138 this.publisher.close();
139 } catch (Exception e) {
140 logger.warn("{}: CLOSE FAILED because of {}", this, e.getMessage(), e);
146 public String toString() {
147 return "CambriaPublisherWrapper []";
153 * Kafka based library publisher.
155 public static class KafkaPublisherWrapper implements BusPublisher {
157 private static Logger logger = LoggerFactory.getLogger(KafkaPublisherWrapper.class);
160 * The actual Kafka publisher.
162 private final KafkaProducer producer;
167 * @param busTopicParams topic parameters
169 public KafkaPublisherWrapper(BusTopicParams busTopicParams) {
170 // TODO Setting of topic parameters is not implemented yet.
171 //Setup Properties for Kafka Producer
172 Properties kafkaProps = new Properties();
173 this.producer = new KafkaProducer(kafkaProps);
177 public boolean send(String partitionId, String message) {
178 if (message == null) {
179 throw new IllegalArgumentException("No message provided");
181 // TODO Sending messages is not implemented yet
186 public void close() {
187 logger.info("{}: CLOSE", this);
189 try (this.producer) {
190 this.producer.close();
191 } catch (Exception e) {
192 logger.warn("{}: CLOSE FAILED because of {}", this, e.getMessage(), e);
198 public String toString() {
199 return "KafkaPublisherWrapper []";
205 * DmaapClient library wrapper.
207 public abstract class DmaapPublisherWrapper implements BusPublisher {
209 private static Logger logger = LoggerFactory.getLogger(DmaapPublisherWrapper.class);
212 * MR based Publisher.
214 protected MRSimplerBatchPublisher publisher;
215 protected Properties props;
218 * MR Publisher Wrapper.
220 * @param servers messaging bus hosts
222 * @param username AAF or DME2 Login
223 * @param password AAF or DME2 Password
225 protected DmaapPublisherWrapper(ProtocolTypeConstants protocol, List<String> servers, String topic,
226 String username, String password, boolean useHttps) {
229 if (StringUtils.isBlank(topic)) {
230 throw new IllegalArgumentException("No topic for DMaaP");
234 configureProtocol(topic, protocol, servers, useHttps);
236 this.publisher.logTo(LoggerFactory.getLogger(MRSimplerBatchPublisher.class.getName()));
238 this.publisher.setUsername(username);
239 this.publisher.setPassword(password);
241 props = new Properties();
243 props.setProperty("Protocol", (useHttps ? "https" : "http"));
244 props.setProperty("contenttype", "application/json");
245 props.setProperty("username", username);
246 props.setProperty("password", password);
248 props.setProperty("topic", topic);
250 this.publisher.setProps(props);
252 if (protocol == ProtocolTypeConstants.AAF_AUTH) {
253 this.publisher.setHost(servers.get(0));
256 logger.info("{}: CREATION: using protocol {}", this, protocol.getValue());
259 private void configureProtocol(String topic, ProtocolTypeConstants protocol, List<String> servers,
262 if (protocol == ProtocolTypeConstants.AAF_AUTH) {
263 if (servers == null || servers.isEmpty()) {
264 throw new IllegalArgumentException("No DMaaP servers or DME2 partner provided");
267 ArrayList<String> dmaapServers = new ArrayList<>();
268 String port = useHttps ? ":3905" : ":3904";
269 for (String server : servers) {
270 dmaapServers.add(server + port);
274 this.publisher = new MRSimplerBatchPublisher.Builder().againstUrls(dmaapServers).onTopic(topic).build();
276 this.publisher.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue());
278 } else if (protocol == ProtocolTypeConstants.DME2) {
279 ArrayList<String> dmaapServers = new ArrayList<>();
280 dmaapServers.add("0.0.0.0:3904");
282 this.publisher = new MRSimplerBatchPublisher.Builder().againstUrls(dmaapServers).onTopic(topic).build();
284 this.publisher.setProtocolFlag(ProtocolTypeConstants.DME2.getValue());
287 throw new IllegalArgumentException("Invalid DMaaP protocol " + protocol);
292 public void close() {
293 logger.info("{}: CLOSE", this);
296 this.publisher.close(1, TimeUnit.SECONDS);
298 } catch (InterruptedException e) {
299 logger.warn("{}: CLOSE FAILED", this, e);
300 Thread.currentThread().interrupt();
302 } catch (Exception e) {
303 logger.warn("{}: CLOSE FAILED", this, e);
308 public boolean send(String partitionId, String message) {
309 if (message == null) {
310 throw new IllegalArgumentException("No message provided");
313 this.publisher.setPubResponse(new MRPublisherResponse());
314 this.publisher.send(partitionId, message);
315 MRPublisherResponse response = this.publisher.sendBatchWithResponse();
316 if (response != null) {
317 logger.debug("DMaaP publisher received {} : {}", response.getResponseCode(),
318 response.getResponseMessage());
325 public String toString() {
326 return "DmaapPublisherWrapper [" + "publisher.getAuthDate()=" + publisher.getAuthDate()
327 + ", publisher.getAuthKey()=" + publisher.getAuthKey() + ", publisher.getHost()="
328 + publisher.getHost() + ", publisher.getProtocolFlag()=" + publisher.getProtocolFlag()
329 + ", publisher.getUsername()=" + publisher.getUsername() + "]";
334 * DmaapClient library wrapper.
336 public static class DmaapAafPublisherWrapper extends DmaapPublisherWrapper {
338 * MR based Publisher.
340 public DmaapAafPublisherWrapper(List<String> servers, String topic, String aafLogin, String aafPassword,
343 super(ProtocolTypeConstants.AAF_AUTH, servers, topic, aafLogin, aafPassword, useHttps);
347 public static class DmaapDmePublisherWrapper extends DmaapPublisherWrapper {
352 * @param busTopicParams topic parameters
354 public DmaapDmePublisherWrapper(BusTopicParams busTopicParams) {
356 super(ProtocolTypeConstants.DME2, busTopicParams.getServers(), busTopicParams.getTopic(),
357 busTopicParams.getUserName(), busTopicParams.getPassword(), busTopicParams.isUseHttps());
359 String dme2RouteOffer = busTopicParams.isAdditionalPropsValid()
360 ? busTopicParams.getAdditionalProps().get(
361 PolicyEndPointProperties.DME2_ROUTE_OFFER_PROPERTY)
364 validateParams(busTopicParams, dme2RouteOffer);
366 String serviceName = busTopicParams.getServers().get(0);
368 /* These are required, no defaults */
369 props.setProperty("Environment", busTopicParams.getEnvironment());
370 props.setProperty("AFT_ENVIRONMENT", busTopicParams.getAftEnvironment());
372 props.setProperty(PolicyEndPointProperties.DME2_SERVICE_NAME_PROPERTY, serviceName);
374 if (busTopicParams.getPartner() != null) {
375 props.setProperty("Partner", busTopicParams.getPartner());
377 if (dme2RouteOffer != null) {
378 props.setProperty(PolicyEndPointProperties.DME2_ROUTE_OFFER_PROPERTY, dme2RouteOffer);
381 props.setProperty("Latitude", busTopicParams.getLatitude());
382 props.setProperty("Longitude", busTopicParams.getLongitude());
384 // ServiceName also a default, found in additionalProps
386 /* These are optional, will default to these values if not set in optionalProps */
387 props.setProperty("AFT_DME2_EP_READ_TIMEOUT_MS", "50000");
388 props.setProperty("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", "240000");
389 props.setProperty("AFT_DME2_EP_CONN_TIMEOUT", "15000");
390 props.setProperty("Version", "1.0");
391 props.setProperty("SubContextPath", "/");
392 props.setProperty("sessionstickinessrequired", "no");
394 /* These should not change */
395 props.setProperty("TransportType", "DME2");
396 props.setProperty("MethodType", "POST");
398 if (busTopicParams.isAdditionalPropsValid()) {
399 addAdditionalProps(busTopicParams);
402 this.publisher.setProps(props);
405 private void validateParams(BusTopicParams busTopicParams, String dme2RouteOffer) {
406 if (busTopicParams.isEnvironmentInvalid()) {
407 throw parmException(busTopicParams.getTopic(),
408 PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ENVIRONMENT_SUFFIX);
410 if (busTopicParams.isAftEnvironmentInvalid()) {
411 throw parmException(busTopicParams.getTopic(),
412 PolicyEndPointProperties.PROPERTY_DMAAP_DME2_AFT_ENVIRONMENT_SUFFIX);
414 if (busTopicParams.isLatitudeInvalid()) {
415 throw parmException(busTopicParams.getTopic(),
416 PolicyEndPointProperties.PROPERTY_DMAAP_DME2_LATITUDE_SUFFIX);
418 if (busTopicParams.isLongitudeInvalid()) {
419 throw parmException(busTopicParams.getTopic(),
420 PolicyEndPointProperties.PROPERTY_DMAAP_DME2_LONGITUDE_SUFFIX);
423 if ((busTopicParams.isPartnerInvalid())
424 && StringUtils.isBlank(dme2RouteOffer)) {
425 throw new IllegalArgumentException(
426 "Must provide at least " + PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "."
427 + busTopicParams.getTopic()
428 + PolicyEndPointProperties.PROPERTY_DMAAP_DME2_PARTNER_SUFFIX + " or "
429 + PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS + "." + busTopicParams.getTopic()
430 + PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ROUTE_OFFER_SUFFIX + " for DME2");
434 private void addAdditionalProps(BusTopicParams busTopicParams) {
435 for (Map.Entry<String, String> entry : busTopicParams.getAdditionalProps().entrySet()) {
436 String key = entry.getKey();
437 String value = entry.getValue();
440 props.setProperty(key, value);
445 private IllegalArgumentException parmException(String topic, String propnm) {
446 return new IllegalArgumentException("Missing " + PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS + "."
447 + topic + propnm + " property for DME2 in DMaaP");