summaryrefslogtreecommitdiffstats
path: root/message-router/publisher/provider/src/main/java/org/onap/ccsdk/sli/adaptors/messagerouter/publisher/provider/impl/PublisherApiImpl.java
blob: 4aedc6071ef15f7ffe8dc861a95e073732315f50 (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
/**
 * ============LICENSE_START====================================================
 * org.onap.aaf
 * ===========================================================================
 * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
 *
 * Modifications Copyright (C) 2019 IBM.
 * ===========================================================================
 * 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.adaptors.messagerouter.publisher.provider.impl;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.URL;
import java.util.Base64;

import org.onap.ccsdk.sli.adaptors.messagerouter.publisher.api.PublisherApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PublisherApiImpl implements PublisherApi {
	private static final Logger logger = LoggerFactory.getLogger(PublisherApiImpl.class);
	protected static final Integer DEFAULT_CONNECT_TIMEOUT = 30000; // will be treated as 30 seconds
	protected static final Integer DEFAULT_READ_TIMEOUT = 180000; // will be treated as 3 minutes
	private String authorizationString;
	protected Integer connectTimeout;
	protected Integer readTimeout;
	protected String baseUrl;
	protected String username;
	protected String[] hosts;
	private String password;

	public PublisherApiImpl() {
		connectTimeout = DEFAULT_CONNECT_TIMEOUT;
		readTimeout = DEFAULT_READ_TIMEOUT;
	}

	public void setUsername(String username) {
		this.username = username;
		setAuthorizationString();
	}

	public void setPassword(String password) {
		this.password = password;
		setAuthorizationString();
	}

	public void setHost(String hostString) {
		// a comma separated list of hosts can be passed in or a single host may be used
		if (!hostString.contains(",")) {
			this.hosts = new String[] { hostString };
		} else {
			this.hosts = hostString.split(",");
		}
	}

	public void init() {
		setAuthorizationString();
	}

	protected String buildUrlString(Integer hostIndex, String topic) {
		return hosts[hostIndex] + "/events/" + topic;
	}

	protected void configureHttpURLConnection(HttpURLConnection httpUrlConnection) {
		httpUrlConnection.setRequestProperty("Content-Type", "application/json");
	}

	public Boolean publish(String topic, String body) {
		for (int hostIndex = 0; hostIndex < hosts.length; hostIndex++) {
			HttpURLConnection httpUrlConnection = null;
			URL url = null;
			try {
				url = new URL(buildUrlString(hostIndex, topic));
				logger.info("Publishing body to topic {} using the url {}", topic, url);
				logger.info("Message to publish is\n{}", body);
				httpUrlConnection = buildHttpURLConnection(url);
				httpUrlConnection.setDoInput(true);
				httpUrlConnection.setDoOutput(true);
				httpUrlConnection.setUseCaches(false);
				httpUrlConnection.setRequestMethod("POST");

				// Write message
				httpUrlConnection.setRequestProperty("Content-Length", Integer.toString(body.length()));
				DataOutputStream outStr = new DataOutputStream(httpUrlConnection.getOutputStream());
				outStr.write(body.getBytes());
				outStr.close();

				int status = httpUrlConnection.getResponseCode();
				logger.info("Publishing body for topic {} using  url {} returned status {}.", topic, url, status);
				if (status < 300) {
					String responseFromDMaaP = readFromStream(httpUrlConnection.getInputStream());
					logger.info("Message router response is\n{}", responseFromDMaaP);
					return true;
				} else {
					if (httpUrlConnection.getErrorStream() != null) {
						String responseFromDMaaP = readFromStream(httpUrlConnection.getErrorStream());
						logger.warn("Publishing body for topic {} using  url {} failed." + " Error message is\n{}",
								topic, url, responseFromDMaaP);
					}
					return false;
				}

			} catch (SocketException socketException) {
				logger.error("SocketException was thrown during publishing message to DMaaP on url {}.", url,
						socketException);
				if (hostIndex < hosts.length) {
					logger.info("Message sent to {} failed with a SocketException, but will be tried on {}",
							hosts[hostIndex], hosts[hostIndex + 1]);
				}
			} catch (Exception e) {
				logger.warn("Exception was thrown during publishing message to DMaaP on url {}.", url, e);
				return false;
			} finally {
				if (httpUrlConnection != null) {
					httpUrlConnection.disconnect();
				}
			}
		}
		return false;
	}

	protected void setAuthorizationString() {
	    String str = buildAuthorizationString(this.username, this.password);
		this.authorizationString = str;
		//System.out.println(this.authorizationString);
	}
	
         protected String buildAuthorizationString(String username, String password) {
             String basicAuthString = username + ":" + password;
             basicAuthString = Base64.getEncoder().encodeToString(basicAuthString.getBytes());
             return "Basic " + basicAuthString;
        }

	protected HttpURLConnection buildHttpURLConnection(URL url) throws IOException {
		HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
		if (authorizationString != null) {
		    System.out.println(authorizationString);
			httpUrlConnection.setRequestProperty("Authorization", authorizationString);
		}
		httpUrlConnection.setRequestProperty("Accept", "application/json");
		httpUrlConnection.setUseCaches(false);
		httpUrlConnection.setConnectTimeout(connectTimeout);
		httpUrlConnection.setReadTimeout(readTimeout);
		configureHttpURLConnection(httpUrlConnection);
		return httpUrlConnection;
	}

	protected String readFromStream(InputStream stream) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(stream));
		StringBuilder sb = new StringBuilder();
		String line;
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		br.close();
		return sb.toString();
	}

}