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