Update AAI Assistant Tools for CCVPN Extension
[holmes/common.git] / holmes-actions / src / main / java / org / onap / holmes / common / aai / AaiJsonParserUtil.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.onap.holmes.common.aai
4  * ================================================================================
5  * Copyright (C) 2018-2019 Huawei. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.holmes.common.aai;
22
23 import com.alibaba.fastjson.JSONArray;
24 import com.alibaba.fastjson.JSONObject;
25 import lombok.extern.slf4j.Slf4j;
26 import org.jvnet.hk2.annotations.Service;
27 import org.onap.holmes.common.aai.config.AaiConfig;
28 import org.onap.holmes.common.config.MicroServiceConfig;
29 import org.onap.holmes.common.exception.CorrelationException;
30
31 import javax.ws.rs.client.Client;
32 import javax.ws.rs.client.ClientBuilder;
33 import javax.ws.rs.client.WebTarget;
34 import javax.ws.rs.core.MultivaluedHashMap;
35 import javax.ws.rs.core.MultivaluedMap;
36 import javax.ws.rs.core.Response;
37 import java.util.Map;
38 import java.util.regex.Matcher;
39 import java.util.regex.Pattern;
40
41
42 @Service
43 @Slf4j
44 public class AaiJsonParserUtil {
45
46     public static String getPath(String urlTemplate, String paramName, String paramValue) {
47         return urlTemplate.replaceAll("\\{" + paramName + "\\}", paramValue);
48     }
49
50     public static String getPath(String serviceInstancePath) {
51         Pattern pattern = Pattern.compile("/aai/(v\\d+)/([A-Za-z0-9\\-]+[^/])(/*.*)");
52         Matcher matcher = pattern.matcher(serviceInstancePath);
53         String ret = "/api";
54         if (matcher.find()) {
55             ret += "/aai-" + matcher.group(2) + "/" + matcher.group(1) + matcher.group(3);
56         }
57
58         return ret;
59     }
60
61     public static Response get(String host, String path) throws CorrelationException {
62         Client client = ClientBuilder.newClient();
63         WebTarget target = client.target(host).path(path);
64         try {
65             Response response = target.request().headers(getAaiHeaders()).get();
66             if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
67                 throw new CorrelationException("Failed to connect to AAI. \nCause: "
68                                                        + response.getStatusInfo().getReasonPhrase() + "\nDetails: \n"
69                                                        + getErrorMsg(String.format("%s%s", host, path), null, response));
70             }
71             return response;
72         } catch (CorrelationException e) {
73             throw e;
74         } catch (Exception e) {
75             throw new CorrelationException(e.getMessage() + "More info: "
76                                                    + getErrorMsg(String.format("%s%s", host, path), null, null), e);
77         }
78     }
79
80     public static JSONObject getInfo(String response, String field) {
81         JSONObject jObject = JSONObject.parseObject(response);
82         JSONObject relationshipList = extractJsonObject(jObject, "relationship-list");
83         JSONArray relationShip = extractJsonArray(relationshipList, "relationship");
84         if (relationShip != null) {
85             for (int i = 0; i < relationShip.size(); ++i) {
86                 final JSONObject object = relationShip.getJSONObject(i);
87                 if (object.getString("related-to").equals(field)) {
88                     return object;
89                 }
90             }
91         }
92         return null;
93     }
94
95     public static JSONObject extractJsonObject(JSONObject obj, String key) {
96         if (obj != null && key != null && obj.containsKey(key)) {
97             return obj.getJSONObject(key);
98         }
99         return null;
100     }
101
102     public static JSONArray extractJsonArray(JSONObject obj, String key) {
103         if (obj != null && key != null && obj.containsKey(key)) {
104             return obj.getJSONArray(key);
105         }
106         return null;
107     }
108
109     public static String getHostAddr() {
110         return MicroServiceConfig.getMsbServerAddrWithHttpPrefix();
111     }
112
113     public static String getErrorMsg(String url, Map<String, Object> body, Response response) {
114         StringBuilder sb = new StringBuilder();
115         sb.append("Rerquest URL: ").append(url).append("\n");
116         sb.append("Request Header: ").append(JSONObject.toJSONString(getAaiHeaders())).append("\n");
117         if (body != null) {
118             sb.append("Request Body: ").append(JSONObject.toJSONString(body)).append("\n");
119         }
120         if (response != null) {
121             sb.append("Request Body: ").append(response.readEntity(String.class));
122         }
123         return sb.toString();
124     }
125
126     public static MultivaluedMap getAaiHeaders() {
127         MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
128         headers.add("X-TransactionId", AaiConfig.X_TRANSACTION_ID);
129         headers.add("X-FromAppId", AaiConfig.X_FROMAPP_ID);
130         headers.add("Authorization", AaiConfig.getAuthenticationCredentials());
131         headers.add("Accept", "application/json");
132         headers.add("Content-Type", "application/json");
133         return headers;
134     }
135 }