1073e152f6235bd104b65cf47ddbe9e33868c849
[appc.git] / appc-adapters / appc-dmaap-adapter / appc-dmaap-adapter-bundle / src / main / java / org / openecomp / appc / adapter / messaging / dmaap / http / HttpDmaapProducerImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.openecomp.appc.adapter.messaging.dmaap.http;
26
27 import java.net.URI;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.HashSet;
31 import java.util.List;
32 import java.util.Set;
33
34 import com.att.eelf.configuration.EELFLogger;
35 import com.att.eelf.configuration.EELFManager;
36
37 import org.apache.http.client.methods.CloseableHttpResponse;
38 import org.apache.http.client.methods.HttpPost;
39 import org.apache.http.entity.StringEntity;
40 import org.openecomp.appc.adapter.message.Producer;
41
42 public class HttpDmaapProducerImpl extends CommonHttpClient implements Producer {
43
44     private static final EELFLogger LOG = EELFManager.getInstance().getLogger(HttpDmaapProducerImpl.class);
45
46     private static final String CONTENT_TYPE = "application/cambria";
47     private static final String URL_TEMPLATE = "%s/events/%s";
48
49     private List<String> hosts;
50     private Set<String> topics;
51
52     private boolean useHttps = false;
53
54     public HttpDmaapProducerImpl(Collection<String> urls, String topicName) {
55         hosts = new ArrayList<String>();
56         topics = new HashSet<String>();
57         topics.add(topicName);
58
59         for (String host : urls) {
60             hosts.add(formatHostString(host));
61         }
62     }
63
64     public HttpDmaapProducerImpl(Collection<String> urls, Set<String> topicNames) {
65         hosts = new ArrayList<String>();
66         topics = topicNames;
67
68         for (String host : urls) {
69             hosts.add(formatHostString(host));
70         }
71     }
72
73     @Override
74     public void updateCredentials(String user, String pass) {
75         LOG.debug(String.format("Setting auth to %s for %s", user, this.toString()));
76         this.setBasicAuth(user, pass);
77     }
78
79     @Override
80     public boolean post(String partition, String data) {
81         int sent = 0;
82         try {
83             HttpPost request = postReq(null);
84             request.setHeader("Content-Type", CONTENT_TYPE);
85             request.setEntity(new StringEntity(bodyLine(partition, data)));
86
87             for (String topic : topics) {
88                 String uriStr = String.format(URL_TEMPLATE, hosts.get(0), topic);
89                 try {
90                     request.setURI(new URI(uriStr));
91                     CloseableHttpResponse response = getClient().execute(request);
92                     if (response.getStatusLine().getStatusCode() == 200) {
93                         sent++;
94                     }
95                     response.close();
96                 } catch (Exception sendEx) {
97                     LOG.error(String.format("Failed to send message to %s. Reason: %s", uriStr, sendEx.getMessage()),
98                         sendEx);
99                     if (hosts.size() > 1) {
100                         String failedUrl = hosts.remove(0);
101                         hosts.add(failedUrl);
102                         LOG.debug(String.format("Moving host %s to the end of the pool. New primary host is %s",
103                             failedUrl, hosts.get(0)));
104                     }
105                 }
106             }
107         } catch (Exception buildEx) {
108             LOG.error(
109                 String.format("Failed to build request with string [%s]. Message not sent to any topic. Reason: %s",
110                     data, buildEx.getMessage()),
111                 buildEx);
112         }
113         return sent == topics.size();
114     }
115
116     @Override
117     public void useHttps(boolean yes) {
118         useHttps = yes;
119     }
120
121     /**
122      * Format the body for the application/cambria content type with no partitioning.
123      *
124      * @param msg
125      *            The message body to format
126      * @return A string in the application/cambria content type
127      */
128     private String bodyLine(String partition, String msg) {
129         String p = (partition == null) ? "" : partition;
130         String m = (msg == null) ? "" : msg;
131         return String.format("%d.%d.%s%s", p.length(), m.length(), p, m);
132     }
133
134         @Override
135         public void close() {
136                 // Nothing to do                
137         }
138 }