aboutsummaryrefslogtreecommitdiffstats
path: root/ransim/ransimctrlr/RANSIM-CTRLR/src/main/java/org/onap/ransim/rest/client/RestClient.java
blob: cee94df715a70f8ac41b8b62924ac00ed4c7f837 (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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/*-
 * ============LICENSE_START=======================================================
 * Ran Simulator Controller
 * ================================================================================
 * Copyright (C) 2020 Wipro Limited.
 * ================================================================================
 * 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.onap.ransim.rest.client;

import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.eclipse.persistence.internal.oxm.conversion.Base64;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import javax.net.ssl.HttpsURLConnection;
import java.net.URL;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import org.slf4j.LoggerFactory;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.net.ssl.*;
import java.io.*;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import org.apache.http.client.HttpClient;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.apache.http.impl.client.HttpClientBuilder;

public class RestClient {

private static class NullHostnameVerifier implements HostnameVerifier {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        }
 private static class SavingTrustManager implements X509TrustManager {

        private final X509TrustManager tm;
        private X509Certificate[] chain;

        SavingTrustManager(X509TrustManager tm) {
            this.tm = tm;
        }

        public X509Certificate[] getAcceptedIssuers() {

            return new X509Certificate[0];
           
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            throw new UnsupportedOperationException();
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
            this.chain = chain;
            tm.checkServerTrusted(chain, authType);
        }
    }

    static Logger log = Logger.getLogger(RestClient.class.getName());

    HttpHeaders createHeaders(String username, String password) {
        return new HttpHeaders() {
            {
                String auth = username + ":" + password;
                byte[] encodedAuth = Base64.base64Encode(auth.getBytes(Charset.forName("US-ASCII")));

                String authHeader = "Basic " + new String(encodedAuth);
                set("Authorization", authHeader);
                set("Content-Type", "application/xml");
                set("Accept", "application/xml");
            }
        };
    }

    /**
     * Sends mount request to sdnr.
     *
     * @param serverId
     *            netconf server id name
     * @param ip
     *            server ip address
     * @param port
     *            port number
     * @param agentIp
     *            agent ip address
     * @param agentPort
     *            agent port number
     * @param agentUsername
     *            agent username
     * @param agentPassword
     *            agent password
     * @return returns the message to be passed
     */
      
         public String sendMountRequestToSdnr(String serverId, String ip, int port, String agentIp, String agentPort,
            String agentUsername, String agentPassword) {


       ResponseEntity<String> result=null;
       try{          
        String requestBody = "<node xmlns=\"urn:TBD:params:xml:ns:yang:network-topology\">    <node-id> " + serverId + " </node-id>    <username xmlns=\"urn:opendaylight:netconf-node-topology\">admin</username>    <password xmlns=\"urn:opendaylight:netconf-node-topology\">admin</password>    <host xmlns=\"urn:opendaylight:netconf-node-topology\">" + agentIp + "</host>    <schema-cache-directory xmlns=\"urn:opendaylight:netconf-node-topology\">" + serverId + "</schema-cache-directory>    <port xmlns=\"urn:opendaylight:netconf-node-topology\">" + agentPort + "</port>    <tcp-only xmlns=\"urn:opendaylight:netconf-node-topology\">false</tcp-only>    <schemaless xmlns=\"urn:opendaylight:netconf-node-topology\">false</schemaless>    <max-connection-attempts xmlns=\"urn:opendaylight:netconf-node-topology\">0</max-connection-attempts>    <connection-timeout-millis xmlns=\"urn:opendaylight:netconf-node-topology\">20000</connection-timeout-millis>    <default-request-timeout-millis xmlns=\"urn:opendaylight:netconf-node-topology\">60000</default-request-timeout-millis>    <sleep-factor xmlns=\"urn:opendaylight:netconf-node-topology\">1.1</sleep-factor>    <between-attempts-timeout-millis xmlns=\"urn:opendaylight:netconf-node-topology\">2000</between-attempts-timeout-millis>    <reconnect-on-changed-schema xmlns=\"urn:opendaylight:netconf-node-topology\">false</reconnect-on-changed-schema>    <keepalive-delay xmlns=\"urn:opendaylight:netconf-node-topology\">60</keepalive-delay>    <concurrent-rpc-limit xmlns=\"urn:opendaylight:netconf-node-topology\">0</concurrent-rpc-limit>    <actor-response-wait-time xmlns=\"urn:opendaylight:netconf-node-topology\">60</actor-response-wait-time></node>";


    
          String response = "";
        HttpsURLConnection connection = null;
        BufferedReader br = null;
        log.info("Change in  http to https");
         char[] passphrase;
                 String p ="changeit";
                 passphrase = p.toCharArray();
            File file = new File("jssecacerts");
         if (file.isFile() == false) {
             char SEP = File.separatorChar;
             File dir = new File( SEP
                     + "tmp" + SEP +"ransim-install"+ SEP + "config");
             file = new File(dir, "jssecacerts");
         }
         log.info("Loading new  KeyStores" + file + "...");
         InputStream in = new FileInputStream(file);
         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
         ks.load(in, passphrase);
         in.close();
         SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
              new SSLContextBuilder()
                .loadTrustMaterial(null, new TrustSelfSignedStrategy())
                .loadKeyMaterial(ks, passphrase)
                .build(),
                NoopHostnameVerifier.INSTANCE);

            HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(
              socketFactory).build();

            ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
              httpClient);

         SSLContext context = SSLContext.getInstance("TLS");
         TrustManagerFactory tmf =
                 TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
         tmf.init(ks);
         X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
         SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
         context.init(null, new TrustManager[]{tm}, null);

         SSLContext.setDefault(context);
         SSLSocketFactory factory = context.getSocketFactory();

         log.info("Using Authorization");

         SSLSocket socket = (SSLSocket) factory.createSocket(ip,port);
         socket.setSoTimeout(10000);

        try{
            socket.startHandshake();
        }
        catch (SSLException e) {
        
            log.error("Exc insocket handshake", e);

        }

     log.info("Started SSL handshake without hostname verifier...");
             
     RestTemplate restTemplate = new RestTemplate(requestFactory);
     HttpClientBuilder httpClientBuilder = HttpClients.custom()
                     .setSSLContext(SSLContext.getDefault())
                     .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)    
             .useSystemProperties();

     restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build()));


    HttpHeaders headers = createHeaders(agentUsername, agentPassword);

        log.info("request : " + requestBody);
        log.info("headers : " + headers);
        for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
            log.info("Key:" + entry.getKey() + "  , Value:" + entry.getValue());
        }
        String url = "https://" + ip + ":" + port
                + "/restconf/config/network-topology:network-topology/topology/topology-netconf/node/" + serverId;
        

        HttpEntity<String> entity = new HttpEntity<String>(requestBody, headers);
        result = restTemplate.exchange(url, HttpMethod.PUT, entity, String.class);

        log.info("Request sent, result: " + result);
        socket.close();
            }
    catch (SSLException e) {
         System.out.println();
         e.printStackTrace(System.out);
     }

     catch (Exception e) {

         log.error("Exc in post {}", e);
     }
     return result.toString();
    }

    /**
     * Sends an unmount request to sdnr.
     *
     * @param serverId
     *            netconf server id name
     * @param ip
     *            ip address
     * @param port
     *            port number
     * @param sdnrUsername
     *            sdnr username
     * @param sdnrPassword
     *            sdnr password
     * @return returns the message to be passed
     */
    public String sendUnmountRequestToSdnr(String serverId, String ip, int port, String sdnrUsername,
            String sdnrPassword) {
        String url = "http://" + ip + ":" + port
                + "/restconf/config/network-topology:network-topology/topology/topology-netconf/node/" + serverId;
        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = createHeaders(sdnrUsername, sdnrPassword);
        HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
        ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.DELETE, entity, String.class);
        log.info("request sent, result: " + result);
        return result.toString();
    }
}