3a986c31e33ff86a340e797af369559718173b87
[appc.git] / appc-adapters / appc-dmaap-adapter / appc-dmaap-adapter-bundle / src / main / java / org / onap / appc / adapter / messaging / dmaap / http / HttpDmaapProducerImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * 
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.appc.adapter.messaging.dmaap.http;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import java.net.URI;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.HashSet;
32 import java.util.List;
33 import java.util.Set;
34 import org.apache.http.client.methods.CloseableHttpResponse;
35 import org.apache.http.client.methods.HttpPost;
36 import org.apache.http.entity.StringEntity;
37 import org.onap.appc.adapter.message.Producer;
38
39 public class HttpDmaapProducerImpl extends CommonHttpClient implements Producer {
40
41     private static final EELFLogger LOG = EELFManager.getInstance().getLogger(HttpDmaapProducerImpl.class);
42
43     private static final String CONTENT_TYPE = "application/cambria";
44     private static final String URL_TEMPLATE = "%s/events/%s";
45
46     private List<String> hosts;
47     private Set<String> topics;
48
49     public HttpDmaapProducerImpl() {
50         //for test purposes
51     }
52
53     public HttpDmaapProducerImpl(Collection<String> urls, String topicName) {
54         topics = new HashSet<>();
55         topics.add(topicName);
56
57         hosts = new ArrayList<>();
58         for (String host : urls) {
59             hosts.add(formatHostString(host));
60         }
61     }
62
63     @Override
64     public void updateCredentials(String user, String pass) {
65         LOG.debug(String.format("Setting auth to %s for %s", user, this.toString()));
66         this.setBasicAuth(user, pass);
67     }
68
69     @Override
70     public boolean post(String partition, String data) {
71         LOG.debug("Entering HttpDmaapProducerImpl::: post ");
72         long sent = 0;
73         try {
74             HttpPost request = postReq(null);
75             request.setHeader("Content-Type", CONTENT_TYPE);
76             request.setEntity(new StringEntity(bodyLine(partition, data)));
77
78             LOG.debug("Before sendRequest HttpDmaapProducerImpl::: post ");
79             sent = topics.stream()
80                 .filter(topic -> sendRequest(request, topic))
81                 .count();
82
83         } catch (Exception buildEx) {
84             LOG.error(
85                 String.format("Failed to build request with string [%s]. Message not sent to any topic. Reason: %s",
86                     data, buildEx.getMessage()),
87                 buildEx);
88         }
89         LOG.debug("Exiting HttpDmaapProducerImpl::: post ");
90         return sent == topics.size();
91     }
92
93     private boolean sendRequest(HttpPost request, String topic) {
94         boolean successful = false;
95         String uriStr = String.format(URL_TEMPLATE, hosts.get(0), topic);
96         try {
97             request.setURI(new URI(uriStr));
98             LOG.debug("HttpDmaapProducerImpl::: before sendRequest()");
99             CloseableHttpResponse response = getClient().execute(request);
100             LOG.debug("HttpDmaapProducerImpl::: after sendRequest()");
101             if (response.getStatusLine().getStatusCode() == 200) {
102                 successful = true;
103             }
104             else {
105                 LOG.debug("HttpDmaapProducerImpl::: did not receive 200 for sendRequest");
106             }
107             response.close();
108         } catch (Exception sendEx) {
109             LOG.error(String.format("Failed to send message to %s. Reason: %s", uriStr, sendEx.getMessage()),
110                 sendEx);
111             if (hosts.size() > 1) {
112                 String failedUrl = hosts.remove(0);
113                 hosts.add(failedUrl);
114                 LOG.debug(String.format("Moving host %s to the end of the pool. New primary host is %s",
115                     failedUrl, hosts.get(0)));
116             }
117         }
118         return successful;
119     }
120
121     /**
122      * Format the body for the application/cambria content type with no partitioning. See
123      *
124      * @param message
125      *            The message body to format
126      * @return A string in the application/cambria content type
127      */
128     private String bodyLine(String partition, String message) {
129         String prt = (partition == null) ? "" : partition;
130         String msg = (message == null) ? "" : message;
131         return String.format("%d.%d.%s%s", prt.length(), msg.length(), prt, msg);
132     }
133
134 }