d317e56ac89840f9db7b551cc388355599c1b327
[nonrtric.git] / sdnc-a1-controller / northbound / nonrt-ric-api / provider / src / main / java / org / o_ran_sc / nonrtric / sdnc_a1 / northbound / restadapter / RestAdapterImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.o_ran_sc.nonrtric.sdnc_a1.northbound.restadapter;
22
23 import java.io.FileNotFoundException;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.net.MalformedURLException;
27 import java.net.URL;
28 import java.security.KeyManagementException;
29 import java.security.KeyStoreException;
30 import java.security.NoSuchAlgorithmException;
31 import java.security.UnrecoverableKeyException;
32 import java.security.cert.CertificateException;
33 import java.util.Properties;
34 import org.apache.http.client.HttpClient;
35 import org.apache.http.conn.ssl.NoopHostnameVerifier;
36 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
37 import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
38 import org.apache.http.impl.client.HttpClients;
39 import org.apache.http.ssl.SSLContexts;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.springframework.http.HttpEntity;
43 import org.springframework.http.HttpHeaders;
44 import org.springframework.http.HttpMethod;
45 import org.springframework.http.HttpStatus;
46 import org.springframework.http.MediaType;
47 import org.springframework.http.ResponseEntity;
48 import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
49 import org.springframework.util.ResourceUtils;
50 import org.springframework.web.client.RestTemplate;
51
52 /**
53  * This class provides the Generic Rest Adapter interface to the RestTemplate
54  *
55  * @author lathishbabu.ganesan@est.tech
56  *
57  */
58
59 public class RestAdapterImpl implements RestAdapter {
60
61   private static final String PROPERTIES_FILE = "nonrt-ric-api-provider.properties";
62   private final Logger log = LoggerFactory.getLogger(RestAdapterImpl.class);
63
64   private RestTemplate restTemplateHttp;
65   private RestTemplate restTemplateHttps;
66
67   public RestAdapterImpl() {
68       restTemplateHttp = new RestTemplate();
69       try {
70           restTemplateHttps = createRestTemplateForHttps();
71       } catch (IOException | UnrecoverableKeyException | KeyManagementException | CertificateException
72               | NoSuchAlgorithmException | KeyStoreException ex) {
73         log.error("Caught exception when trying to create restTemplateHttps: {}", ex.getMessage());
74       }
75   }
76
77   private RestTemplate createRestTemplateForHttps() throws IOException, UnrecoverableKeyException, CertificateException,
78               NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
79       InputStream inputStream = RestAdapterImpl.class.getClassLoader().getResourceAsStream(PROPERTIES_FILE);
80       if (inputStream == null) {
81           throw new FileNotFoundException("properties file not found in classpath");
82       } else {
83           Properties properties = new Properties();
84           properties.load(inputStream);
85           final String keystorePassword = properties.getProperty("key-store-password");
86           SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(
87                   SSLContexts.custom()
88                              .loadKeyMaterial(ResourceUtils.getFile(properties.getProperty("key-store")),
89                                      keystorePassword.toCharArray(), keystorePassword.toCharArray())
90                              .loadTrustMaterial(null, new TrustSelfSignedStrategy())
91                              .build(),
92                   NoopHostnameVerifier.INSTANCE);
93           HttpClient client = HttpClients.custom().setSSLSocketFactory(scsf).build();
94           HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
95           requestFactory.setHttpClient(client);
96           inputStream.close();
97           return new RestTemplate(requestFactory);
98       }
99   }
100
101   private HttpEntity<?> getHttpEntity(final Object object) {
102     return new HttpEntity<>(object);
103   }
104
105   @Override
106   public <T> ResponseEntity<T> get(String uri, Class<?> clazz) {
107     HttpEntity<?> entity = getHttpEntity(null);
108     return invokeHttpRequest(uri, HttpMethod.GET, clazz, entity);
109   }
110
111   @Override
112   public <T> ResponseEntity<T> put(String uri, String body, Class<T> clazz) {
113     HttpHeaders headers = new HttpHeaders();
114     headers.setContentType(MediaType.APPLICATION_JSON);
115     HttpEntity<String> entity = new HttpEntity<>(body, headers);
116     return invokeHttpRequest(uri, HttpMethod.PUT, clazz, entity);
117   }
118
119   @Override
120   public <T> ResponseEntity<T> delete(String uri) {
121     HttpEntity<?> entity = getHttpEntity(null);
122     return invokeHttpRequest(uri, HttpMethod.DELETE, null, entity);
123   }
124
125   @SuppressWarnings("unchecked")
126   private <T> ResponseEntity<T> invokeHttpRequest(String uri, HttpMethod httpMethod, Class<?> clazz,
127       HttpEntity<?> entity) {
128     try {
129         URL url = new URL(uri);
130         if (url.getProtocol().equals("https")) {
131             return (ResponseEntity<T>) restTemplateHttps.exchange(uri, httpMethod, entity, clazz);
132         } else if (url.getProtocol().equals("http")) {
133             return (ResponseEntity<T>) restTemplateHttp.exchange(uri, httpMethod, entity, clazz);
134         } else {
135             log.error("Invalid protocol in URL");
136             return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
137         }
138     } catch (MalformedURLException ex) {
139         log.error("URL is not valid, exception: {}", ex.getMessage());
140         return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
141     }
142   }
143 }