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