ebddc24ae8d6a6f7f0d2016e1ea4a2cbc4999bca
[ccsdk/sli.git] /
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.onap.ccsdk.sli.adaptors.resource.mdsal;
23
24 import org.apache.commons.codec.binary.Base64;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27 import org.w3c.dom.Document;
28
29 import javax.net.ssl.HostnameVerifier;
30 import javax.net.ssl.HttpsURLConnection;
31 import javax.xml.XMLConstants;
32 import javax.xml.parsers.DocumentBuilder;
33 import javax.xml.parsers.DocumentBuilderFactory;
34 import java.io.*;
35 import java.net.Authenticator;
36 import java.net.HttpURLConnection;
37 import java.net.PasswordAuthentication;
38 import java.net.URL;
39
40 public class RestService {
41
42     private static final Logger LOG = LoggerFactory.getLogger(ConfigResource.class);
43     private String user;
44     private String passwd;
45     private String contentType;
46     private String accept;
47     private String protocol;
48     private String host;
49     private String port;
50
51     public RestService(String protocol, String host, String port, String user, String passwd, String accept, String contentType) {
52         this.protocol = protocol;
53         this.host = host;
54         this.port = port;
55         this.user = user;
56         this.passwd = passwd;
57         this.accept = accept;
58         this.contentType = contentType;
59     }
60
61     private HttpURLConnection getRestConnection(String urlString, String method) throws IOException {
62         URL sdncUrl = new URL(urlString);
63         Authenticator.setDefault(new SdncAuthenticator(user, passwd));
64
65         String authStr = user + ":" + passwd;
66         String encodedAuthStr = new String(Base64.encodeBase64(authStr.getBytes()));
67
68         HttpURLConnection conn = (HttpURLConnection) sdncUrl.openConnection();
69         conn.addRequestProperty("Authentication", "Basic " + encodedAuthStr);
70         conn.setRequestMethod(method);
71         conn.setDoInput(true);
72         conn.setDoOutput(true);
73         conn.setUseCaches(false);
74
75         //Setting Accept header (doesn't dependent on Msg Body if present or not)
76         if ("XML".equalsIgnoreCase(accept)) {
77             conn.setRequestProperty("Accept", "application/xml");
78         } else {
79             conn.setRequestProperty("Accept", "application/json");
80         }
81
82         return (conn);
83     }
84
85     private Document send(String urlString, byte[] msgBytes, String method) {
86         Document response = null;
87         String fullUrl = protocol + "://" + host + ":" + port + "/" + urlString;
88         LOG.info("Sending REST {} to {}", method, fullUrl);
89
90         try {
91             HttpURLConnection conn = getRestConnection(fullUrl, method);
92             if (conn instanceof HttpsURLConnection) {
93                 HostnameVerifier hostnameVerifier = (hostname, session) -> true;
94                 ((HttpsURLConnection) conn).setHostnameVerifier(hostnameVerifier);
95             }
96
97             // Write message
98             if (msgBytes != null) {
99                 LOG.info("Message body:\n{}", msgBytes);
100                 conn.setRequestProperty("Content-Length", "" + msgBytes.length);
101
102                 // Setting Content-Type header only if Msg Body is present
103                 if ("XML".equalsIgnoreCase(contentType)) {
104                     conn.setRequestProperty("Content-Type", "application/xml");
105                 } else {
106                     conn.setRequestProperty("Content-Type", "application/json");
107                 }
108
109                 DataOutputStream outStr = new DataOutputStream(conn.getOutputStream());
110                 outStr.write(msgBytes);
111                 outStr.close();
112             } else {
113                 conn.setRequestProperty("Content-Length", "0");
114             }
115
116             // Read response
117             LOG.info("Response: {} {}", conn.getResponseCode(), conn.getResponseMessage());
118
119             BufferedReader respRdr;
120             if (conn.getResponseCode() < 300) {
121                 respRdr = new BufferedReader(new InputStreamReader(conn.getInputStream()));
122             } else {
123                 respRdr = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
124             }
125
126             StringBuffer respBuff = new StringBuffer();
127             String respLn;
128             while ((respLn = respRdr.readLine()) != null) {
129                 respBuff.append(respLn + "\n");
130             }
131             respRdr.close();
132
133             String respString = respBuff.toString();
134             LOG.info("Response body :\n{}", respString);
135
136             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
137             dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);  
138             dbf.setFeature("http://xml.org/sax/features/external-general-entities", false); 
139             dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
140             DocumentBuilder db = dbf.newDocumentBuilder();
141
142             response = db.parse(new ByteArrayInputStream(respString.getBytes()));
143
144         } catch (Exception e) {
145             LOG.error("Caught exception executing REST command", e);
146         }
147
148         return (response);
149     }
150
151     public Document get(String urlString) {
152         return (send(urlString, null, "GET"));
153     }
154
155     public Document delete(String urlString) {
156         return (send(urlString, null, "DELETE"));
157     }
158
159     public Document post(String urlString, byte[] msgBytes) {
160         return (send(urlString, msgBytes, "POST"));
161     }
162
163     public Document put(String urlString, byte[] msgBytes) {
164         return (send(urlString, msgBytes, "PUT"));
165     }
166
167
168     private class SdncAuthenticator extends Authenticator {
169         private String user;
170         private String passwd;
171
172         SdncAuthenticator(String user, String passwd) {
173             this.user = user;
174             this.passwd = passwd;
175         }
176
177         @Override
178         protected PasswordAuthentication getPasswordAuthentication() {
179             return new PasswordAuthentication(user, passwd.toCharArray());
180         }
181
182     }
183
184 }