2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.so.adapters.nssmf.rest;
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;
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;
67 public class RestUtil {
69 private static final Logger logger = LoggerFactory.getLogger(RestUtil.class);
71 private static final int DEFAULT_TIME_OUT = 60000;
73 private static final String NSSMI_ADAPTER = "NSSMI Adapter";
75 private static final String TOKEN_URL = "/api/rest/securityManagement/v1" + "/oauth/token";
78 private AaiServiceProvider aaiSvcProv;
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()) {
86 EsrSystemInfoList sysInfoList =
87 aaiSvcProv.invokeGetThirdPartySdncEsrSystemInfo(sdncEsr.getThirdpartySdncId());
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);
112 throw new ApplicationException(BAD_REQUEST, "ESR information is improper");
115 public RestResponse sendRequest(String url, HttpMethod methodType, String content, EsrInfo esrInfo)
116 throws ApplicationException {
118 NssmfInfo nssmfInfo = getNssmfHost(esrInfo);
120 TokenRequest req = new TokenRequest();
121 req.setGrantType("password");
122 req.setUserName(nssmfInfo.getUserName());
123 req.setValue(nssmfInfo.getPassword());
125 String tokenReq = marshal(req);
127 logger.info("Sending token request to NSSMF: " + tokenReq);
128 RestResponse tokenRes = send(nssmfInfo.getUrl() + TOKEN_URL, POST, tokenReq, null);
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);
137 private RestResponse send(String url, HttpMethod methodType, String content, Header header) {
139 HttpRequestBase req = null;
140 HttpResponse res = null;
142 logger.debug("Beginning to send message {}: {}", methodType, url);
145 int timeout = DEFAULT_TIME_OUT;
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);
153 String resContent = null;
154 if (res.getEntity() != null) {
155 resContent = EntityUtils.toString(res.getEntity(), "UTF-8");
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));
163 if (res.getStatusLine().getStatusCode() >= 300) {
164 String errMsg = "{\n \"errorCode\": " + res.getStatusLine().getStatusCode()
165 + "\n \"errorDescription\": " + statusMessage + "\n}";
167 return createResponse(statusCode, errMsg);
172 logger.debug("method is NULL:");
176 return createResponse(statusCode, resContent);
178 } catch (SocketTimeoutException | ConnectTimeoutException e) {
179 String errMsg = "Request to NSSMF timed out";
181 return createResponse(408, errMsg);
182 } catch (Exception e) {
183 String errMsg = "Error processing request to NSSMF";
185 return createResponse(500, errMsg);
189 EntityUtils.consume(res.getEntity());
190 } catch (Exception e) {
191 logger.debug("Exception :", e);
197 } catch (Exception e) {
198 logger.debug("Exception :", e);
204 private RestResponse createResponse(int statusCode, String errMsg) {
205 RestResponse restResponse = new RestResponse();
206 restResponse.setStatus(statusCode);
207 restResponse.setResponseContent(errMsg);
211 private HttpRequestBase getHttpReq(String url, HttpMethod method, Header header, RequestConfig config,
212 String content) throws ApplicationException {
213 HttpRequestBase base = null;
216 HttpPost post = new HttpPost(url);
217 post.setEntity(new StringEntity(content, APPLICATION_JSON));
222 base = new HttpGet(url);
226 HttpPut put = new HttpPut(url);
227 put.setEntity(new StringEntity(content, APPLICATION_JSON));
235 HttpDeleteWithBody delete = new HttpDeleteWithBody(url);
236 if (content != null) {
237 delete.setEntity(new StringEntity(content, APPLICATION_JSON));
243 base.setConfig(config);
244 if (header != null) {
245 base.setHeader(header);
250 class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
251 public static final String METHOD_NAME = "DELETE";
253 public String getMethod() {
257 public HttpDeleteWithBody(final String uri) {
259 setURI(URI.create(uri));
262 public HttpDeleteWithBody(final URI uri) {
267 public HttpDeleteWithBody() {
273 public HttpClient getHttpsClient() {
275 TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
276 public java.security.cert.X509Certificate[] getAcceptedIssuers() {
280 public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
282 public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
285 // Install the all-trusting trust manager
287 SSLContext sc = SSLContext.getInstance("SSL");
288 sc.init(null, trustAllCerts, new java.security.SecureRandom());
289 // HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
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);
299 private static void logError(String errMsg, Throwable t) {
300 logger.error(FOUR, RA_NS_EXC.toString(), NSSMI_ADAPTER, AvailabilityError.getValue(), errMsg, t);
303 private static void logError(String errMsg) {
304 logger.error(FOUR, RA_NS_EXC.toString(), NSSMI_ADAPTER, AvailabilityError.toString(), errMsg);