aboutsummaryrefslogtreecommitdiffstats
path: root/mdsal-resource/provider/src/main/java/org/openecomp/sdnc/sli/resource/mdsal/RestService.java
blob: a8e78c0b8684b92e86947fc686ca48f694aec953 (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
212
213
/*-
 * ============LICENSE_START=======================================================
 * openECOMP : SDN-C
 * ================================================================================
 * Copyright (C) 2017 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.openecomp.sdnc.sli.resource.mdsal;

import java.io.BufferedReader;

import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;




public class RestService {
	
	private static final Logger LOG = LoggerFactory.getLogger(ConfigResource.class);
	
	public enum PayloadType {
		XML,
		JSON
	}
	
	private class SdncAuthenticator extends Authenticator {
		
		private String user;
		private String passwd;

		SdncAuthenticator(String user, String passwd) {
			this.user = user;
			this.passwd = passwd;
		}
		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(user, passwd.toCharArray());
		}
		
	}
	
	private String user;
	private String passwd;
	private PayloadType payloadType;

	private String protocol;
	private String host;
	private String port;
	
	public RestService(String protocol, String host, String port, String user, String passwd, PayloadType payloadType) {
		this.protocol = protocol;
		this.host = host;
		this.port = port;
		this.user = user;
		this.passwd = passwd;
		this.payloadType = payloadType;
	}
	
	private HttpURLConnection getRestConnection(String urlString, String method) throws IOException
	{
		
		URL sdncUrl = new URL(urlString);
		Authenticator.setDefault(new SdncAuthenticator(user, passwd));
		
		HttpURLConnection conn = (HttpURLConnection) sdncUrl.openConnection();
		
		String authStr = user+":"+passwd;
		String encodedAuthStr = new String(Base64.encodeBase64(authStr.getBytes()));
		
		conn.addRequestProperty("Authentication", "Basic "+encodedAuthStr);
		
		conn.setRequestMethod(method);
		
		if (payloadType == PayloadType.XML) {
			conn.setRequestProperty("Content-Type", "application/xml");
			conn.setRequestProperty("Accept", "application/xml");
		} else {

			conn.setRequestProperty("Content-Type", "application/json");
			conn.setRequestProperty("Accept", "application/json");
		}
		
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		
		return(conn);
		
	}
	

	private Document send(String urlString, byte[] msgBytes, String method) {
		Document response = null;
		String fullUrl = protocol + "://" + host + ":" + port + "/" + urlString;
		LOG.info("Sending REST "+method +" to "+fullUrl);
		
		if (msgBytes != null) {
			LOG.info("Message body:\n"+msgBytes);
		}
		
		try {
			HttpURLConnection conn = getRestConnection(fullUrl, method);

			if (conn instanceof HttpsURLConnection) {
				HostnameVerifier hostnameVerifier = new HostnameVerifier() {
					@Override
					public boolean verify(String hostname, SSLSession session) {
						return true;
					}
				};
				((HttpsURLConnection)conn).setHostnameVerifier(hostnameVerifier);
			}

			// Write message
			if (msgBytes != null) {
				conn.setRequestProperty("Content-Length", ""+msgBytes.length);
				DataOutputStream outStr = new DataOutputStream(conn.getOutputStream());
				outStr.write(msgBytes);
				outStr.close();
			} else {
				conn.setRequestProperty("Content-Length", "0");
			}


			// Read response
			BufferedReader respRdr;
			
			LOG.info("Response: "+conn.getResponseCode()+" "+conn.getResponseMessage());
			

			if (conn.getResponseCode() < 300) {

				respRdr = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			} else {
				respRdr = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
			}

			StringBuffer respBuff = new StringBuffer();

			String respLn;

			while ((respLn = respRdr.readLine()) != null) {
				respBuff.append(respLn+"\n");
			}
			respRdr.close();

			String respString = respBuff.toString();

			LOG.info("Response body :\n"+respString);

			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();


			response = db.parse(new ByteArrayInputStream(respString.getBytes()));

		} catch (Exception e) {

			LOG.error("Caught exception executing REST command", e);
		}
		
		return (response);
	}

	
	public Document get(String urlString) {
		return(send(urlString, null, "GET"));
	}
	
	public Document delete(String urlString) {
		return(send(urlString, null, "DELETE"));
	}
	
	public Document post(String urlString, byte[] msgBytes) {
		return(send(urlString, msgBytes, "POST"));
	}

	public Document put(String urlString, byte[] msgBytes) {
		return(send(urlString, msgBytes, "PUT"));
	}
}