Fixed some NPEs reported by Sonar
[holmes/common.git] / holmes-actions / src / main / java / org / onap / holmes / common / aai / AaiQuery4Ccvpn.java
1 /**
2  * Copyright 2018 ZTE Corporation.
3  * <p>
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  * <p>
7  * http://www.apache.org/licenses/LICENSE-2.0
8  * <p>
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14
15 package org.onap.holmes.common.aai;
16
17 import com.alibaba.fastjson.JSON;
18 import com.alibaba.fastjson.JSONArray;
19 import com.alibaba.fastjson.JSONObject;
20 import org.glassfish.jersey.client.HttpUrlConnectorProvider;
21 import org.onap.holmes.common.aai.config.AaiConfig;
22 import org.onap.holmes.common.config.MicroServiceConfig;
23 import org.onap.holmes.common.exception.CorrelationException;
24
25 import javax.ws.rs.client.Client;
26 import javax.ws.rs.client.ClientBuilder;
27 import javax.ws.rs.client.Entity;
28 import javax.ws.rs.client.WebTarget;
29 import javax.ws.rs.core.MultivaluedHashMap;
30 import javax.ws.rs.core.MultivaluedMap;
31 import javax.ws.rs.core.Response;
32 import java.util.HashMap;
33 import java.util.Map;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
36
37 import lombok.extern.slf4j.Slf4j;
38
39 @Slf4j
40 public class AaiQuery4Ccvpn {
41
42     private MultivaluedMap<String, Object> headers;
43
44     public static AaiQuery4Ccvpn newInstance() {
45         return new AaiQuery4Ccvpn();
46     }
47
48     private static final String EMPTY_STR = "";
49
50     private static final JSONObject EMPTY_JSON = new JSONObject();
51
52     private AaiQuery4Ccvpn() {
53         headers = new MultivaluedHashMap<>();
54         headers.add("X-TransactionId", AaiConfig.X_TRANSACTION_ID);
55         headers.add("X-FromAppId", AaiConfig.X_FROMAPP_ID);
56         headers.add("Authorization", AaiConfig.getAuthenticationCredentials());
57         headers.add("Accept", "application/json");
58         headers.add("Content-Type", "application/json");
59     }
60
61     /**
62      * Query the logic link information for AAI. This method is based on the API:
63      * https://<AAI host>:<AAI port>/aai/v14/network/network-resources/network-resource/{networkId}/pnfs/pnf/{pnfName}/p-interfaces?interface-name={ifName}&operational-status={status}
64      * provided by AAI.
65      *
66      * @param networkId
67      * @param pnfName
68      * @param ifName
69      * @param status
70      * @return the ID of the logic link
71      */
72     public String getLogicLink(String networkId, String pnfName, String ifName, String status) throws CorrelationException {
73         Map<String, String> params = new HashMap<>();
74         params.put("networkId", networkId);
75         params.put("pnfName", pnfName);
76         params.put("ifName", ifName);
77
78         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_LINK_QUERY, params)
79                 + (status == null ? "" : String.format("&operational-status=%s", status)));
80         JSONObject linkInfo = getInfo(response.readEntity(String.class), "p-interface", "logical-link");
81         if (linkInfo == null) {
82             log.warn(String.format("Link information is missing from AAI. Method: [getLogicLink], " +
83                     "params: [networkId - %s, pnfName - %s, ifName - %s].", networkId, pnfName, ifName));
84             return EMPTY_STR;
85         }
86         return extractValueFromJsonArray(linkInfo.getJSONArray("relationship-data"), "logical-link.link-name");
87     }
88
89     /**
90      * Query the service instances related to a terminal point. This method is mainly based on the API:
91      * https://<AAI host>:<AAI port>/aai/v14/network/connectivities?connectivity-id={connectivityId}
92      * and
93      * https://<AAI host>:<AAI port>/aai/v14/business/customers/customer/{global-customer-id}/service-subscriptions/service-subscription/{service-type}
94      * provided by AAI. The path for getting the required instance information is: p-interface → vpn-vpnbinding → connectivity → service instance
95      *
96      * @param networkId
97      * @param pnfName
98      * @param ifName
99      * @param status
100      * @return service instances in JSONObject format
101      */
102     public JSONObject getServiceInstance(String networkId, String pnfName, String ifName, String status) {
103         try {
104             JSONObject vpnBindingInfo = getVpnBindingInfo(networkId, pnfName, ifName, status);
105             if (vpnBindingInfo == null) {
106                 log.warn(String.format("VPN binding information is missing from AAI. " +
107                         "Method: [getServiceInstance], params: [networkId - %s, pnfName - %s, " +
108                         "ifName - %s, status - %s].", networkId, pnfName, ifName, status));
109                 return EMPTY_JSON;
110             }
111             String vpnBindingId = extractValueFromJsonArray(vpnBindingInfo.getJSONArray("relationship-data"),
112                     "vpn-binding.vpn-id");
113             JSONObject connectivityInfo = getConnectivityInfo(vpnBindingId);
114             if (connectivityInfo == null) {
115                 log.warn(String.format("Connectivity information is missing from AAI. " +
116                         "Method: [getServiceInstance], params: [networkId - %s, pnfName - %s, " +
117                         "ifName - %s, status - %s].", networkId, pnfName, ifName, status));
118                 return EMPTY_JSON;
119             }
120             String connectivityId = extractValueFromJsonArray(connectivityInfo.getJSONArray("relationship-data"),
121                     "connectivity.connectivity-id");
122             JSONObject serviceInstanceInfo = getServiceInstanceByConn(connectivityId);
123             if (serviceInstanceInfo == null) {
124                 log.warn(String.format("Service instance information is missing from AAI. " +
125                         "Method: [getServiceInstance], params: [networkId - %s, pnfName - %s, " +
126                         "ifName - %s, status - %s].", networkId, pnfName, ifName, status));
127                 return EMPTY_JSON;
128             }
129             String serviceInstancePath = serviceInstanceInfo.getString("related-link");
130
131             Response response = get(getHostAddr(), getPath(serviceInstancePath));
132             JSONObject instance = JSON.parseObject(response.readEntity(String.class));
133
134             String[] params = new String[2];
135             Pattern pattern = Pattern.compile("/aai/v\\d+/business/customers/customer/(.+)" +
136                     "/service-subscriptions/service-subscription/(.+)" +
137                     "/service-instances/service-instance/(.+)");
138             Matcher matcher = pattern.matcher(serviceInstancePath);
139             if (matcher.find()) {
140                 params[0] = matcher.group(1);
141                 params[1] = matcher.group(2);
142             }
143             instance.put("globalSubscriberId", params[0]);
144             instance.put("serviceType", params[1]);
145             return instance;
146         } catch (CorrelationException e) {
147             throw new RuntimeException(e.getMessage(), e);
148         }
149     }
150
151     public void updateTerminalPointStatus(String networkId, String pnfName, String ifName,
152                                           Map<String, Object> body) throws CorrelationException {
153         Map<String, String> params = new HashMap<>();
154         params.put("networkId", networkId);
155         params.put("pnfName", pnfName);
156         params.put("ifName", ifName);
157         Response r = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_TP_UPDATE, params));
158         JSONObject jsonObject = JSONObject.parseObject(r.readEntity(String.class));
159         body.put("resource-version", jsonObject.get("resource-version").toString());
160
161         put(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_TP_UPDATE, params), body);
162     }
163
164     public void updateLogicLinkStatus(String linkName, Map<String, Object> body) throws CorrelationException {
165         Response r = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_LINK_UPDATE, "linkName", linkName));
166         JSONObject jsonObject = JSONObject.parseObject(r.readEntity(String.class));
167         body.put("resource-version", jsonObject.get("resource-version").toString());
168         body.put("link-type", jsonObject.get("link-type").toString());
169         put(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_LINK_UPDATE, "linkName", linkName), body);
170     }
171
172     private JSONObject getVpnBindingInfo(String networkId, String pnfName,
173                                          String ifName, String status) throws CorrelationException {
174         Map<String, String> params = new HashMap();
175         params.put("networkId", networkId);
176         params.put("pnfName", pnfName);
177         params.put("ifName", ifName);
178         params.put("status", status);
179         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_VPN_ADDR, params));
180         return getInfo(response.readEntity(String.class), "p-interface", "vpn-binding");
181     }
182
183     private JSONObject getConnectivityInfo(String vpnId) throws CorrelationException {
184         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_CONN_ADDR, "vpnId", vpnId));
185         return getInfo(response.readEntity(String.class), "vpn-binding", "connectivity");
186     }
187
188     private JSONObject getServiceInstanceByConn(String connectivityId) throws CorrelationException {
189         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_SERVICE_INSTANCE_ADDR_4_CCVPN,
190                 "connectivityId", connectivityId));
191         return getInfo(response.readEntity(String.class), "connectivity", "service-instance");
192     }
193
194     private JSONObject getServiceInstance(String globalCustomerId, String serviceType) throws CorrelationException {
195         Map<String, String> params = new HashMap();
196         params.put("global-customer-id", globalCustomerId);
197         params.put("service-type", serviceType);
198         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_SERVICE_INSTANCES_ADDR_4_CCVPN, params));
199         return JSON.parseObject(response.readEntity(String.class));
200     }
201
202     private String getPath(String urlTemplate, Map<String, String> pathParams) {
203         String url = urlTemplate;
204         for (Map.Entry<String, String> entry : pathParams.entrySet()) {
205             url = url.replaceAll("\\{" + entry.getKey() + "\\}", entry.getValue());
206         }
207         return url;
208     }
209
210     private String getPath(String urlTemplate, String paramName, String paramValue) {
211         return urlTemplate.replaceAll("\\{" + paramName + "\\}", paramValue);
212     }
213
214     private String getPath(String serviceInstancePath) {
215         Pattern pattern = Pattern.compile("/aai/(v\\d+)/([A-Za-z0-9\\-]+[^/])(/*.*)");
216         Matcher matcher = pattern.matcher(serviceInstancePath);
217         String ret = "/api";
218         if (matcher.find()) {
219             ret += "/aai-" + matcher.group(2) + "/" + matcher.group(1) + matcher.group(3);
220         }
221
222         return ret;
223     }
224
225     private Response get(String host, String path) throws CorrelationException {
226         Client client = ClientBuilder.newClient();
227         WebTarget target = client.target(host).path(path);
228         try {
229             Response response = target.request().headers(getAaiHeaders()).get();
230             if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
231                 throw new CorrelationException("Failed to connect to AAI. \nCause: "
232                         + response.getStatusInfo().getReasonPhrase() + "\nDetails: \n"
233                         + getErrorMsg(String.format("%s%s", host, path), null, response));
234             }
235             return response;
236         } catch (CorrelationException e) {
237             throw e;
238         } catch (Exception e) {
239             throw new CorrelationException(e.getMessage() + "More info: "
240                     + getErrorMsg(String.format("%s%s", host, path), null, null), e);
241         }
242     }
243
244     private void put(String host, String path, Map<String, Object> body) throws CorrelationException {
245         Client client = ClientBuilder.newClient();
246         WebTarget target = client.target(host).path(path);
247         try {
248             Response response = target.request().headers(getAaiHeaders()).build("PUT", Entity.json(body))
249                     .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true).invoke();
250             if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
251                 throw new CorrelationException("Failed to connect to AAI. \nCause: "
252                         + response.getStatusInfo().getReasonPhrase() + "\nDetails: \n"
253                         + getErrorMsg(String.format("%s%s", host, path), body, response));
254             }
255         } catch (CorrelationException e) {
256             throw e;
257         } catch (Exception e) {
258             throw new CorrelationException(e.getMessage() + "More info: "
259                     + getErrorMsg(String.format("%s%s", host, path), body, null), e);
260         }
261     }
262
263     private JSONObject getInfo(String response, String pField, String field) {
264         JSONObject jObject = JSONObject.parseObject(response);
265         JSONObject pInterface = extractJsonObject(jObject, pField);
266         if (pInterface == null) {
267             pInterface = jObject;
268         }
269         JSONObject relationshipList = extractJsonObject(pInterface, "relationship-list");
270         JSONArray relationShip = extractJsonArray(relationshipList, "relationship");
271         if (relationShip != null) {
272             for (int i = 0; i < relationShip.size(); ++i) {
273                 final JSONObject object = relationShip.getJSONObject(i);
274                 if (object.getString("related-to").equals(field)) {
275                     return object;
276                 }
277             }
278         }
279         return null;
280     }
281
282     private JSONObject extractJsonObject(JSONObject obj, String key) {
283         if (obj != null && key != null && obj.containsKey(key)) {
284             return obj.getJSONObject(key);
285         }
286         return null;
287     }
288
289     private JSONArray extractJsonArray(JSONObject obj, String key) {
290         if (obj != null && key != null && obj.containsKey(key)) {
291             return obj.getJSONArray(key);
292         }
293         return null;
294     }
295
296     private MultivaluedMap getAaiHeaders() {
297         return headers;
298     }
299
300     private String getHostAddr() {
301         return MicroServiceConfig.getMsbServerAddrWithHttpPrefix();
302     }
303
304     private String extractValueFromJsonArray(JSONArray relationshipData, String keyName) {
305         if (relationshipData != null) {
306             for (int i = 0; i < relationshipData.size(); ++i) {
307                 JSONObject item = relationshipData.getJSONObject(i);
308                 if (item.getString("relationship-key").equals(keyName)) {
309                     return item.getString("relationship-value");
310                 }
311             }
312         }
313         return null;
314     }
315
316     private String getErrorMsg(String url, Map<String, Object> body, Response response) {
317         StringBuilder sb = new StringBuilder();
318         sb.append("Rerquest URL: ").append(url).append("\n");
319         sb.append("Request Header: ").append(JSONObject.toJSONString(headers)).append("\n");
320         if (body != null) {
321             sb.append("Request Body: ").append(JSONObject.toJSONString(body)).append("\n");
322         }
323         if (response != null) {
324             sb.append("Request Body: ").append(response.readEntity(String.class));
325         }
326         return sb.toString();
327     }
328 }