Fixed the CLM Issues
[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-2020 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.google.gson.Gson;
24 import com.google.gson.JsonArray;
25 import com.google.gson.JsonObject;
26 import com.google.gson.JsonParser;
27 import lombok.extern.slf4j.Slf4j;
28 import org.jvnet.hk2.annotations.Service;
29 import org.onap.holmes.common.aai.config.AaiConfig;
30 import org.onap.holmes.common.config.MicroServiceConfig;
31 import org.onap.holmes.common.exception.CorrelationException;
32
33 import javax.ws.rs.client.Client;
34 import javax.ws.rs.client.ClientBuilder;
35 import javax.ws.rs.client.WebTarget;
36 import javax.ws.rs.core.MultivaluedHashMap;
37 import javax.ws.rs.core.MultivaluedMap;
38 import javax.ws.rs.core.Response;
39 import java.util.Map;
40 import java.util.regex.Matcher;
41 import java.util.regex.Pattern;
42
43
44 @Service
45 @Slf4j
46 public class AaiJsonParserUtil {
47
48     public static String getPath(String urlTemplate, String paramName, String paramValue) {
49         return urlTemplate.replaceAll("\\{" + paramName + "\\}", paramValue);
50     }
51
52     public static String getPath(String serviceInstancePath) {
53         Pattern pattern = Pattern.compile("/aai/(v\\d+)/([A-Za-z0-9\\-]+[^/])(/*.*)");
54         Matcher matcher = pattern.matcher(serviceInstancePath);
55         String ret = "/api";
56         if (matcher.find()) {
57             ret += "/aai-" + matcher.group(2) + "/" + matcher.group(1) + matcher.group(3);
58         }
59
60         return ret;
61     }
62
63     public static Response get(String host, String path) throws CorrelationException {
64         Client client = ClientBuilder.newClient();
65         WebTarget target = client.target(host).path(path);
66         try {
67             Response response = target.request().headers(getAaiHeaders()).get();
68             if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
69                 throw new CorrelationException("Failed to connect to AAI. \nCause: "
70                                                        + response.getStatusInfo().getReasonPhrase() + "\nDetails: \n"
71                                                        + getErrorMsg(String.format("%s%s", host, path), null, response));
72             }
73             return response;
74         } catch (CorrelationException e) {
75             throw e;
76         } catch (Exception e) {
77             throw new CorrelationException(e.getMessage() + "More info: "
78                                                    + getErrorMsg(String.format("%s%s", host, path), null, null), e);
79         }
80     }
81
82     public static JsonObject getInfo(String response, String field) {
83         JsonObject jObject = JsonParser.parseString(response).getAsJsonObject();
84         JsonObject relationshipList = extractJsonObject(jObject, "relationship-list");
85         JsonArray relationShip = extractJsonArray(relationshipList, "relationship");
86         if (relationShip != null) {
87             for (int i = 0; i < relationShip.size(); ++i) {
88                 final JsonObject object = relationShip.get(i).getAsJsonObject();
89                 if (object.get("related-to").getAsString().equals(field)) {
90                     return object;
91                 }
92             }
93         }
94         return null;
95     }
96
97     public static JsonObject extractJsonObject(JsonObject obj, String key) {
98         if (obj != null && key != null && obj.has(key)) {
99             return obj.get(key).getAsJsonObject();
100         }
101         return null;
102     }
103
104     public static JsonArray extractJsonArray(JsonObject obj, String key) {
105         if (obj != null && key != null && obj.has(key)) {
106             return obj.get(key).getAsJsonArray();
107         }
108         return null;
109     }
110
111     public static String getHostAddr() {
112         return MicroServiceConfig.getMsbServerAddrWithHttpPrefix();
113     }
114
115     public static String getErrorMsg(String url, Map<String, Object> body, Response response) {
116         Gson gson = new Gson();
117         StringBuilder sb = new StringBuilder();
118         sb.append("Rerquest URL: ").append(url).append("\n");
119         sb.append("Request Header: ").append(gson.toJson(getAaiHeaders())).append("\n");
120         if (body != null) {
121             sb.append("Request Body: ").append(gson.toJson(body)).append("\n");
122         }
123         if (response != null) {
124             sb.append("Request Body: ").append(response.readEntity(String.class));
125         }
126         return sb.toString();
127     }
128
129     public static MultivaluedMap getAaiHeaders() {
130         MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
131         headers.add("X-TransactionId", AaiConfig.X_TRANSACTION_ID);
132         headers.add("X-FromAppId", AaiConfig.X_FROMAPP_ID);
133         headers.add("Authorization", AaiConfig.getAuthenticationCredentials());
134         headers.add("Accept", "application/json");
135         headers.add("Content-Type", "application/json");
136         return headers;
137     }
138 }