create custom spring aop annotation for logging
[so.git] / adapters / mso-nssmf-adapter / src / main / java / org / onap / so / adapters / nssmf / rest / RestUtil.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2020 Huawei Technologies Co., Ltd. All rights reserved.
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
21 package org.onap.so.adapters.nssmf.rest;
22
23 import javax.net.ssl.SSLContext;
24 import javax.net.ssl.TrustManager;
25 import javax.net.ssl.X509TrustManager;
26 import javax.ws.rs.core.UriBuilder;
27 import java.net.SocketTimeoutException;
28 import java.net.URI;
29 import org.apache.http.Header;
30 import org.apache.http.HttpResponse;
31 import org.apache.http.client.HttpClient;
32 import org.apache.http.client.config.RequestConfig;
33 import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
34 import org.apache.http.client.methods.HttpGet;
35 import org.apache.http.client.methods.HttpPost;
36 import org.apache.http.client.methods.HttpPut;
37 import org.apache.http.client.methods.HttpRequestBase;
38 import org.apache.http.conn.ConnectTimeoutException;
39 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
40 import org.apache.http.entity.StringEntity;
41 import org.apache.http.impl.client.HttpClients;
42 import org.apache.http.message.BasicHeader;
43 import org.apache.http.util.EntityUtils;
44 import org.onap.aai.domain.yang.EsrSystemInfo;
45 import org.onap.aai.domain.yang.EsrSystemInfoList;
46 import org.onap.aai.domain.yang.EsrThirdpartySdnc;
47 import org.onap.aai.domain.yang.EsrThirdpartySdncList;
48 import org.onap.so.adapters.nssmf.exceptions.ApplicationException;
49 import org.onap.so.adapters.nssmf.extclients.aai.AaiServiceProvider;
50 import org.onap.so.adapters.nssmf.model.TokenRequest;
51 import org.onap.so.adapters.nssmf.model.TokenResponse;
52 import org.onap.so.beans.nsmf.EsrInfo;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.springframework.beans.factory.annotation.Autowired;
56 import org.springframework.stereotype.Component;
57 import static org.apache.http.entity.ContentType.APPLICATION_JSON;
58 import static org.onap.so.adapters.nssmf.rest.HttpMethod.POST;
59 import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.BAD_REQUEST;
60 import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.marshal;
61 import static org.onap.so.adapters.nssmf.util.NssmfAdapterUtil.unMarshal;
62 import static org.onap.logging.filter.base.ErrorCode.AvailabilityError;
63 import static org.onap.so.logger.LoggingAnchor.FOUR;
64 import static org.onap.so.logger.MessageEnum.RA_NS_EXC;
65
66 @Component
67 public class RestUtil {
68
69     private static final Logger logger = LoggerFactory.getLogger(RestUtil.class);
70
71     private static final int DEFAULT_TIME_OUT = 60000;
72
73     private static final String NSSMI_ADAPTER = "NSSMI Adapter";
74
75     private static final String TOKEN_URL = "/api/rest/securityManagement/v1" + "/oauth/token";
76
77     @Autowired
78     private AaiServiceProvider aaiSvcProv;
79
80
81     public NssmfInfo getNssmfHost(EsrInfo esrInfo) throws ApplicationException {
82         EsrThirdpartySdncList sdncList = aaiSvcProv.invokeGetThirdPartySdncList();
83         if (sdncList != null && sdncList.getEsrThirdpartySdnc() != null) {
84             for (EsrThirdpartySdnc sdncEsr : sdncList.getEsrThirdpartySdnc()) {
85
86                 EsrSystemInfoList sysInfoList =
87                         aaiSvcProv.invokeGetThirdPartySdncEsrSystemInfo(sdncEsr.getThirdpartySdncId());
88
89                 if (sysInfoList != null && sysInfoList.getEsrSystemInfo() != null) {
90                     for (EsrSystemInfo esr : sysInfoList.getEsrSystemInfo()) {
91                         if (esr != null && esr.getType().equals(esrInfo.getNetworkType().getNetworkType())
92                                 && esr.getVendor().equals(esrInfo.getVendor())) {
93                             logger.info("Found an entry with vendor name " + esrInfo.getVendor() + " and network type "
94                                     + esrInfo.getNetworkType() + " in ESR.");
95                             NssmfInfo nssmfInfo = new NssmfInfo();
96                             nssmfInfo.setIpAddress(esr.getIpAddress());
97                             nssmfInfo.setPort(esr.getPort());
98                             nssmfInfo.setCacert(esr.getSslCacert());
99                             nssmfInfo.setUserName(esr.getUserName());
100                             nssmfInfo.setPassword(esr.getPassword());
101                             String endPoint = UriBuilder.fromPath("").host(esr.getIpAddress())
102                                     .port(Integer.valueOf(esr.getPort())).scheme("https").build().toString();
103                             nssmfInfo.setUrl(endPoint);
104                             return nssmfInfo;
105                         }
106                     }
107                 }
108
109             }
110         }
111
112         throw new ApplicationException(BAD_REQUEST, "ESR information is improper");
113     }
114
115     public RestResponse sendRequest(String url, HttpMethod methodType, String content, EsrInfo esrInfo)
116             throws ApplicationException {
117
118         NssmfInfo nssmfInfo = getNssmfHost(esrInfo);
119
120         TokenRequest req = new TokenRequest();
121         req.setGrantType("password");
122         req.setUserName(nssmfInfo.getUserName());
123         req.setValue(nssmfInfo.getPassword());
124
125         String tokenReq = marshal(req);
126
127         logger.info("Sending token request to NSSMF: " + tokenReq);
128         RestResponse tokenRes = send(nssmfInfo.getUrl() + TOKEN_URL, POST, tokenReq, null);
129
130         TokenResponse res = unMarshal(tokenRes.getResponseContent(), TokenResponse.class);
131         String token = res.getAccessToken();
132         Header header = new BasicHeader("X-Auth-Token", token);
133         String nssmfUrl = nssmfInfo.getUrl() + url;
134         return send(nssmfUrl, methodType, content, header);
135     }
136
137     private RestResponse send(String url, HttpMethod methodType, String content, Header header) {
138
139         HttpRequestBase req = null;
140         HttpResponse res = null;
141
142         logger.debug("Beginning to send message {}: {}", methodType, url);
143
144         try {
145             int timeout = DEFAULT_TIME_OUT;
146
147             RequestConfig config = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
148                     .setConnectionRequestTimeout(timeout).build();
149             logger.debug("Sending request to NSSMF: " + content);
150             req = getHttpReq(url, methodType, header, config, content);
151             res = getHttpsClient().execute(req);
152
153             String resContent = null;
154             if (res.getEntity() != null) {
155                 resContent = EntityUtils.toString(res.getEntity(), "UTF-8");
156             }
157
158             int statusCode = res.getStatusLine().getStatusCode();
159             String statusMessage = res.getStatusLine().getReasonPhrase();
160             logger.info("NSSMF Response: {} {}", statusCode,
161                     statusMessage + (resContent == null ? "" : System.lineSeparator() + resContent));
162
163             if (res.getStatusLine().getStatusCode() >= 300) {
164                 String errMsg = "{\n  \"errorCode\": " + res.getStatusLine().getStatusCode()
165                         + "\n  \"errorDescription\": " + statusMessage + "\n}";
166                 logError(errMsg);
167                 return createResponse(statusCode, errMsg);
168             }
169             if (null != req) {
170                 req.reset();
171             } else {
172                 logger.debug("method is NULL:");
173             }
174             req = null;
175
176             return createResponse(statusCode, resContent);
177
178         } catch (SocketTimeoutException | ConnectTimeoutException e) {
179             String errMsg = "Request to NSSMF timed out";
180             logError(errMsg, e);
181             return createResponse(408, errMsg);
182         } catch (Exception e) {
183             String errMsg = "Error processing request to NSSMF";
184             logError(errMsg, e);
185             return createResponse(500, errMsg);
186         } finally {
187             if (res != null) {
188                 try {
189                     EntityUtils.consume(res.getEntity());
190                 } catch (Exception e) {
191                     logger.debug("Exception :", e);
192                 }
193             }
194             if (req != null) {
195                 try {
196                     req.reset();
197                 } catch (Exception e) {
198                     logger.debug("Exception :", e);
199                 }
200             }
201         }
202     }
203
204     private RestResponse createResponse(int statusCode, String errMsg) {
205         RestResponse restResponse = new RestResponse();
206         restResponse.setStatus(statusCode);
207         restResponse.setResponseContent(errMsg);
208         return restResponse;
209     }
210
211     private HttpRequestBase getHttpReq(String url, HttpMethod method, Header header, RequestConfig config,
212             String content) throws ApplicationException {
213         HttpRequestBase base = null;
214         switch (method) {
215             case POST:
216                 HttpPost post = new HttpPost(url);
217                 post.setEntity(new StringEntity(content, APPLICATION_JSON));
218                 base = post;
219                 break;
220
221             case GET:
222                 base = new HttpGet(url);
223                 break;
224
225             case PUT:
226                 HttpPut put = new HttpPut(url);
227                 put.setEntity(new StringEntity(content, APPLICATION_JSON));
228                 base = put;
229                 break;
230
231             case PATCH:
232                 break;
233
234             case DELETE:
235                 HttpDeleteWithBody delete = new HttpDeleteWithBody(url);
236                 if (content != null) {
237                     delete.setEntity(new StringEntity(content, APPLICATION_JSON));
238                 }
239                 base = delete;
240                 break;
241
242         }
243         base.setConfig(config);
244         if (header != null) {
245             base.setHeader(header);
246         }
247         return base;
248     }
249
250     class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
251         public static final String METHOD_NAME = "DELETE";
252
253         public String getMethod() {
254             return METHOD_NAME;
255         }
256
257         public HttpDeleteWithBody(final String uri) {
258             super();
259             setURI(URI.create(uri));
260         }
261
262         public HttpDeleteWithBody(final URI uri) {
263             super();
264             setURI(uri);
265         }
266
267         public HttpDeleteWithBody() {
268             super();
269         }
270     }
271
272
273     public HttpClient getHttpsClient() {
274
275         TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
276             public java.security.cert.X509Certificate[] getAcceptedIssuers() {
277                 return null;
278             }
279
280             public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
281
282             public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
283         }};
284
285         // Install the all-trusting trust manager
286         try {
287             SSLContext sc = SSLContext.getInstance("SSL");
288             sc.init(null, trustAllCerts, new java.security.SecureRandom());
289             // HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
290
291             SSLConnectionSocketFactory sslsf =
292                     new SSLConnectionSocketFactory(sc, new String[] {"TLSv1"}, null, new TrustAllHostNameVerifier());
293             return HttpClients.custom().setSSLSocketFactory(sslsf).build();
294         } catch (Exception e) {
295             throw new IllegalArgumentException(e);
296         }
297     }
298
299     private static void logError(String errMsg, Throwable t) {
300         logger.error(FOUR, RA_NS_EXC.toString(), NSSMI_ADAPTER, AvailabilityError.getValue(), errMsg, t);
301     }
302
303     private static void logError(String errMsg) {
304         logger.error(FOUR, RA_NS_EXC.toString(), NSSMI_ADAPTER, AvailabilityError.toString(), errMsg);
305     }
306 }
307