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