aboutsummaryrefslogtreecommitdiffstats
path: root/dmaap-listener/src/main/java/org/onap/ccsdk/sli/northbound/dmaapclient/MessageRouterHttpClientJdk.java
blob: d720e5fcdabe4782bf0954e7843af2051dd74ea1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
/*-
 * ============LICENSE_START=======================================================
 * openECOMP : SDN-C
 * ================================================================================
 * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights
 * 						reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.ccsdk.sli.northbound.dmaapclient;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.HttpURLConnection;

/*
 * java.net based client to build message router consumers
 */
public class MessageRouterHttpClientJdk implements SdncDmaapConsumer {
    private static final Logger Log = LoggerFactory.getLogger(MessageRouterHttpClientJdk.class);

    protected Boolean isReady = false;
    protected Boolean isRunning = false;
    protected URL url;
    protected Integer fetchPause;
    protected Properties properties;
    protected final String DEFAULT_CONNECT_TIMEOUT = "30000";
    protected final String DEFAULT_READ_TIMEOUT = "180000";
    protected final String DEFAULT_TIMEOUT_QUERY_PARAM_VALUE = "15000";
    protected final String DEFAULT_LIMIT = null;
    private String authorizationString;
    protected Integer connectTimeout;
    protected Integer readTimeout;
    protected String topic;

    public MessageRouterHttpClientJdk() {}

    @Override
    public void run() {
        if (isReady) {
            isRunning = true;
            while (isRunning) {
                HttpURLConnection httpUrlConnection = null;
                try {
                    httpUrlConnection = (HttpURLConnection) url.openConnection();
                    if (authorizationString != null) {
                        httpUrlConnection.addRequestProperty("Authorization", authorizationString);
                    }
                    httpUrlConnection.setRequestMethod("GET");
                    httpUrlConnection.setRequestProperty("Accept", "application/json");
                    httpUrlConnection.setUseCaches(false);
                    httpUrlConnection.setConnectTimeout(connectTimeout);
                    httpUrlConnection.setReadTimeout(readTimeout);
                    httpUrlConnection.connect();
                    int status = httpUrlConnection.getResponseCode();
                    Log.info("GET " + url + " returned http status " + status);
                    if (status < 300) {
                        BufferedReader br =
                                new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
                        StringBuilder sb = new StringBuilder();
                        String line;
                        while ((line = br.readLine()) != null) {
                            sb.append(line + "\n");
                        }
                        br.close();
                        String responseBody = sb.toString();
                        if (responseBody.contains("{")) {
                            // Get rid of opening [" entity =
                            responseBody = responseBody.substring(2);
                            // Get rid of closing "]
                            responseBody = responseBody.substring(0, responseBody.length() - 2);
                            // Split the json array into individual elements to process
                            for (String message : responseBody.split("\",\"")) {
                                // unescape the json
                                message = message.replace("\\\"", "\"");
                                // Topic names cannot contain periods
                                processMsg(message);
                            }
                        } else {
                            Log.info("Entity doesn't appear to contain JSON elements, logging body");
                            Log.info(responseBody);
                        }
                    }
                } catch (Exception e) {
                    Log.error("GET " + url + " failed.", e);
                } finally {
                    if (httpUrlConnection != null) {
                        httpUrlConnection.disconnect();
                    }
                    Log.info("Pausing " + fetchPause + " milliseconds before fetching from " + url + " again.");
                    try {
                        Thread.sleep(fetchPause);
                    } catch (InterruptedException e) {
                        Log.error("Could not sleep thread", e);
                    }
                }
            }
        }
    }

    @Override
    public void init(Properties baseProperties, String consumerPropertiesPath) {
        try {
            baseProperties.load(new FileInputStream(new File(consumerPropertiesPath)));

            this.properties = baseProperties;
            String username = properties.getProperty("username");
            String password = properties.getProperty("password");
            topic = properties.getProperty("topic");
            String group = properties.getProperty("group");
            String host = properties.getProperty("host");
            String id = properties.getProperty("id");

            String filter = properties.getProperty("filter");
            if (filter != null) {
                if (filter.length() > 0) {
                    try {
                        filter = URLEncoder.encode(filter, StandardCharsets.UTF_8.name());
                    } catch (UnsupportedEncodingException e) {
                        Log.error("Couldn't encode filter string", e);
                    }
                } else {
                    filter = null;
                }
            }

            String limitString = properties.getProperty("limit", DEFAULT_LIMIT);
            Integer limit = null;
            if (limitString != null && limitString.length() > 0) {
                limit = Integer.valueOf(limitString);
            }

            Integer timeoutQueryParamValue =
                    Integer.valueOf(properties.getProperty("timeout", DEFAULT_TIMEOUT_QUERY_PARAM_VALUE));
            connectTimeout = Integer.valueOf(properties.getProperty("connectTimeoutSeconds", DEFAULT_CONNECT_TIMEOUT));
            readTimeout = Integer.valueOf(properties.getProperty("readTimeoutMinutes", DEFAULT_READ_TIMEOUT));
            if (username != null && password != null && username.length() > 0 && password.length() > 0) {
                authorizationString = buildAuthorizationString(username, password);
            }
            String urlString = buildlUrlString(topic, group, id, host, timeoutQueryParamValue, limit, filter);
            this.url = new URL(urlString);
            this.fetchPause = Integer.valueOf(properties.getProperty("fetchPause"));
            this.isReady = true;
        } catch (FileNotFoundException e) {
            Log.error("FileNotFoundException while reading consumer properties", e);
        } catch (IOException e) {
            Log.error("IOException while reading consumer properties", e);
        }
    }

    public void processMsg(String msg) {
        Log.info(msg);
    }

    protected String buildAuthorizationString(String userName, String password) {
        String basicAuthString = userName + ":" + password;
        basicAuthString = Base64.getEncoder().encodeToString(basicAuthString.getBytes());
        return "Basic " + basicAuthString;
    }

    protected String buildlUrlString(String topic, String consumerGroup, String consumerId, String host,
            Integer timeout, Integer limit, String filter) {
        StringBuilder sb = new StringBuilder();
        sb.append("http://" + host + "/events/" + topic + "/" + consumerGroup + "/" + consumerId);
        sb.append("?timeout=" + timeout);

        if (limit != null) {
            sb.append("&limit=" + limit);
        }
        if (filter != null) {
            sb.append("&filter=" + filter);
        }
        return sb.toString();
    }

    @Override
    public boolean isReady() {
        return isReady;
    }

    @Override
    public boolean isRunning() {
        return isRunning;
    }

}