Merge "DG changes for the closed loop and async support in MDONS"
[sdnc/oam.git] / data-migrator / src / main / java / org / onap / sdnc / oam / datamigrator / common / RestconfClient.java
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP : SDNC
4  * ================================================================================
5  * Copyright 2019 AMDOCS
6  *=================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 package org.onap.sdnc.oam.datamigrator.common;
21
22 import com.google.gson.JsonObject;
23 import com.google.gson.JsonParser;
24 import org.onap.sdnc.oam.datamigrator.exceptions.RestconfException;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 import javax.net.ssl.HostnameVerifier;
29 import javax.net.ssl.HttpsURLConnection;
30 import java.io.BufferedReader;
31 import java.io.DataOutputStream;
32 import java.io.IOException;
33 import java.io.InputStreamReader;
34 import java.net.Authenticator;
35 import java.net.HttpURLConnection;
36 import java.net.PasswordAuthentication;
37 import java.net.URL;
38 import java.util.Base64;
39
40 public class RestconfClient {
41
42     private HttpURLConnection httpConn = null;
43     private final String host ;
44     private final String user ;
45     private final String password ;
46     private static final String CONFIG_PATH = "/restconf/config/";
47     private static final String CONTENT_TYPE_JSON = "application/json";
48     private final Logger log = LoggerFactory.getLogger(RestconfClient.class);
49
50     public RestconfClient (String host , String user , String password){
51         this.host = host;
52         this.user = user;
53         this.password = password;
54     }
55
56     private class SdncAuthenticator extends Authenticator {
57
58         private final String user;
59         private final String passwd;
60
61         SdncAuthenticator(String user, String passwd) {
62             this.user = user;
63             this.passwd = passwd;
64         }
65         @Override
66         protected PasswordAuthentication getPasswordAuthentication() {
67             return new PasswordAuthentication(user, passwd.toCharArray());
68         }
69     }
70
71     public JsonObject get(String path) throws RestconfException {
72             String getResponse = send(path,"GET",CONTENT_TYPE_JSON,"");
73             JsonParser parser = new JsonParser();
74             return parser.parse(getResponse).getAsJsonObject();
75     }
76
77     public void put(String path, String data) throws RestconfException {
78             send(path,"PUT",CONTENT_TYPE_JSON, data );
79     }
80
81     private String send(String path,String method, String contentType, String msg) throws RestconfException {
82         Authenticator.setDefault(new SdncAuthenticator(user, password));
83         String url = host + CONFIG_PATH + path;
84         try {
85             URL sdncUrl = new URL(url);
86             log.info("SDNC url: " + url);
87             log.info("Method: " + method);
88             this.httpConn = (HttpURLConnection) sdncUrl.openConnection();
89             String authStr = user + ":" + password;
90             String encodedAuthStr = new String(Base64.getEncoder().encode(authStr.getBytes()));
91             httpConn.addRequestProperty("Authentication", "Basic " + encodedAuthStr);
92
93             httpConn.setRequestMethod(method);
94             httpConn.setRequestProperty("Content-Type", contentType);
95             httpConn.setRequestProperty("Accept", contentType);
96
97             httpConn.setDoInput(true);
98             httpConn.setDoOutput(true);
99             httpConn.setUseCaches(false);
100
101             if (httpConn instanceof HttpsURLConnection) {
102                 HostnameVerifier hostnameVerifier = (hostname, session) -> true;
103                 ((HttpsURLConnection) httpConn).setHostnameVerifier(hostnameVerifier);
104             }
105             if (!method.equals("GET")) {
106                 log.info("Request payload: " + msg);
107                 httpConn.setRequestProperty("Content-Length", "" + msg.length());
108                 DataOutputStream outStr = new DataOutputStream(httpConn.getOutputStream());
109                 outStr.write(msg.getBytes());
110                 outStr.close();
111             }
112
113             BufferedReader respRdr;
114             log.info("Response: " + httpConn.getResponseCode() + " " + httpConn.getResponseMessage());
115
116             if (httpConn.getResponseCode() < 300) {
117                 respRdr = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
118             } else {
119                 respRdr = new BufferedReader(new InputStreamReader(httpConn.getErrorStream()));
120                 log.error("Error during restconf operation: "+ method + ". URL:" + sdncUrl.toString()+". Response:"+respRdr);
121                 throw new RestconfException(httpConn.getResponseCode(),"Error during restconf operation: "+ method +". Response:"+respRdr);
122             }
123
124             StringBuilder respBuff = new StringBuilder();
125             String respLn;
126             while ((respLn = respRdr.readLine()) != null) {
127                 respBuff.append(respLn).append("\n");
128             }
129             respRdr.close();
130             String respString = respBuff.toString();
131
132             log.info("Response body :\n" + respString);
133             return respString;
134         }catch (IOException e){
135             throw new RestconfException(500,e.getMessage(),e);
136         }finally {
137             if (httpConn != null) {
138                 httpConn.disconnect();
139             }
140         }
141     }
142
143
144 }