9b2e6f5ca2e1d5dd9f3956488c36b7dcbe7448a1
[policy/common.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * policy-endpoints
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.common.endpoints.event.comm.bus.internal;
23
24 import com.att.nsa.apiClient.http.HttpClient.ConnectionType;
25 import com.att.nsa.cambria.client.CambriaBatchingPublisher;
26 import com.att.nsa.cambria.client.CambriaClientBuilders;
27 import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder;
28 import com.fasterxml.jackson.annotation.JsonIgnore;
29
30 import java.net.MalformedURLException;
31 import java.security.GeneralSecurityException;
32 import java.util.ArrayList;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Properties;
36 import java.util.concurrent.TimeUnit;
37
38 import org.apache.commons.lang3.StringUtils;
39 import org.onap.dmaap.mr.client.impl.MRSimplerBatchPublisher;
40 import org.onap.dmaap.mr.client.response.MRPublisherResponse;
41 import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants;
42 import org.onap.policy.common.endpoints.event.comm.bus.DmaapTopicSinkFactory;
43 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 public interface BusPublisher {
48
49     /**
50      * sends a message.
51      * 
52      * @param partitionId id
53      * @param message the message
54      * @return true if success, false otherwise
55      * @throws IllegalArgumentException if no message provided
56      */
57     public boolean send(String partitionId, String message);
58
59     /**
60      * closes the publisher.
61      */
62     public void close();
63
64     /**
65      * Cambria based library publisher.
66      */
67     public static class CambriaPublisherWrapper implements BusPublisher {
68
69         private static Logger logger = LoggerFactory.getLogger(CambriaPublisherWrapper.class);
70
71         /**
72          * The actual Cambria publisher.
73          */
74         @JsonIgnore
75         protected volatile CambriaBatchingPublisher publisher;
76
77         /**
78          * Constructor.
79          * 
80          * @param busTopicParams topic parameters
81          */
82         public CambriaPublisherWrapper(BusTopicParams busTopicParams) {
83
84             PublisherBuilder builder = new CambriaClientBuilders.PublisherBuilder();
85
86             builder.usingHosts(busTopicParams.getServers()).onTopic(busTopicParams.getTopic());
87
88             // Set read timeout to 30 seconds (TBD: this should be configurable)
89             builder.withSocketTimeout(30000);
90
91             if (busTopicParams.isUseHttps()) {
92                 if (busTopicParams.isAllowSelfSignedCerts()) {
93                     builder.withConnectionType(ConnectionType.HTTPS_NO_VALIDATION);
94                 } else {
95                     builder.withConnectionType(ConnectionType.HTTPS);
96                 }
97             }
98
99
100             if (busTopicParams.isApiKeyValid() && busTopicParams.isApiSecretValid()) {
101                 builder.authenticatedBy(busTopicParams.getApiKey(), busTopicParams.getApiSecret());
102             }
103
104             if (busTopicParams.isUserNameValid() && busTopicParams.isPasswordValid()) {
105                 builder.authenticatedByHttp(busTopicParams.getUserName(), busTopicParams.getPassword());
106             }
107
108             try {
109                 this.publisher = builder.build();
110             } catch (MalformedURLException | GeneralSecurityException e) {
111                 throw new IllegalArgumentException(e);
112             }
113         }
114
115         @Override
116         public boolean send(String partitionId, String message) {
117             if (message == null) {
118                 throw new IllegalArgumentException("No message provided");
119             }
120
121             try {
122                 this.publisher.send(partitionId, message);
123             } catch (Exception e) {
124                 logger.warn("{}: SEND of {} cannot be performed because of {}", this, message, e.getMessage(), e);
125                 return false;
126             }
127             return true;
128         }
129
130         @Override
131         public void close() {
132             logger.info("{}: CLOSE", this);
133
134             try {
135                 this.publisher.close();
136             } catch (Exception e) {
137                 logger.warn("{}: CLOSE FAILED because of {}", this, e.getMessage(), e);
138             }
139         }
140
141
142         @Override
143         public String toString() {
144             return "CambriaPublisherWrapper []";
145         }
146
147     }
148
149     /**
150      * DmaapClient library wrapper.
151      */
152     public abstract class DmaapPublisherWrapper implements BusPublisher {
153
154         private static Logger logger = LoggerFactory.getLogger(DmaapPublisherWrapper.class);
155
156         /**
157          * MR based Publisher.
158          */
159         protected MRSimplerBatchPublisher publisher;
160         protected Properties props;
161
162         /**
163          * MR Publisher Wrapper.
164          *
165          * @param servers messaging bus hosts
166          * @param topic topic
167          * @param username AAF or DME2 Login
168          * @param password AAF or DME2 Password
169          */
170         public DmaapPublisherWrapper(ProtocolTypeConstants protocol, List<String> servers, String topic,
171                 String username, String password, boolean useHttps) {
172
173
174             if (StringUtils.isBlank(topic)) {
175                 throw new IllegalArgumentException("No topic for DMaaP");
176             }
177
178
179             if (protocol == ProtocolTypeConstants.AAF_AUTH) {
180                 if (servers == null || servers.isEmpty()) {
181                     throw new IllegalArgumentException("No DMaaP servers or DME2 partner provided");
182                 }
183
184                 ArrayList<String> dmaapServers = new ArrayList<>();
185                 if (useHttps) {
186                     for (String server : servers) {
187                         dmaapServers.add(server + ":3905");
188                     }
189
190                 } else {
191                     for (String server : servers) {
192                         dmaapServers.add(server + ":3904");
193                     }
194                 }
195
196
197                 this.publisher = new MRSimplerBatchPublisher.Builder().againstUrls(dmaapServers).onTopic(topic).build();
198
199                 this.publisher.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue());
200             } else if (protocol == ProtocolTypeConstants.DME2) {
201                 ArrayList<String> dmaapServers = new ArrayList<>();
202                 dmaapServers.add("0.0.0.0:3904");
203
204                 this.publisher = new MRSimplerBatchPublisher.Builder().againstUrls(dmaapServers).onTopic(topic).build();
205
206                 this.publisher.setProtocolFlag(ProtocolTypeConstants.DME2.getValue());
207             } else {
208                 throw new IllegalArgumentException("Invalid DMaaP protocol " + protocol);
209             }
210
211             this.publisher.logTo(LoggerFactory.getLogger(MRSimplerBatchPublisher.class.getName()));
212
213             this.publisher.setUsername(username);
214             this.publisher.setPassword(password);
215
216             props = new Properties();
217
218             if (useHttps) {
219                 props.setProperty("Protocol", "https");
220             } else {
221                 props.setProperty("Protocol", "http");
222             }
223
224             props.setProperty("contenttype", "application/json");
225             props.setProperty("username", username);
226             props.setProperty("password", password);
227
228             props.setProperty("topic", topic);
229
230             this.publisher.setProps(props);
231
232             if (protocol == ProtocolTypeConstants.AAF_AUTH) {
233                 this.publisher.setHost(servers.get(0));
234             }
235
236             logger.info("{}: CREATION: using protocol {}", this, protocol.getValue());
237         }
238
239         @Override
240         public void close() {
241             logger.info("{}: CLOSE", this);
242
243             try {
244                 this.publisher.close(1, TimeUnit.SECONDS);
245             } catch (Exception e) {
246                 logger.warn("{}: CLOSE FAILED because of {}", this, e.getMessage(), e);
247             }
248         }
249
250         @Override
251         public boolean send(String partitionId, String message) {
252             if (message == null) {
253                 throw new IllegalArgumentException("No message provided");
254             }
255
256             this.publisher.setPubResponse(new MRPublisherResponse());
257             this.publisher.send(partitionId, message);
258             MRPublisherResponse response = this.publisher.sendBatchWithResponse();
259             if (response != null) {
260                 logger.debug("DMaaP publisher received {} : {}", response.getResponseCode(),
261                         response.getResponseMessage());
262             }
263
264             return true;
265         }
266
267         @Override
268         public String toString() {
269             return "DmaapPublisherWrapper [" + "publisher.getAuthDate()=" + publisher.getAuthDate()
270                     + ", publisher.getAuthKey()=" + publisher.getAuthKey() + ", publisher.getHost()="
271                     + publisher.getHost() + ", publisher.getProtocolFlag()=" + publisher.getProtocolFlag()
272                     + ", publisher.getUsername()=" + publisher.getUsername() + "]";
273         }
274     }
275
276     /**
277      * DmaapClient library wrapper.
278      */
279     public static class DmaapAafPublisherWrapper extends DmaapPublisherWrapper {
280         /**
281          * MR based Publisher.
282          */
283         public DmaapAafPublisherWrapper(List<String> servers, String topic, String aafLogin, String aafPassword,
284                 boolean useHttps) {
285
286             super(ProtocolTypeConstants.AAF_AUTH, servers, topic, aafLogin, aafPassword, useHttps);
287         }
288     }
289
290     public static class DmaapDmePublisherWrapper extends DmaapPublisherWrapper {
291         
292         /**
293          * Constructor.
294          * 
295          * @param busTopicParams topic parameters
296          */
297         public DmaapDmePublisherWrapper(BusTopicParams busTopicParams) {
298
299             super(ProtocolTypeConstants.DME2, busTopicParams.getServers(),busTopicParams.getTopic(),
300                     busTopicParams.getUserName(),busTopicParams.getPassword(),busTopicParams.isUseHttps());
301             String dme2RouteOffer = null;
302             if (busTopicParams.isAdditionalPropsValid()) {
303                 dme2RouteOffer = busTopicParams.getAdditionalProps().get(
304                         DmaapTopicSinkFactory.DME2_ROUTE_OFFER_PROPERTY);
305             }
306
307             if (busTopicParams.isEnvironmentInvalid()) {
308                 throw parmException(busTopicParams.getTopic(),
309                         PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ENVIRONMENT_SUFFIX);
310             }
311             if (busTopicParams.isAftEnvironmentInvalid()) {
312                 throw parmException(busTopicParams.getTopic(),
313                         PolicyEndPointProperties.PROPERTY_DMAAP_DME2_AFT_ENVIRONMENT_SUFFIX);
314             }
315             if (busTopicParams.isLatitudeInvalid()) {
316                 throw parmException(busTopicParams.getTopic(),
317                         PolicyEndPointProperties.PROPERTY_DMAAP_DME2_LATITUDE_SUFFIX);
318             }
319             if (busTopicParams.isLongitudeInvalid()) {
320                 throw parmException(busTopicParams.getTopic(),
321                         PolicyEndPointProperties.PROPERTY_DMAAP_DME2_LONGITUDE_SUFFIX);
322             }
323
324             if ((busTopicParams.isPartnerInvalid())
325                     && StringUtils.isBlank(dme2RouteOffer)) {
326                 throw new IllegalArgumentException(
327                         "Must provide at least " + PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "."
328                                 + busTopicParams.getTopic()
329                                 + PolicyEndPointProperties.PROPERTY_DMAAP_DME2_PARTNER_SUFFIX + " or "
330                                 + PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS + "." + busTopicParams.getTopic()
331                                 + PolicyEndPointProperties.PROPERTY_DMAAP_DME2_ROUTE_OFFER_SUFFIX + " for DME2");
332             }
333
334             String serviceName = busTopicParams.getServers().get(0);
335
336             /* These are required, no defaults */
337             props.setProperty("Environment", busTopicParams.getEnvironment());
338             props.setProperty("AFT_ENVIRONMENT", busTopicParams.getAftEnvironment());
339
340             props.setProperty(DmaapTopicSinkFactory.DME2_SERVICE_NAME_PROPERTY, serviceName);
341
342             if (busTopicParams.getPartner() != null) {
343                 props.setProperty("Partner", busTopicParams.getPartner());
344             }
345             if (dme2RouteOffer != null) {
346                 props.setProperty(DmaapTopicSinkFactory.DME2_ROUTE_OFFER_PROPERTY, dme2RouteOffer);
347             }
348
349             props.setProperty("Latitude", busTopicParams.getLatitude());
350             props.setProperty("Longitude", busTopicParams.getLongitude());
351
352             // ServiceName also a default, found in additionalProps
353
354             /* These are optional, will default to these values if not set in optionalProps */
355             props.setProperty("AFT_DME2_EP_READ_TIMEOUT_MS", "50000");
356             props.setProperty("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", "240000");
357             props.setProperty("AFT_DME2_EP_CONN_TIMEOUT", "15000");
358             props.setProperty("Version", "1.0");
359             props.setProperty("SubContextPath", "/");
360             props.setProperty("sessionstickinessrequired", "no");
361
362             /* These should not change */
363             props.setProperty("TransportType", "DME2");
364             props.setProperty("MethodType", "POST");
365
366             if (busTopicParams.isAdditionalPropsValid()) {
367                 for (Map.Entry<String, String> entry : busTopicParams.getAdditionalProps().entrySet()) {
368                     String key = entry.getKey();
369                     String value = entry.getValue();
370
371                     if (value != null) {
372                         props.setProperty(key, value);
373                     }
374                 }
375             }
376
377             this.publisher.setProps(props);
378         }
379
380         private IllegalArgumentException parmException(String topic, String propnm) {
381             return new IllegalArgumentException("Missing " + PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS + "."
382                     + topic + propnm + " property for DME2 in DMaaP");
383
384         }
385     }
386 }