Fixes in "appc-dmaap-adapter-bundle"
[appc.git] / appc-adapters / appc-dmaap-adapter / appc-dmaap-adapter-bundle / src / main / java / org / onap / appc / adapter / messaging / dmaap / http / HttpDmaapConsumerImpl.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.onap.appc.adapter.messaging.dmaap.http;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import java.io.IOException;
30 import java.net.URI;
31 import java.util.ArrayList;
32 import java.util.Collection;
33 import java.util.List;
34 import org.apache.http.HttpEntity;
35 import org.apache.http.NameValuePair;
36 import org.apache.http.client.methods.CloseableHttpResponse;
37 import org.apache.http.client.methods.HttpGet;
38 import org.apache.http.client.utils.URIBuilder;
39 import org.apache.http.message.BasicNameValuePair;
40 import org.apache.http.util.EntityUtils;
41 import org.json.JSONArray;
42 import org.onap.appc.adapter.message.Consumer;
43
44 public class HttpDmaapConsumerImpl extends CommonHttpClient implements Consumer {
45
46     private static final EELFLogger LOG = EELFManager.getInstance().getLogger(HttpDmaapConsumerImpl.class);
47
48     // Default values
49     private static final int DEFAULT_TIMEOUT_MS = 15000;
50     private static final int DEFAULT_LIMIT = 1000;
51     private static final String URL_TEMPLATE = "%s/events/%s/%s/%s";
52
53     private List<String> urls;
54     private String filter;
55
56     public HttpDmaapConsumerImpl(Collection<String> hosts, String topicName, String consumerName, String consumerId,
57                                  String filter) {
58
59         this(hosts, topicName, consumerName, consumerId, filter, null, null);
60     }
61
62     public HttpDmaapConsumerImpl(Collection<String> hosts, String topicName, String consumerName, String consumerId,
63                                  String filter, String user, String password) {
64
65         urls = new ArrayList<>();
66         for (String host : hosts) {
67             urls.add(String.format(URL_TEMPLATE, formatHostString(host), topicName, consumerName, consumerId));
68         }
69         this.filter = filter;
70         updateCredentials(user, password);
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 List<String> fetch(int waitMs, int limit) {
81         LOG.debug(String.format("Fetching up to %d records with %dms wait on %s", limit, waitMs, this.toString()));
82         List<String> out = new ArrayList<>();
83         try {
84             List<NameValuePair> urlParams = new ArrayList<>();
85             urlParams.add(new BasicNameValuePair("timeout", String.valueOf(waitMs)));
86             urlParams.add(new BasicNameValuePair("limit", String.valueOf(limit)));
87             if (filter != null) {
88                 urlParams.add(new BasicNameValuePair("filter", filter));
89             }
90
91             URIBuilder builder = new URIBuilder(urls.get(0));
92             builder.setParameters(urlParams);
93
94             URI uri = builder.build();
95             LOG.info(String.format("GET %s", uri));
96             HttpGet request = getReq(uri, waitMs);
97             CloseableHttpResponse response = getClient().execute(request);
98
99             int httpStatus = response.getStatusLine().getStatusCode();
100             HttpEntity entity = response.getEntity();
101             String body = (entity != null) ? entityToString(entity) : null;
102
103             LOG.debug(String.format("Request to %s completed with status %d and a body size of %s", uri, httpStatus,
104                 body != null ? body.length() : "null"));
105
106             response.close();
107             if (httpStatus == 200 && body != null) {
108                 JSONArray json = new JSONArray(body);
109                 LOG.info(String.format("Got %d messages from DMaaP", json.length()));
110                 for (int i = 0; i < json.length(); i++) {
111                     out.add(json.getString(i));
112                 }
113             } else {
114                 LOG.error(String.format("Did not get 200 from DMaaP. Got %d - %s", httpStatus, body));
115                 sleep(waitMs);
116             }
117         } catch (Exception e) {
118             if (urls.size() > 1) {
119                 String failedUrl = urls.remove(0);
120                 urls.add(failedUrl);
121                 LOG.debug(String.format("Moving host %s to the end of the pool. New primary host is %s", failedUrl,
122                     urls.get(0)));
123             }
124             LOG.error(String.format("Got exception while querying DMaaP. Message: %s", e.getMessage()), e);
125             sleep(waitMs);
126         }
127         return out;
128     }
129
130     @Override
131     public List<String> fetch() {
132         return fetch(DEFAULT_TIMEOUT_MS, DEFAULT_LIMIT);
133     }
134
135     @Override
136     public String toString() {
137         String hostStr = (urls == null || urls.isEmpty()) ? "N/A" : urls.get(0);
138         return String.format("Consumer listening to [%s]", hostStr);
139     }
140
141     String entityToString(HttpEntity entity) throws IOException {
142         return EntityUtils.toString(entity);
143     }
144
145     private void sleep(int ms) {
146         LOG.info(String.format("Sleeping for %ds after failed request", ms / 1000));
147         try {
148             Thread.sleep(ms);
149         } catch (InterruptedException e1) {
150             LOG.error("Interrupted while sleeping", e1);
151             Thread.currentThread().interrupt();
152         }
153     }
154
155 }