Fix license headers
[ccsdk/sli/adaptors.git] / mdsal-resource / provider / src / main / java / org / openecomp / sdnc / sli / resource / mdsal / RestService.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : SDN-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                      reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.openecomp.sdnc.sli.resource.mdsal;
23
24 import java.io.BufferedReader;
25 import java.io.ByteArrayInputStream;
26 import java.io.DataOutputStream;
27 import java.io.IOException;
28 import java.io.InputStreamReader;
29 import java.net.Authenticator;
30 import java.net.HttpURLConnection;
31 import java.net.PasswordAuthentication;
32 import java.net.URL;
33
34 import javax.net.ssl.HostnameVerifier;
35 import javax.net.ssl.HttpsURLConnection;
36 import javax.net.ssl.SSLSession;
37 import javax.xml.parsers.DocumentBuilder;
38 import javax.xml.parsers.DocumentBuilderFactory;
39
40 import org.apache.commons.codec.binary.Base64;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.w3c.dom.Document;
44
45
46
47
48 public class RestService {
49
50     private static final Logger LOG = LoggerFactory.getLogger(ConfigResource.class);
51
52     public enum PayloadType {
53         XML,
54         JSON
55     }
56
57     private class SdncAuthenticator extends Authenticator {
58
59         private String user;
60         private String passwd;
61
62         SdncAuthenticator(String user, String passwd) {
63             this.user = user;
64             this.passwd = passwd;
65         }
66         @Override
67         protected PasswordAuthentication getPasswordAuthentication() {
68             return new PasswordAuthentication(user, passwd.toCharArray());
69         }
70
71     }
72
73     private String user;
74     private String passwd;
75     private PayloadType payloadType;
76
77     private String protocol;
78     private String host;
79     private String port;
80
81     public RestService(String protocol, String host, String port, String user, String passwd, PayloadType payloadType) {
82         this.protocol = protocol;
83         this.host = host;
84         this.port = port;
85         this.user = user;
86         this.passwd = passwd;
87         this.payloadType = payloadType;
88     }
89
90     private HttpURLConnection getRestConnection(String urlString, String method) throws IOException
91     {
92
93         URL sdncUrl = new URL(urlString);
94         Authenticator.setDefault(new SdncAuthenticator(user, passwd));
95
96         HttpURLConnection conn = (HttpURLConnection) sdncUrl.openConnection();
97
98         String authStr = user+":"+passwd;
99         String encodedAuthStr = new String(Base64.encodeBase64(authStr.getBytes()));
100
101         conn.addRequestProperty("Authentication", "Basic "+encodedAuthStr);
102
103         conn.setRequestMethod(method);
104
105         if (payloadType == PayloadType.XML) {
106             conn.setRequestProperty("Content-Type", "application/xml");
107             conn.setRequestProperty("Accept", "application/xml");
108         } else {
109
110             conn.setRequestProperty("Content-Type", "application/json");
111             conn.setRequestProperty("Accept", "application/json");
112         }
113
114         conn.setDoInput(true);
115         conn.setDoOutput(true);
116         conn.setUseCaches(false);
117
118         return(conn);
119
120     }
121
122
123     private Document send(String urlString, byte[] msgBytes, String method) {
124         Document response = null;
125         String fullUrl = protocol + "://" + host + ":" + port + "/" + urlString;
126         LOG.info("Sending REST "+method +" to "+fullUrl);
127
128         if (msgBytes != null) {
129             LOG.info("Message body:\n"+msgBytes);
130         }
131
132         try {
133             HttpURLConnection conn = getRestConnection(fullUrl, method);
134
135             if (conn instanceof HttpsURLConnection) {
136                 HostnameVerifier hostnameVerifier = new HostnameVerifier() {
137                     @Override
138                     public boolean verify(String hostname, SSLSession session) {
139                         return true;
140                     }
141                 };
142                 ((HttpsURLConnection)conn).setHostnameVerifier(hostnameVerifier);
143             }
144
145             // Write message
146             if (msgBytes != null) {
147                 conn.setRequestProperty("Content-Length", ""+msgBytes.length);
148                 DataOutputStream outStr = new DataOutputStream(conn.getOutputStream());
149                 outStr.write(msgBytes);
150                 outStr.close();
151             } else {
152                 conn.setRequestProperty("Content-Length", "0");
153             }
154
155
156             // Read response
157             BufferedReader respRdr;
158
159             LOG.info("Response: "+conn.getResponseCode()+" "+conn.getResponseMessage());
160
161
162             if (conn.getResponseCode() < 300) {
163
164                 respRdr = new BufferedReader(new InputStreamReader(conn.getInputStream()));
165             } else {
166                 respRdr = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
167             }
168
169             StringBuffer respBuff = new StringBuffer();
170
171             String respLn;
172
173             while ((respLn = respRdr.readLine()) != null) {
174                 respBuff.append(respLn+"\n");
175             }
176             respRdr.close();
177
178             String respString = respBuff.toString();
179
180             LOG.info("Response body :\n"+respString);
181
182             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
183             DocumentBuilder db = dbf.newDocumentBuilder();
184
185
186             response = db.parse(new ByteArrayInputStream(respString.getBytes()));
187
188         } catch (Exception e) {
189
190             LOG.error("Caught exception executing REST command", e);
191         }
192
193         return (response);
194     }
195
196
197     public Document get(String urlString) {
198         return(send(urlString, null, "GET"));
199     }
200
201     public Document delete(String urlString) {
202         return(send(urlString, null, "DELETE"));
203     }
204
205     public Document post(String urlString, byte[] msgBytes) {
206         return(send(urlString, msgBytes, "POST"));
207     }
208
209     public Document put(String urlString, byte[] msgBytes) {
210         return(send(urlString, msgBytes, "PUT"));
211     }
212 }