Upgrade sonar plugin
[vid.git] / vid-app-common / src / main / java / org / openecomp / vid / aai / AaiClient.java
1 package org.openecomp.vid.aai;
2
3 import org.apache.http.HttpStatus;
4 import org.codehaus.jackson.map.ObjectMapper;
5 import org.ecomp.aai.model.AaiAICZones.AicZones;
6 import org.json.simple.JSONArray;
7 import org.json.simple.JSONObject;
8 import org.json.simple.parser.JSONParser;
9 import org.openecomp.aai.util.AAIRestInterface;
10 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
11 import org.openecomp.vid.aai.model.ServiceRelationships;
12 import org.openecomp.vid.aai.model.AaiGetServicesRequestModel.GetServicesAAIRespone;
13 import org.openecomp.vid.aai.model.AaiGetTenatns.GetTenantsResponse;
14 import org.openecomp.vid.model.SubscriberList;
15 import org.springframework.beans.factory.annotation.Autowired;
16
17 import javax.servlet.ServletContext;
18 import javax.ws.rs.BadRequestException;
19 import javax.ws.rs.WebApplicationException;
20 import javax.ws.rs.core.Response;
21 import java.io.File;
22 import java.io.IOException;
23 import java.text.DateFormat;
24 import java.text.SimpleDateFormat;
25 import java.util.Date;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.UUID;
29
30
31 /**
32  * Created by Oren on 7/4/17.
33  */
34 public class AaiClient implements AaiClientInterface {
35
36     /**
37      * The Constant dateFormat.
38      */
39     final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
40     protected String fromAppId = "VidAaiController";
41     @Autowired
42     ServletContext servletContext;
43     /**
44      * The logger
45      */
46
47     EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AaiClient.class);
48
49
50     public AaiClient() {
51         //        certiPath = getCertificatesFile().getAbsolutePath();
52         //        depth = "0";
53     }
54
55     public AaiClient(ServletContext context) {
56         servletContext = context;
57     }
58
59
60     private static String checkForNull(String local) {
61         if (local != null)
62             return local;
63         else
64             return "";
65
66     }
67
68     @Override
69     public AaiResponse<SubscriberList> getAllSubscribers() {
70         String certiPath = getCertificatesFile().getAbsolutePath();
71         String depth = "0";
72         Response resp = doAaiGet(certiPath, "business/customers?subscriber-type=INFRA&depth=" + depth, false);
73         return proccessAaiResponse(resp, SubscriberList.class, null);
74     }
75
76
77     @Override
78     public AaiResponse getAllAicZones() {
79         String certiPath = getCertificatesFile().getAbsolutePath();
80         Response resp = doAaiGet(certiPath, "network/zones", false);
81         AaiResponse aaiAicZones = proccessAaiResponse(resp, AicZones.class, null);
82         return aaiAicZones;
83     }
84     
85     
86         @Override
87         public AaiResponse<String> getAicZoneForPnf(String globalCustomerId , String serviceType , String serviceId) {
88                 String certiPath = getCertificatesFile().getAbsolutePath();
89                 String aicZonePath = "business/customers/customer/" + globalCustomerId + "/service-subscriptions/service-subscription/" + serviceType + "/service-instances/service-instance/" + serviceId;
90                 Response resp = doAaiGet(certiPath , aicZonePath , false);
91                 AaiResponse<ServiceRelationships> aaiResponse = proccessAaiResponse(resp , ServiceRelationships.class , null);
92                 ServiceRelationships serviceRelationships = (ServiceRelationships)aaiResponse.getT();
93                 String aicZone = serviceRelationships.getRelationshipList().getRelationship().get(0).getRelatedToPropertyList().get(0).getPropertyValue();
94                 AaiResponse<String> aaiAicZonaForPnfResponse = new AaiResponse(aicZone , null ,HttpStatus.SC_OK);
95                 return  aaiAicZonaForPnfResponse;
96         }
97     
98
99     @Override
100     public AaiResponse getVNFData() {
101         String certiPath = getCertificatesFile().getAbsolutePath();
102         String payload = "{\"start\": [\"/business/customers/customer/e433710f-9217-458d-a79d-1c7aff376d89/service-subscriptions/service-subscription/VIRTUAL%20USP/service-instances/service-instance/3f93c7cb-2fd0-4557-9514-e189b7b04f9d\"], \"query\": \"query/vnf-topology-fromServiceInstance\"}";
103         Response resp = doAaiPut(certiPath, "query?format=simple", payload, false);
104         return proccessAaiResponse(resp, AaiGetVnfResponse.class, null);
105
106     }
107
108     @Override
109     public Response getVNFData(String globalSubscriberId, String serviceType) {
110         String certiPath = getCertificatesFile().getAbsolutePath();
111         String payload = "{\"start\": [\"business/customers/customer/" + globalSubscriberId + "/service-subscriptions/service-subscription/"+ serviceType +"/service-instances\"]," +
112                 "\"query\": \"query/vnf-topology-fromServiceInstance\"}";
113         return doAaiPut(certiPath, "query?format=simple", payload, false);
114
115     }
116
117     @Override
118     public AaiResponse getVNFData(String globalSubscriberId, String serviceType, String serviceInstanceId) {
119         String certiPath = getCertificatesFile().getAbsolutePath();
120         String payload = "{\"start\": [\"/business/customers/customer/" + globalSubscriberId + "/service-subscriptions/service-subscription/" + serviceType + "/service-instances/service-instance/" + serviceInstanceId + "\"],        \"query\": \"query/vnf-topology-fromServiceInstance\"}";
121         Response resp = doAaiPut(certiPath, "query?format=simple", payload, false);
122         return proccessAaiResponse(resp, AaiGetVnfResponse.class, null);
123     }
124
125     @Override
126     public Response getVersionByInvariantId(List<String> modelInvariantId) {
127         File certiPath = getCertificatesFile();
128         StringBuilder sb = new StringBuilder();
129         for (String id : modelInvariantId){
130             sb.append("&model-invariant-id=");
131             sb.append(id);
132
133         }
134         Response resp = doAaiGet(certiPath.getAbsolutePath(), "service-design-and-creation/models?depth=2"+ sb.toString(), false);
135         return resp;
136     }
137
138     @Override
139     public AaiResponse getSubscriberData(String subscriberId) {
140         File certiPath = getCertificatesFile();
141         String depth = "2";
142         AaiResponse subscriberDataResponse;
143         Response resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + subscriberId + "?depth=" + depth, false);
144         subscriberDataResponse = proccessAaiResponse(resp, Services.class, null);
145         return subscriberDataResponse;
146     }
147
148     @Override
149     public AaiResponse getServices() {
150         File certiPath = getCertificatesFile();
151         Response resp = doAaiGet(certiPath.getAbsolutePath(), "service-design-and-creation/services", false);
152         AaiResponse<GetServicesAAIRespone> getServicesResponse = proccessAaiResponse(resp, GetServicesAAIRespone.class, null);
153
154         return getServicesResponse;
155     }
156
157     @Override
158     public AaiResponse getTenants(String globalCustomerId, String serviceType) {
159         File certiPath = getCertificatesFile();
160         String url = "business/customers/customer/" + globalCustomerId + "/service-subscriptions/service-subscription/" + serviceType;
161
162         Response resp = doAaiGet(certiPath.getAbsolutePath(), url, false);
163         String responseAsString = parseForTenantsByServiceSubscription(resp.readEntity(String.class));
164
165         AaiResponse<GetTenantsResponse[]> getTenantsResponse = proccessAaiResponse(resp, GetTenantsResponse[].class, responseAsString);
166         return getTenantsResponse;
167     }
168
169     private AaiResponse proccessAaiResponse(Response resp, Class classType, String responseBody) {
170         AaiResponse subscriberDataResponse;
171         if (resp == null) {
172             subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR);
173             logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "Invalid response from AAI");
174         } else {
175             logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getSubscribers() resp=" + resp.getStatusInfo().toString());
176             if (resp.getStatus() != HttpStatus.SC_OK) {
177                 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "Invalid response from AAI");
178                 subscriberDataResponse = new AaiResponse<>(null, resp.readEntity(String.class), resp.getStatus());
179             } else {
180                 String finalResponse;
181                 try {
182                     if (responseBody != null) {
183                         finalResponse = responseBody;
184                     } else {
185                         finalResponse = resp.readEntity(String.class);
186                     }
187
188                     subscriberDataResponse = new AaiResponse<>((new ObjectMapper().readValue(finalResponse, classType)), null, HttpStatus.SC_OK);
189
190                 } catch (IOException e) {
191                     subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR);
192                 }
193
194             }
195         }
196         return subscriberDataResponse;
197     }
198
199     private File getCertificatesFile() {
200         if (servletContext != null)
201             return new File(servletContext.getRealPath("/WEB-INF/cert/"));
202         return null;
203     }
204
205     @SuppressWarnings("all")
206     protected Response doAaiGet(String certiPath, String uri, boolean xml) {
207         String methodName = "doAaiGet";
208         String transId = UUID.randomUUID().toString();
209         logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
210
211         Response resp = null;
212         try {
213
214             AAIRestInterface restContrller = new AAIRestInterface(certiPath);
215             resp = restContrller.RestGet(fromAppId, transId, uri, xml);
216
217         } catch (WebApplicationException e) {
218             final String message = ((BadRequestException) e).getResponse().readEntity(String.class);
219             logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message);
220             logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message);
221         } catch (Exception e) {
222             logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
223             logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
224         }
225
226         return resp;
227     }
228
229     private String parseForTenantsByServiceSubscription(String resp) {
230         String tenantList = "";
231
232         try {
233             JSONParser jsonParser = new JSONParser();
234
235             JSONObject jsonObject = (JSONObject) jsonParser.parse(resp);
236
237             return parseServiceSubscriptionObjectForTenants(jsonObject);
238         } catch (Exception ex) {
239
240         }
241
242         return tenantList;
243     }
244
245     protected Response doAaiPut(String certiPath, String uri, String payload, boolean xml) {
246         String methodName = "doAaiPut";
247         String transId = UUID.randomUUID().toString();
248         logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
249
250         Response resp = null;
251         try {
252
253             AAIRestInterface restContrller = new AAIRestInterface(certiPath);
254             resp = restContrller.RestPut(fromAppId, transId, uri, payload, xml);
255
256         } catch (Exception e) {
257             logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
258             logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
259         }
260
261         return resp;
262     }
263
264
265     public static String parseServiceSubscriptionObjectForTenants(JSONObject jsonObject) {
266
267         JSONArray tenantArray = new JSONArray();
268         boolean bconvert = false;
269
270         try {
271             JSONObject relationShipListsObj = (JSONObject) jsonObject.get("relationship-list");
272             if (relationShipListsObj != null) {
273                 JSONArray rShipArray = (JSONArray) relationShipListsObj.get("relationship");
274                 if (rShipArray != null) {
275                     Iterator i1 = rShipArray.iterator();
276
277                     while (i1.hasNext()) {
278
279                         JSONObject inner1Obj = (JSONObject) i1.next();
280
281                         if (inner1Obj == null)
282                             continue;
283
284                         String relatedTo = checkForNull((String) inner1Obj.get("related-to"));
285                         if (relatedTo.equalsIgnoreCase("tenant")) {
286                             JSONObject tenantNewObj = new JSONObject();
287
288                             String relatedLink = checkForNull((String) inner1Obj.get("related-link"));
289                             tenantNewObj.put("link", relatedLink);
290
291                             JSONArray rDataArray = (JSONArray) inner1Obj.get("relationship-data");
292                             if (rDataArray != null) {
293                                 Iterator i2 = rDataArray.iterator();
294
295                                 while (i2.hasNext()) {
296                                     JSONObject inner2Obj = (JSONObject) i2.next();
297
298                                     if (inner2Obj == null)
299                                         continue;
300
301                                     String rShipKey = checkForNull((String) inner2Obj.get("relationship-key"));
302                                     String rShipVal = checkForNull((String) inner2Obj.get("relationship-value"));
303                                     if (rShipKey.equalsIgnoreCase("cloud-region.cloud-owner")) {
304                                         tenantNewObj.put("cloudOwner", rShipVal);
305                                     } else if (rShipKey.equalsIgnoreCase("cloud-region.cloud-region-id")) {
306                                         tenantNewObj.put("cloudRegionID", rShipVal);
307                                     }
308
309                                     if (rShipKey.equalsIgnoreCase("tenant.tenant-id")) {
310                                         tenantNewObj.put("tenantID", rShipVal);
311                                     }
312                                 }
313                             }
314
315                             JSONArray relatedTPropArray = (JSONArray) inner1Obj.get("related-to-property");
316                             if (relatedTPropArray != null) {
317                                 Iterator i3 = relatedTPropArray.iterator();
318
319                                 while (i3.hasNext()) {
320                                     JSONObject inner3Obj = (JSONObject) i3.next();
321
322                                     if (inner3Obj == null)
323                                         continue;
324
325                                     String propKey = checkForNull((String) inner3Obj.get("property-key"));
326                                     String propVal = checkForNull((String) inner3Obj.get("property-value"));
327                                     if (propKey.equalsIgnoreCase("tenant.tenant-name")) {
328                                         tenantNewObj.put("tenantName", propVal);
329                                     }
330                                 }
331                             }
332                             bconvert = true;
333                             tenantArray.add(tenantNewObj);
334                         }
335                     }
336
337                 }
338             }
339         } catch (NullPointerException ex) {
340
341
342         }
343
344         if (bconvert)
345             return tenantArray.toJSONString();
346         else
347             return "";
348
349     }
350
351
352 }