2 * Copyright 2018 ZTE Corporation.
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
7 * http://www.apache.org/licenses/LICENSE-2.0
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
15 package org.onap.holmes.common.aai;
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;
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;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
37 public class AaiQuery4Ccvpn {
39 private MultivaluedMap<String, Object> headers;
41 public static AaiQuery4Ccvpn newInstance() {
42 return new AaiQuery4Ccvpn();
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 headers.add("Content-Type", "application/json");
55 * Query the logic link information for AAI. This method is based on the API:
56 * https://<AAI host>:<AAI port>/aai/v14/network/network-resources/network-resource/{networkId}/pnfs/pnf/{pnfName}/p-interfaces?interface-name={ifName}&operational-status={status}
63 * @return the ID of the logic link
65 public String getLogicLink(String networkId, String pnfName, String ifName, String status) throws CorrelationException {
66 Map<String, String> params = new HashMap<>();
67 params.put("networkId", networkId);
68 params.put("pnfName", pnfName);
69 params.put("ifName", ifName);
71 Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_LINK_QUERY, params)
72 + (status == null ? "" : String.format("&operational-status=%s", status)));
73 JSONObject linkInfo = getInfo(response.readEntity(String.class), "p-interface", "logical-link");
74 return extractValueFromJsonArray(linkInfo.getJSONArray("relationship-data"), "logical-link.link-name");
78 * Query the service 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}
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
88 * @return service instances in JSONObject format
90 public JSONObject getServiceInstance(String networkId, String pnfName, String ifName, String status) {
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");
101 Response response = get(getHostAddr(), getPath(serviceInstancePath));
102 JSONObject instance = JSON.parseObject(response.readEntity(String.class));
104 String[] params = new String[2];
105 Pattern pattern = Pattern.compile("/aai/v\\d+/business/customers/customer/(.+)" +
106 "/service-subscriptions/service-subscription/(.+)" +
107 "/service-instances/service-instance/(.+)");
108 Matcher matcher = pattern.matcher(serviceInstancePath);
109 if (matcher.find()) {
110 params[0] = matcher.group(1);
111 params[1] = matcher.group(2);
113 instance.put("globalSubscriberId", params[0]);
114 instance.put("serviceType", params[1]);
116 } catch (CorrelationException e) {
117 throw new RuntimeException(e.getMessage(), e);
121 public void updateTerminalPointStatus(String networkId, String pnfName, String ifName,
122 Map<String, Object> body) throws CorrelationException {
123 Map<String, String> params = new HashMap<>();
124 params.put("networkId", networkId);
125 params.put("pnfName", pnfName);
126 params.put("ifName", ifName);
127 Response r = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_TP_UPDATE, params));
128 JSONObject jsonObject = JSONObject.parseObject(r.readEntity(String.class));
129 body.put("resource-version", jsonObject.get("resource-version").toString());
131 put(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_TP_UPDATE, params), body);
134 public void updateLogicLinkStatus(String linkName, Map<String, Object> body) throws CorrelationException {
135 Response r = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_LINK_UPDATE, "linkName", linkName));
136 JSONObject jsonObject = JSONObject.parseObject(r.readEntity(String.class));
137 body.put("resource-version", jsonObject.get("resource-version").toString());
138 body.put("link-type", jsonObject.get("link-type").toString());
139 put(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_LINK_UPDATE, "linkName", linkName), body);
142 private JSONObject getVpnBindingInfo(String networkId, String pnfName,
143 String ifName, String status) throws CorrelationException {
144 Map<String, String> params = new HashMap();
145 params.put("networkId", networkId);
146 params.put("pnfName", pnfName);
147 params.put("ifName", ifName);
148 params.put("status", status);
149 Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_VPN_ADDR, params));
150 return getInfo(response.readEntity(String.class), "p-interface", "vpn-binding");
153 private JSONObject getConnectivityInfo(String vpnId) throws CorrelationException {
154 Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_CONN_ADDR, "vpnId", vpnId));
155 return getInfo(response.readEntity(String.class), "vpn-binding", "connectivity");
158 private JSONObject getServiceInstanceByConn(String connectivityId) throws CorrelationException {
159 Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_SERVICE_INSTANCE_ADDR_4_CCVPN,
160 "connectivityId", connectivityId));
161 return getInfo(response.readEntity(String.class), "connectivity", "service-instance");
164 private JSONObject getServiceInstance(String globalCustomerId, String serviceType) throws CorrelationException {
165 Map<String, String> params = new HashMap();
166 params.put("global-customer-id", globalCustomerId);
167 params.put("service-type", serviceType);
168 Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_SERVICE_INSTANCES_ADDR_4_CCVPN, params));
169 return JSON.parseObject(response.readEntity(String.class));
172 private String getPath(String urlTemplate, Map<String, String> pathParams) {
173 String url = urlTemplate;
174 for(Map.Entry<String, String> entry : pathParams.entrySet()){
175 url = url.replaceAll("\\{" + entry.getKey() + "\\}", entry.getValue());
180 private String getPath(String urlTemplate, String paramName, String paramValue) {
181 return urlTemplate.replaceAll("\\{" + paramName + "\\}", paramValue);
184 private String getPath(String serviceInstancePath) {
185 Pattern pattern = Pattern.compile("/aai/(v\\d+)/([A-Za-z0-9\\-]+[^/])(/*.*)");
186 Matcher matcher = pattern.matcher(serviceInstancePath);
188 if (matcher.find()) {
189 ret += "/aai-" + matcher.group(2) + "/" + matcher.group(1) + matcher.group(3);
195 private Response get(String host, String path) throws CorrelationException {
196 Client client = ClientBuilder.newClient();
197 WebTarget target = client.target(host).path(path);
199 Response response = target.request().headers(getAaiHeaders()).get();
200 if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
201 throw new CorrelationException("Failed to connect to AAI. \nCause: "
202 + response.getStatusInfo().getReasonPhrase() + "\nDetails: \n"
203 + getErrorMsg(String.format("%s%s", host, path), null, response));
206 } catch (CorrelationException e) {
208 } catch (Exception e) {
209 throw new CorrelationException(e.getMessage() + "More info: "
210 + getErrorMsg(String.format("%s%s", host, path), null, null), e);
214 private void put(String host, String path, Map<String, Object> body) throws CorrelationException {
215 Client client = ClientBuilder.newClient();
216 WebTarget target = client.target(host).path(path);
218 Response response = target.request().headers(getAaiHeaders()).build("PUT", Entity.json(body))
219 .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true).invoke();
220 if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
221 throw new CorrelationException("Failed to connect to AAI. \nCause: "
222 + response.getStatusInfo().getReasonPhrase() + "\nDetails: \n"
223 + getErrorMsg(String.format("%s%s", host, path), body, response));
225 } catch (CorrelationException e) {
227 } catch (Exception e) {
228 throw new CorrelationException(e.getMessage() + "More info: "
229 + getErrorMsg(String.format("%s%s", host, path), body, null), e);
233 private JSONObject getInfo(String response, String pField, String field) {
234 JSONObject jObject = JSONObject.parseObject(response);
235 JSONObject pInterface = extractJsonObject(jObject, pField);
236 if (pInterface == null) {
237 pInterface = jObject;
239 JSONObject relationshipList = extractJsonObject(pInterface, "relationship-list");
240 JSONArray relationShip = extractJsonArray(relationshipList, "relationship");
241 if (relationShip != null) {
242 for (int i = 0; i < relationShip.size(); ++i) {
243 final JSONObject object = relationShip.getJSONObject(i);
244 if (object.getString("related-to").equals(field)) {
252 private JSONObject extractJsonObject(JSONObject obj, String key) {
253 if (obj != null && key != null && obj.containsKey(key)) {
254 return obj.getJSONObject(key);
259 private JSONArray extractJsonArray(JSONObject obj, String key) {
260 if (obj != null && key != null && obj.containsKey(key)) {
261 return obj.getJSONArray(key);
266 private MultivaluedMap getAaiHeaders() {
270 private String getHostAddr() {
271 return MicroServiceConfig.getMsbServerAddrWithHttpPrefix();
274 private String extractValueFromJsonArray(JSONArray relationshipData, String keyName) {
275 for (int i = 0; i < relationshipData.size(); ++i) {
276 JSONObject item = relationshipData.getJSONObject(i);
277 if (item.getString("relationship-key").equals(keyName)) {
278 return item.getString("relationship-value");
284 private String getErrorMsg(String url, Map<String, Object> body, Response response) {
285 StringBuilder sb = new StringBuilder();
286 sb.append("Rerquest URL: ").append(url).append("\n");
287 sb.append("Request Header: ").append(JSONObject.toJSONString(headers)).append("\n");
289 sb.append("Request Body: ").append(JSONObject.toJSONString(body)).append("\n");
291 if (response != null) {
292 sb.append("Request Body: ").append(response.readEntity(String.class));
294 return sb.toString();