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