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,2023 Bell Canada. All rights reserved.
8 * Modifications Copyright (C) 2022-2023 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.UUID;
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.Producer;
40 import org.apache.kafka.clients.producer.ProducerConfig;
41 import org.apache.kafka.clients.producer.ProducerRecord;
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 {
52 public static final String NO_MESSAGE_PROVIDED = "No message provided";
57 * @param partitionId id
58 * @param message the message
59 * @return true if success, false otherwise
60 * @throws IllegalArgumentException if no message provided
62 public boolean send(String partitionId, String message);
65 * closes the publisher.
70 * Cambria based library publisher.
72 public static class CambriaPublisherWrapper implements BusPublisher {
74 private static Logger logger = LoggerFactory.getLogger(CambriaPublisherWrapper.class);
77 * The actual Cambria publisher.
80 protected CambriaBatchingPublisher publisher;
85 * @param busTopicParams topic parameters
87 public CambriaPublisherWrapper(BusTopicParams busTopicParams) {
89 var builder = new CambriaClientBuilders.PublisherBuilder();
91 builder.usingHosts(busTopicParams.getServers()).onTopic(busTopicParams.getTopic());
93 // Set read timeout to 30 seconds (TBD: this should be configurable)
94 builder.withSocketTimeout(30000);
96 if (busTopicParams.isUseHttps()) {
97 if (busTopicParams.isAllowSelfSignedCerts()) {
98 builder.withConnectionType(ConnectionType.HTTPS_NO_VALIDATION);
100 builder.withConnectionType(ConnectionType.HTTPS);
104 if (busTopicParams.isApiKeyValid() && busTopicParams.isApiSecretValid()) {
105 builder.authenticatedBy(busTopicParams.getApiKey(), busTopicParams.getApiSecret());
108 if (busTopicParams.isUserNameValid() && busTopicParams.isPasswordValid()) {
109 builder.authenticatedByHttp(busTopicParams.getUserName(), busTopicParams.getPassword());
113 this.publisher = builder.build();
114 } catch (MalformedURLException | GeneralSecurityException e) {
115 throw new IllegalArgumentException(e);
120 public boolean send(String partitionId, String message) {
121 if (message == null) {
122 throw new IllegalArgumentException(NO_MESSAGE_PROVIDED);
126 this.publisher.send(partitionId, message);
127 } catch (Exception e) {
128 logger.warn("{}: SEND of {} cannot be performed because of {}", this, message, e.getMessage(), e);
135 public void close() {
136 logger.info("{}: CLOSE", this);
139 this.publisher.close();
140 } catch (Exception e) {
141 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);
158 private static final String KEY_SERIALIZER = "org.apache.kafka.common.serialization.StringSerializer";
160 private String topic;
165 private Producer<String, String> producer;
166 protected Properties kafkaProps;
169 * Kafka Publisher Wrapper.
171 * @param busTopicParams topic parameters
173 protected KafkaPublisherWrapper(BusTopicParams busTopicParams) {
175 if (busTopicParams.isTopicInvalid()) {
176 throw new IllegalArgumentException("No topic for Kafka");
179 this.topic = busTopicParams.getTopic();
181 // Setup Properties for consumer
182 kafkaProps = new Properties();
183 kafkaProps.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, busTopicParams.getServers().get(0));
184 if (busTopicParams.isAdditionalPropsValid()) {
185 for (Map.Entry<String, String> entry : busTopicParams.getAdditionalProps().entrySet()) {
186 kafkaProps.put(entry.getKey(), entry.getValue());
189 if (kafkaProps.get(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG) == null) {
190 kafkaProps.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, KEY_SERIALIZER);
192 if (kafkaProps.get(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG) == null) {
193 kafkaProps.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, KEY_SERIALIZER);
196 producer = new KafkaProducer<>(kafkaProps);
200 public boolean send(String partitionId, String message) {
201 if (message == null) {
202 throw new IllegalArgumentException(NO_MESSAGE_PROVIDED);
207 ProducerRecord<String, String> producerRecord =
208 new ProducerRecord<>(topic, UUID.randomUUID().toString(), message);
210 this.producer.send(producerRecord);
212 } catch (Exception e) {
213 logger.warn("{}: SEND of {} cannot be performed because of {}", this, message, e.getMessage(), e);
220 public void close() {
221 logger.info("{}: CLOSE", this);
224 this.producer.close();
225 } catch (Exception e) {
226 logger.warn("{}: CLOSE FAILED because of {}", this, e.getMessage(), e);
231 public String toString() {
232 return "KafkaPublisherWrapper []";
238 * DmaapClient library wrapper.
240 public abstract class DmaapPublisherWrapper implements BusPublisher {
242 private static Logger logger = LoggerFactory.getLogger(DmaapPublisherWrapper.class);
245 * MR based Publisher.
247 protected MRSimplerBatchPublisher publisher;
248 protected Properties props;
251 * MR Publisher Wrapper.
253 * @param servers messaging bus hosts
255 * @param username AAF or DME2 Login
256 * @param password AAF or DME2 Password
258 protected DmaapPublisherWrapper(ProtocolTypeConstants protocol, List<String> servers, String topic,
259 String username, String password, boolean useHttps) {
261 if (StringUtils.isBlank(topic)) {
262 throw new IllegalArgumentException("No topic for DMaaP");
265 configureProtocol(topic, protocol, servers, useHttps);
267 this.publisher.logTo(LoggerFactory.getLogger(MRSimplerBatchPublisher.class.getName()));
269 this.publisher.setUsername(username);
270 this.publisher.setPassword(password);
272 props = new Properties();
274 props.setProperty("Protocol", (useHttps ? "https" : "http"));
275 props.setProperty("contenttype", "application/json");
276 props.setProperty("username", username);
277 props.setProperty("password", password);
279 props.setProperty("topic", topic);
281 this.publisher.setProps(props);
283 if (protocol == ProtocolTypeConstants.AAF_AUTH) {
284 this.publisher.setHost(servers.get(0));
287 logger.info("{}: CREATION: using protocol {}", this, protocol.getValue());
290 private void configureProtocol(String topic, ProtocolTypeConstants protocol, List<String> servers,
293 if (protocol == ProtocolTypeConstants.AAF_AUTH) {
294 if (servers == null || servers.isEmpty()) {
295 throw new IllegalArgumentException("No DMaaP servers or DME2 partner provided");
298 ArrayList<String> dmaapServers = new ArrayList<>();
299 String port = useHttps ? ":3905" : ":3904";
300 for (String server : servers) {
301 dmaapServers.add(server + port);
304 this.publisher = new MRSimplerBatchPublisher.Builder().againstUrls(dmaapServers).onTopic(topic).build();
306 this.publisher.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue());
308 } else if (protocol == ProtocolTypeConstants.DME2) {
309 ArrayList<String> dmaapServers = new ArrayList<>();
310 dmaapServers.add("0.0.0.0:3904");
312 this.publisher = new MRSimplerBatchPublisher.Builder().againstUrls(dmaapServers).onTopic(topic).build();
314 this.publisher.setProtocolFlag(ProtocolTypeConstants.DME2.getValue());
317 throw new IllegalArgumentException("Invalid DMaaP protocol " + protocol);
322 public void close() {
323 logger.info("{}: CLOSE", this);
326 this.publisher.close(1, TimeUnit.SECONDS);
328 } catch (InterruptedException e) {
329 logger.warn("{}: CLOSE FAILED", this, e);
330 Thread.currentThread().interrupt();
332 } catch (Exception e) {
333 logger.warn("{}: CLOSE FAILED", this, e);
338 public boolean send(String partitionId, String message) {
339 if (message == null) {
340 throw new IllegalArgumentException(NO_MESSAGE_PROVIDED);
343 this.publisher.setPubResponse(new MRPublisherResponse());
344 this.publisher.send(partitionId, message);
345 MRPublisherResponse response = this.publisher.sendBatchWithResponse();
346 if (response != null) {
347 logger.debug("DMaaP publisher received {} : {}", response.getResponseCode(),
348 response.getResponseMessage());
355 public String toString() {
356 return "DmaapPublisherWrapper [" + "publisher.getAuthDate()=" + publisher.getAuthDate()
357 + ", publisher.getAuthKey()=" + publisher.getAuthKey() + ", publisher.getHost()="
358 + publisher.getHost() + ", publisher.getProtocolFlag()=" + publisher.getProtocolFlag()
359 + ", publisher.getUsername()=" + publisher.getUsername() + "]";
364 * DmaapClient library wrapper.
366 public static class DmaapAafPublisherWrapper extends DmaapPublisherWrapper {
368 * MR based Publisher.
370 public DmaapAafPublisherWrapper(List<String> servers, String topic, String aafLogin, String aafPassword,
373 super(ProtocolTypeConstants.AAF_AUTH, servers, topic, aafLogin, aafPassword, useHttps);
377 public static class DmaapDmePublisherWrapper extends DmaapPublisherWrapper {
382 * @param busTopicParams topic parameters
384 public DmaapDmePublisherWrapper(BusTopicParams busTopicParams) {
386 super(ProtocolTypeConstants.DME2, busTopicParams.getServers(), busTopicParams.getTopic(),
387 busTopicParams.getUserName(), busTopicParams.getPassword(), busTopicParams.isUseHttps());
389 String dme2RouteOffer = busTopicParams.isAdditionalPropsValid()
390 ? busTopicParams.getAdditionalProps().get(PolicyEndPointProperties.DME2_ROUTE_OFFER_PROPERTY)
393 validateParams(busTopicParams, dme2RouteOffer);
395 String serviceName = busTopicParams.getServers().get(0);
397 /* These are required, no defaults */
398 props.setProperty("Environment", busTopicParams.getEnvironment());
399 props.setProperty("AFT_ENVIRONMENT", busTopicParams.getAftEnvironment());
401 props.setProperty(PolicyEndPointProperties.DME2_SERVICE_NAME_PROPERTY, serviceName);
403 if (busTopicParams.getPartner() != null) {
404 props.setProperty("Partner", busTopicParams.getPartner());
406 if (dme2RouteOffer != null) {
407 props.setProperty(PolicyEndPointProperties.DME2_ROUTE_OFFER_PROPERTY, dme2RouteOffer);
410 props.setProperty("Latitude", busTopicParams.getLatitude());
411 props.setProperty("Longitude", busTopicParams.getLongitude());
413 // ServiceName also a default, found in additionalProps
415 /* These are optional, will default to these values if not set in optionalProps */
416 props.setProperty("AFT_DME2_EP_READ_TIMEOUT_MS", "50000");
417 props.setProperty("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", "240000");
418 props.setProperty("AFT_DME2_EP_CONN_TIMEOUT", "15000");
419 props.setProperty("Version", "1.0");
420 props.setProperty("SubContextPath", "/");
421 props.setProperty("sessionstickinessrequired", "no");
423 /* These should not change */
424 props.setProperty("TransportType", "DME2");
425 props.setProperty("MethodType", "POST");
427 if (busTopicParams.isAdditionalPropsValid()) {
428 addAdditionalProps(busTopicParams);
431 this.publisher.setProps(props);
434 private void validateParams(BusTopicParams busTopicParams, String dme2RouteOffer) {
435 if (busTopicParams.isEnvironmentInvalid()) {
436 throw parmException(busTopicParams.getTopic(),
437 PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ENVIRONMENT_SUFFIX);
439 if (busTopicParams.isAftEnvironmentInvalid()) {
440 throw parmException(busTopicParams.getTopic(),
441 PolicyEndPointProperties.PROPERTY_DMAAP_DME2_AFT_ENVIRONMENT_SUFFIX);
443 if (busTopicParams.isLatitudeInvalid()) {
444 throw parmException(busTopicParams.getTopic(),
445 PolicyEndPointProperties.PROPERTY_DMAAP_DME2_LATITUDE_SUFFIX);
447 if (busTopicParams.isLongitudeInvalid()) {
448 throw parmException(busTopicParams.getTopic(),
449 PolicyEndPointProperties.PROPERTY_DMAAP_DME2_LONGITUDE_SUFFIX);
452 if ((busTopicParams.isPartnerInvalid()) && StringUtils.isBlank(dme2RouteOffer)) {
453 throw new IllegalArgumentException("Must provide at least "
454 + PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." + busTopicParams.getTopic()
455 + PolicyEndPointProperties.PROPERTY_DMAAP_DME2_PARTNER_SUFFIX + " or "
456 + PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS + "." + busTopicParams.getTopic()
457 + PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ROUTE_OFFER_SUFFIX + " for DME2");
461 private void addAdditionalProps(BusTopicParams busTopicParams) {
462 for (Map.Entry<String, String> entry : busTopicParams.getAdditionalProps().entrySet()) {
463 String key = entry.getKey();
464 String value = entry.getValue();
467 props.setProperty(key, value);
472 private IllegalArgumentException parmException(String topic, String propnm) {
473 return new IllegalArgumentException("Missing " + PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS + "."
474 + topic + propnm + " property for DME2 in DMaaP");