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