Fixed HTTP PATCH Failures
[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
18 import com.alibaba.fastjson.JSONArray;
19 import com.alibaba.fastjson.JSONObject;
20 import org.onap.holmes.common.aai.config.AaiConfig;
21 import org.onap.holmes.common.config.MicroServiceConfig;
22 import org.onap.holmes.common.exception.CorrelationException;
23
24 import javax.ws.rs.client.Client;
25 import javax.ws.rs.client.ClientBuilder;
26 import javax.ws.rs.client.Entity;
27 import javax.ws.rs.client.WebTarget;
28 import javax.ws.rs.core.MultivaluedHashMap;
29 import javax.ws.rs.core.MultivaluedMap;
30 import javax.ws.rs.core.Response;
31 import org.glassfish.jersey.client.HttpUrlConnectorProvider;
32 import java.util.HashMap;
33 import java.util.Map;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
36
37 public class AaiQuery4Ccvpn {
38
39     private MultivaluedMap<String, Object> headers;
40
41     static public AaiQuery4Ccvpn newInstance() {
42         return new AaiQuery4Ccvpn();
43     }
44
45     private AaiQuery4Ccvpn() {
46         headers = new MultivaluedHashMap<>();
47         headers.add("X-TransactionId", AaiConfig.X_TRANSACTION_ID);
48         headers.add("X-FromAppId", AaiConfig.X_FROMAPP_ID);
49         headers.add("Authorization", AaiConfig.getAuthenticationCredentials());
50         headers.add("Accept", "application/json");
51     }
52
53     /**
54      * Query the logic link information for AAI. This method is based on the API:
55      * https://<AAI host>:<AAI port>/aai/v14/network/network-resources/network-resource/{networkId}/pnfs/pnf/{pnfName}/p-interfaces?interface-name={ifName}&operational-status={status}
56      * provided by AAI.
57      *
58      * @param networkId
59      * @param pnfName
60      * @param ifName
61      * @param status
62      * @return the ID of the logic link
63      */
64     public String getLogicLink(String networkId, String pnfName, String ifName, String status) {
65         Map<String, String> params = new HashMap<>();
66         params.put("networkId", networkId);
67         params.put("pnfName", pnfName);
68         params.put("ifName", ifName);
69
70         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_LINK_QUERY, params)
71                 + (status == null ? "" : String.format("&operational-status=%s", status)));
72         if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
73             throw new RuntimeException("Failed to connect to AAI. Cause: "
74                     + response.getStatusInfo().getReasonPhrase());
75         }
76
77         JSONObject linkInfo = getInfo(JSONObject.toJSONString(response.getEntity()), "p-interface", "logical-link");
78         return extractValueFromJsonArray(linkInfo.getJSONArray("relationship-data"), "logical-link.link-name");
79     }
80
81     /**
82      * Query all the instances related to a terminal point. This method is mainly based on the API:
83      * https://<AAI host>:<AAI port>/aai/v14/network/connectivities?connectivity-id={connectivityId}
84      * and
85      * https://<AAI host>:<AAI port>/aai/v14/business/customers/customer/{global-customer-id}/service-subscriptions/service-subscription/{service-type}
86      * provided by AAI. The path for getting the required instance information is: p-interface → vpn-vpnbinding → connectivity → service instance
87      *
88      * @param networkId
89      * @param pnfName
90      * @param ifName
91      * @param status
92      * @return all related service instances in JSONArray format
93      */
94     public JSONArray getServiceInstances(String networkId, String pnfName, String ifName, String status) {
95         try {
96             JSONObject vpnBindingInfo = getVpnBindingInfo(networkId, pnfName, ifName, status);
97             String vpnBindingId = extractValueFromJsonArray(vpnBindingInfo.getJSONArray("relationship-data"),
98                     "vpn-binding.vpn-id");
99             JSONObject connectivityInfo = getConnectivityInfo(vpnBindingId);
100             String connectivityId = extractValueFromJsonArray(connectivityInfo.getJSONArray("relationship-data"),
101                     "connectivity. connectivity-id");
102             JSONObject serviceInstanceInfo = getServiceInstanceByConn(connectivityId);
103             String serviceInstancePath = serviceInstanceInfo.getString("related-link");
104             serviceInstancePath = serviceInstancePath.substring(0, serviceInstancePath.lastIndexOf('/'));
105
106             String[] params = new String[2];
107
108             Pattern pattern = Pattern.compile("/aai/v\\d+/business/customers/customer/(.+)/service-subscriptions/service-subscription/(.+)");
109             Matcher matcher = pattern.matcher(serviceInstancePath);
110             if (matcher.find()) {
111                 params[0] = matcher.group(1);
112                 params[1] = matcher.group(2);
113             }
114
115             Response response = get(getHostAddr(), getPath(serviceInstancePath));
116             if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
117                 throw new RuntimeException("Failed to connect to AAI. Cause: "
118                         + response.getStatusInfo().getReasonPhrase());
119             }
120             JSONArray instances = getInstances(JSONObject.toJSONString(response.getEntity()));
121             for (int i = 0; i < instances.size(); ++i) {
122                 JSONObject instance = instances.getJSONObject(i);
123                 Response res = get(getHostAddr(), serviceInstancePath + "/service-instances?service-instance-id="
124                         + instance.getString("service-instance-id"));
125                 if (res.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
126                     throw new RuntimeException("Failed to connect to AAI. Cause: "
127                             + response.getStatusInfo().getReasonPhrase());
128                 }
129                 String inputParams = JSONObject.parseObject(response.readEntity(String.class)).getString("input-parameters");
130                 instance.put("input-parameters", inputParams);
131                 instance.put("globalSubscriberId", params[0]);
132                 instance.put("serviceType", params[1]);
133             }
134
135             return instances;
136         } catch (CorrelationException e) {
137             throw new RuntimeException(e.getMessage(), e);
138         }
139     }
140
141     public void updateTerminalPointStatus(String networkId, String pnfName, String ifName,
142                                           Map<String, Object> body) throws CorrelationException {
143         Map<String, String> params = new HashMap<>();
144         params.put("networkId", networkId);
145         params.put("pnfName", pnfName);
146         params.put("ifName", ifName);
147         Response response = patch(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_TP_UPDATE, params), body);
148         if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
149             throw new CorrelationException("Failed to connecto to AAI. Cause: "
150                     + response.getStatusInfo().getReasonPhrase());
151         }
152     }
153
154     public void updateLogicLinkStatus(String linkName, Map<String, Object> body) throws CorrelationException {
155         Response response = patch(getHostAddr(),
156                 getPath(AaiConfig.MsbConsts.AAI_TP_UPDATE, "linkName", linkName), body);
157         if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
158             throw new CorrelationException("Failed to connecto to AAI. Cause: "
159                     + response.getStatusInfo().getReasonPhrase());
160         }
161     }
162
163     private JSONObject getVpnBindingInfo(String networkId, String pnfName,
164                                          String ifName, String status) throws CorrelationException {
165         Map<String, String> params = new HashMap();
166         params.put("networkId", networkId);
167         params.put("pnfName", pnfName);
168         params.put("ifName", ifName);
169         params.put("status", status);
170         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_VPN_ADDR, params));
171         if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
172             throw new CorrelationException("Failed to connecto to AAI. Cause: "
173                     + response.getStatusInfo().getReasonPhrase());
174         }
175         return getInfo(JSONObject.toJSONString(response.getEntity()), "p-interface", "vpn-binding");
176     }
177
178     private JSONObject getConnectivityInfo(String vpnId) throws CorrelationException {
179         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_CONN_ADDR, "vpnId", vpnId));
180         if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
181             throw new CorrelationException("Failed to connect to AAI. Cause: "
182                     + response.getStatusInfo().getReasonPhrase());
183         }
184         return getInfo(JSONObject.toJSONString(response.getEntity()), "vpn-binding", "connectivity");
185     }
186
187     private JSONObject getServiceInstanceByConn(String connectivityId) throws CorrelationException {
188         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_SERVICE_INSTANCE_ADDR_4_CCVPN,
189                 "connectivityId", connectivityId));
190         if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
191             throw new CorrelationException("Failed to connect to AAI. Cause: "
192                     + response.getStatusInfo().getReasonPhrase());
193         }
194         return getInfo(JSONObject.toJSONString(response.getEntity()), "connectivity", "service-instance");
195     }
196
197     private JSONArray getServiceInstances(String globalCustomerId, String serviceType) throws CorrelationException {
198         Map<String, String> params = new HashMap();
199         params.put("global-customer-id", globalCustomerId);
200         params.put("service-type", serviceType);
201         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_SERVICE_INSTANCES_ADDR_4_CCVPN, params));
202         if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
203             throw new CorrelationException("Failed to connect to AAI. Cause: "
204                     + response.getStatusInfo().getReasonPhrase());
205         }
206         return getInstances(JSONObject.toJSONString(response.getEntity()));
207     }
208
209     private String getPath(String urlTemplate, Map<String, String> pathParams) {
210         String url = urlTemplate;
211         for (String key : pathParams.keySet()) {
212             url = url.replaceAll("\\{" + key + "\\}", pathParams.get(key));
213         }
214         return url;
215     }
216
217     private String getPath(String urlTemplate, String paramName, String paramValue) {
218         return urlTemplate.replaceAll("\\{" + paramName + "\\}", paramValue);
219     }
220
221     private String getPath(String serviceInstancePath) {
222         Pattern pattern = Pattern.compile("/aai/(v\\d+)/([A-Za-z0-9\\-]+[^/])(/*.*)");
223         Matcher matcher = pattern.matcher(serviceInstancePath);
224         String ret = "/api";
225         if (matcher.find()) {
226             ret += "/aai-" + matcher.group(2) + "/" + matcher.group(1) + matcher.group(3);
227         }
228
229         return ret;
230     }
231
232     private Response get(String host, String path) {
233         Client client = ClientBuilder.newClient();
234         WebTarget target = client.target(host).path(path);
235         return target.request().headers(getAaiHeaders()).get();
236     }
237
238     private Response patch(String host, String path, Map<String, Object> body) {
239         Client client = ClientBuilder.newClient();
240         WebTarget target = client.target(host).path(path);
241         return target.request().headers(getAaiHeaders()).build("PATCH", Entity.json(body))
242                 .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true).invoke();
243     }
244
245     private JSONObject getInfo(String response, String pField, String field) {
246         JSONArray results = extractJsonArray(JSONObject.parseObject(response), "results");
247         JSONObject pInterface = extractJsonObject(results.getJSONObject(0), pField);
248         JSONObject relationshipList = extractJsonObject(pInterface, "relationship-list");
249         JSONArray relationShip = extractJsonArray(relationshipList, "relationship");
250         if (relationShip != null) {
251             for (int i = 0; i < relationShip.size(); ++i) {
252                 final JSONObject object = relationShip.getJSONObject(i);
253                 if (object.getString("related-to").equals(field)) {
254                     return object;
255                 }
256             }
257         }
258         return null;
259     }
260
261     private JSONArray getInstances(String response) {
262         JSONArray results = extractJsonArray(JSONObject.parseObject(response), "results");
263         JSONObject pInterface = extractJsonObject(results.getJSONObject(0), "service-subscription");
264         JSONObject serviceInstances = extractJsonObject(pInterface, "service-instances");
265         JSONArray instance = extractJsonArray(serviceInstances, "service-instance");
266         return instance;
267     }
268
269     private JSONObject extractJsonObject(JSONObject obj, String key) {
270         if (obj != null && key != null && obj.containsKey(key)) {
271             return obj.getJSONObject(key);
272         }
273         return null;
274     }
275
276     private JSONArray extractJsonArray(JSONObject obj, String key) {
277         if (obj != null && key != null && obj.containsKey(key)) {
278             return obj.getJSONArray(key);
279         }
280         return null;
281     }
282
283     private MultivaluedMap getAaiHeaders() {
284         return headers;
285     }
286
287     private String getHostAddr() {
288         String[] msbInfo = MicroServiceConfig.getMsbServerAddrWithHttpPrefix().split(":");
289         StringBuilder sb = new StringBuilder("http://");
290         sb.append(msbInfo[0]).append(msbInfo[1]);
291         return sb.toString();
292     }
293
294     private String extractValueFromJsonArray(JSONArray relationshipData, String keyName) {
295         for (int i = 0; i < relationshipData.size(); ++i) {
296             JSONObject item = relationshipData.getJSONObject(i);
297             if (item.getString("relationship-key").equals(keyName)) {
298                 return item.getString("relationship-value");
299             }
300         }
301         return null;
302     }
303 }