Fixed Some Data Format Anormaly
[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     public String getLogicLink(String networkId, String pnfName, String ifName, String status) {
51         Map<String, String> params = new HashMap<>();
52         params.put("networkId", networkId);
53         params.put("pnfName", pnfName);
54         params.put("ifName", ifName);
55         params.put("status", status);
56         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_LINK_UPDATE, params));
57         if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
58             throw new RuntimeException("Failed to connect to AAI. Cause: "
59                     + response.getStatusInfo().getReasonPhrase());
60         }
61
62         JSONObject linkInfo = getInfo(JSONObject.toJSONString(response.getEntity()), "p-interface", "logical-link");
63         return extractValueFromJsonArray(linkInfo.getJSONArray("relationship-data"), "logical-link.link-name");
64     }
65
66     public JSONArray getServiceInstances(String networkId, String pnfName, String ifName, String status) {
67         try {
68             JSONObject vpnBindingInfo = getVpnBindingInfo(networkId, pnfName, ifName, status);
69             String vpnBindingId = extractValueFromJsonArray(vpnBindingInfo.getJSONArray("relationship-data"),
70                     "vpn-binding.vpn-id");
71             JSONObject connectivityInfo = getConnectivityInfo(vpnBindingId);
72             String connectivityId = extractValueFromJsonArray(connectivityInfo.getJSONArray("relationship-data"),
73                     "connectivity. connectivity-id");
74             JSONObject serviceInstanceInfo = getServiceInstanceByConn(connectivityId);
75             String serviceInstancePath = serviceInstanceInfo.getString("related-link");
76             serviceInstancePath = serviceInstancePath.substring(0, serviceInstancePath.lastIndexOf('/'));
77
78             Response response = get(getHostAddr(), getPath(serviceInstancePath));
79             if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
80                 throw new RuntimeException("Failed to connect to AAI. Cause: "
81                         + response.getStatusInfo().getReasonPhrase());
82             }
83             return getInstances(JSONObject.toJSONString(response.getEntity()));
84         } catch (CorrelationException e) {
85             throw new RuntimeException(e.getMessage(), e);
86         }
87     }
88
89     public void updateTerminalPointStatus(String networkId, String pnfName, String ifName,
90                                           Map<String, Object> body) throws CorrelationException {
91         Map<String, String> params = new HashMap<>();
92         params.put("networkId", networkId);
93         params.put("pnfName", pnfName);
94         params.put("ifName", ifName);
95         Response response = patch(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_TP_UPDATE, params), body);
96         if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
97             throw new CorrelationException("Failed to connecto to AAI. Cause: "
98                     + response.getStatusInfo().getReasonPhrase());
99         }
100     }
101
102     public void updateLogicLinkStatus(String linkName, Map<String, Object> body) throws CorrelationException {
103         Response response = patch(getHostAddr(),
104                 getPath(AaiConfig.MsbConsts.AAI_TP_UPDATE, "linkName", linkName), body);
105         if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
106             throw new CorrelationException("Failed to connecto to AAI. Cause: "
107                     + response.getStatusInfo().getReasonPhrase());
108         }
109     }
110
111     public JSONObject getVpnBindingInfo(String networkId, String pnfName,
112                                         String ifName, String status) throws CorrelationException {
113         Map<String, String> params = new HashMap();
114         params.put("networkId", networkId);
115         params.put("pnfName", pnfName);
116         params.put("ifName", ifName);
117         params.put("status", status);
118         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_VPN_ADDR, params));
119         if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
120             throw new CorrelationException("Failed to connecto to AAI. Cause: "
121                     + response.getStatusInfo().getReasonPhrase());
122         }
123         return getInfo(JSONObject.toJSONString(response.getEntity()), "p-interface", "vpn-binding");
124     }
125
126     public JSONObject getConnectivityInfo(String vpnId) throws CorrelationException {
127         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_CONN_ADDR, "vpnId", vpnId));
128         if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
129             throw new CorrelationException("Failed to connect to AAI. Cause: "
130                     + response.getStatusInfo().getReasonPhrase());
131         }
132         return getInfo(JSONObject.toJSONString(response.getEntity()), "vpn-binding", "connectivity");
133     }
134
135     public JSONObject getServiceInstanceByConn(String connectivityId) throws CorrelationException {
136         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_SERVICE_INSTANCE_ADDR_4_CCVPN,
137                 "connectivityId", connectivityId));
138         if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
139             throw new CorrelationException("Failed to connect to AAI. Cause: "
140                     + response.getStatusInfo().getReasonPhrase());
141         }
142         return getInfo(JSONObject.toJSONString(response.getEntity()), "connectivity", "service-instance");
143     }
144
145     public JSONArray getServiceInstances(String globalCustomerId, String serviceType) throws CorrelationException {
146         Map<String, String> params = new HashMap();
147         params.put("global-customer-id", globalCustomerId);
148         params.put("service-type", serviceType);
149         Response response = get(getHostAddr(), getPath(AaiConfig.MsbConsts.AAI_SERVICE_INSTANCES_ADDR_4_CCVPN, params));
150         if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
151             throw new CorrelationException("Failed to connect to AAI. Cause: "
152                     + response.getStatusInfo().getReasonPhrase());
153         }
154         return getInstances(JSONObject.toJSONString(response.getEntity()));
155     }
156
157     private String getPath(String urlTemplate, Map<String, String> pathParams) {
158         String url = urlTemplate;
159         for (String key : pathParams.keySet()) {
160             url = url.replaceAll("\\{" + key + "\\}", pathParams.get(key));
161         }
162         return url;
163     }
164
165     private String getPath(String urlTemplate, String paramName, String paramValue) {
166         return urlTemplate.replaceAll("\\{" + paramName + "\\}", paramValue);
167     }
168
169     private String getPath(String serviceInstancePath) {
170         Pattern pattern = Pattern.compile("/aai/(v\\d+)/([A-Za-z0-9\\-]+[^/])(/*.*)");
171         Matcher matcher = pattern.matcher(serviceInstancePath);
172         String ret = "/api";
173         if (matcher.find()) {
174             ret += "/aai-" + matcher.group(2) + "/" + matcher.group(1) + matcher.group(3);
175         }
176
177         return ret;
178     }
179
180     public Response get(String host, String path) {
181         Client client = ClientBuilder.newClient();
182         WebTarget target = client.target(host).path(path);
183         return target.request().headers(getAaiHeaders()).get();
184     }
185
186     public Response patch(String host, String path, Map<String, Object> body) {
187         Client client = ClientBuilder.newClient();
188         WebTarget target = client.target(host).path(path);
189         return target.request().headers(getAaiHeaders()).method("PATCH", Entity.json(body));
190     }
191
192     private JSONObject getInfo(String response, String pField, String field) {
193         JSONArray results = extractJsonArray(JSONObject.parseObject(response), "results");
194         JSONObject pInterface = extractJsonObject(results.getJSONObject(0), pField);
195         JSONObject relationshipList = extractJsonObject(pInterface, "relationship-list");
196         JSONArray relationShip = extractJsonArray(relationshipList, "relationship");
197         if (relationShip != null) {
198             for (int i = 0; i < relationShip.size(); ++i) {
199                 final JSONObject object = relationShip.getJSONObject(i);
200                 if (object.getString("related-to").equals(field)) {
201                     return object;
202                 }
203             }
204         }
205         return null;
206     }
207
208     private JSONArray getInstances(String response) {
209         JSONArray results = extractJsonArray(JSONObject.parseObject(response), "results");
210         JSONObject pInterface = extractJsonObject(results.getJSONObject(0), "service-subscription");
211         JSONObject serviceInstances = extractJsonObject(pInterface, "service-instances");
212         JSONArray instance = extractJsonArray(serviceInstances, "service-instance");
213         return instance;
214     }
215
216     private JSONObject extractJsonObject(JSONObject obj, String key) {
217         if (obj != null && key != null && obj.containsKey(key)) {
218             return obj.getJSONObject(key);
219         }
220         return null;
221     }
222
223     private JSONArray extractJsonArray(JSONObject obj, String key) {
224         if (obj != null && key != null && obj.containsKey(key)) {
225             return obj.getJSONArray(key);
226         }
227         return null;
228     }
229
230     private MultivaluedMap getAaiHeaders() {
231         return headers;
232     }
233
234     private String getHostAddr() {
235         String[] msbInfo = MicroServiceConfig.getMsbServerAddrWithHttpPrefix().split(":");
236         StringBuilder sb = new StringBuilder("http://");
237         sb.append(msbInfo[0]).append(msbInfo[1]);
238         return sb.toString();
239     }
240
241     private String extractValueFromJsonArray(JSONArray relationshipData, String keyName) {
242         for (int i = 0; i < relationshipData.size(); ++i) {
243             JSONObject item = relationshipData.getJSONObject(i);
244             if (item.getString("relationship-key").equals(keyName)) {
245                 return item.getString("relationship-value");
246             }
247         }
248         return null;
249     }
250 }