X-Git-Url: https://gerrit.onap.org/r/gitweb?a=blobdiff_plain;f=src%2Fmain%2Fjava%2Forg%2Fonap%2Fclamp%2Fclds%2Fclient%2FDcaeInventoryServices.java;h=6bab2303f388ced8609a2385a4f695d30a29760f;hb=27643f6e0e807c25230214df188f88a3cf0ab2a4;hp=8f80e07ca074294e363c8c5e8a560e5642efa288;hpb=f696add81ddfb39e6c6cdf77871fdcc19cb2b419;p=clamp.git diff --git a/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java b/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java index 8f80e07c..6bab2303 100644 --- a/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java +++ b/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP CLAMP * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights * reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,7 +18,7 @@ * limitations under the License. * ============LICENSE_END============================================ * =================================================================== - * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * */ package org.onap.clamp.clds.client; @@ -26,12 +26,9 @@ package org.onap.clamp.clds.client; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.node.ObjectNode; -import java.io.BufferedReader; import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; import java.util.Date; import java.util.List; @@ -41,33 +38,37 @@ import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; +import org.onap.clamp.clds.config.ClampProperties; import org.onap.clamp.clds.dao.CldsDao; import org.onap.clamp.clds.model.CldsEvent; import org.onap.clamp.clds.model.CldsModel; import org.onap.clamp.clds.model.DcaeEvent; -import org.onap.clamp.clds.model.prop.Global; -import org.onap.clamp.clds.model.prop.ModelProperties; -import org.onap.clamp.clds.model.refprop.RefProp; +import org.onap.clamp.clds.model.dcae.DcaeInventoryResponse; +import org.onap.clamp.clds.model.properties.Global; +import org.onap.clamp.clds.model.properties.ModelProperties; +import org.onap.clamp.clds.util.JacksonUtils; import org.onap.clamp.clds.util.LoggingUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; /** * This class implements the communication with DCAE for the service inventory. - * */ +@Component public class DcaeInventoryServices { - protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DcaeInventoryServices.class); - protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); - protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); - - @Autowired - private RefProp refProp; + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DcaeInventoryServices.class); + protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); + protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + public static final String DCAE_INVENTORY_URL = "dcae.inventory.url"; + public static final String DCAE_INVENTORY_RETRY_INTERVAL = "dcae.intentory.retry.interval"; + public static final String DCAE_INVENTORY_RETRY_LIMIT = "dcae.intentory.retry.limit"; + public static final String DCAE_TYPE_NAME = "typeName"; + public static final String DCAE_TYPE_ID = "typeId"; @Autowired - private CldsDao cldsDao; - + private ClampProperties refProp; @Autowired - private SdcCatalogServices sdcCatalogServices; + private CldsDao cldsDao; /** * Set the event inventory. @@ -77,65 +78,64 @@ public class DcaeInventoryServices { * @param userId * The user ID * @throws ParseException - * In case of issues during the parsing of DCAE answer + * In case of DCAE Json parse exception */ - public void setEventInventory(CldsModel cldsModel, String userId) throws ParseException { + public void setEventInventory(CldsModel cldsModel, String userId) throws ParseException, InterruptedException { String artifactName = cldsModel.getControlName(); DcaeEvent dcaeEvent = new DcaeEvent(); - String isDcaeInfoAvailable = null; + DcaeInventoryResponse dcaeResponse = null; Date startTime = new Date(); LoggingUtils.setTargetContext("DCAE", "setEventInventory"); if (artifactName != null) { artifactName = artifactName + ".yml"; } try { - /* - * Below are the properties required for calling the dcae inventory - * url call - */ + // Below are the properties required for calling the dcae inventory ModelProperties prop = new ModelProperties(cldsModel.getName(), cldsModel.getControlName(), null, false, "{}", cldsModel.getPropText()); Global global = prop.getGlobal(); String invariantServiceUuid = global.getService(); List resourceUuidList = global.getResourceVf(); - String serviceUuid = sdcCatalogServices.getServiceUuidFromServiceInvariantId(invariantServiceUuid); String resourceUuid = ""; if (resourceUuidList != null && !resourceUuidList.isEmpty()) { resourceUuid = resourceUuidList.get(0); } - /* Invemtory service url is called in this method */ - isDcaeInfoAvailable = getDcaeInformation(artifactName, serviceUuid, resourceUuid); - + /* Inventory service url is called in this method */ + dcaeResponse = getDcaeInformation(artifactName, invariantServiceUuid, resourceUuid); /* set dcae events */ dcaeEvent.setArtifactName(artifactName); dcaeEvent.setEvent(DcaeEvent.EVENT_DISTRIBUTION); - + LoggingUtils.setResponseContext("0", "Set inventory success", this.getClass().getName()); } catch (JsonProcessingException e) { + LoggingUtils.setResponseContext("900", "Set inventory failed", this.getClass().getName()); + LoggingUtils.setErrorContext("900", "Set inventory error"); logger.error("Error during JSON decoding", e); } catch (IOException ex) { - logger.error("Error during JSON decoding", ex); + LoggingUtils.setResponseContext("900", "Set inventory failed", this.getClass().getName()); + LoggingUtils.setErrorContext("900", "Set inventory error"); + logger.error("Error during DCAE communication", ex); } finally { LoggingUtils.setTimeContext(startTime, new Date()); metricsLogger.info("setEventInventory complete"); } - /* Null whether the DCAE has items lenght or not */ - if (isDcaeInfoAvailable != null) { - /* Inserting Event in to DB */ - logger.info(isDcaeInfoAvailable); - JSONParser parser = new JSONParser(); - Object obj0 = parser.parse(isDcaeInfoAvailable); - JSONObject jsonObj = (JSONObject) obj0; + this.analyzeAndSaveDcaeResponse(dcaeResponse, cldsModel, dcaeEvent, userId); + } + + private void analyzeAndSaveDcaeResponse(DcaeInventoryResponse dcaeResponse, CldsModel cldsModel, + DcaeEvent dcaeEvent, String userId) { + if (dcaeResponse != null) { + logger.info("Dcae Response for query on inventory: " + dcaeResponse); String oldTypeId = cldsModel.getTypeId(); String newTypeId = ""; - if (jsonObj.get("typeId") != null) { - newTypeId = jsonObj.get("typeId").toString(); - cldsModel.setTypeId(jsonObj.get("typeId").toString()); + if (dcaeResponse.getTypeId() != null) { + newTypeId = dcaeResponse.getTypeId(); + cldsModel.setTypeId(dcaeResponse.getTypeId()); } - // cldsModel.setTypeName(cldsModel.getControlName().toString()+".yml"); - if (jsonObj.get("typeName") != null) { - cldsModel.setTypeName(jsonObj.get("typeName").toString()); + if (dcaeResponse.getTypeName() != null) { + cldsModel.setTypeName(dcaeResponse.getTypeName()); } - if (oldTypeId == null || !oldTypeId.equalsIgnoreCase(newTypeId)) { + if (oldTypeId == null || !oldTypeId.equalsIgnoreCase(newTypeId) + || cldsModel.getEvent().getActionCd().equalsIgnoreCase(CldsEvent.ACTION_SUBMITDCAE)) { CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userId, dcaeEvent.getCldsActionCd(), CldsEvent.ACTION_STATE_RECEIVED, null); } @@ -154,72 +154,134 @@ public class DcaeInventoryServices { * The service UUID * @param resourceUuid * The resource UUID - * @return The DCAE inventory for the artifact + * @return The DCAE inventory for the artifact in DcaeInventoryResponse * @throws IOException * In case of issues with the stream * @throws ParseException * In case of issues with the Json parsing */ - public String getDcaeInformation(String artifactName, String serviceUuid, String resourceUuid) - throws IOException, ParseException { + public DcaeInventoryResponse getDcaeInformation(String artifactName, String serviceUuid, String resourceUuid) + throws IOException, ParseException, InterruptedException { Date startTime = new Date(); LoggingUtils.setTargetContext("DCAE", "getDcaeInformation"); - String queryString = "?sdcResourceId=" + resourceUuid + "&sdcServiceId=" + serviceUuid + "&typeName=" + String queryString = "?asdcResourceId=" + resourceUuid + "&asdcServiceId=" + serviceUuid + "&typeName=" + artifactName; - String fullUrl = refProp.getStringValue("DCAE_INVENTORY_URL") + "/dcae-service-types" + queryString; - + String fullUrl = refProp.getStringValue(DCAE_INVENTORY_URL) + "/dcae-service-types" + queryString; logger.info("Dcae Inventory Service full url - " + fullUrl); - String daceInventoryResponse = null; - URL inventoryUrl = new URL(fullUrl); - - HttpURLConnection conn = (HttpURLConnection) inventoryUrl.openConnection(); - conn.setRequestMethod("GET"); - String reqid = LoggingUtils.getRequestId(); - logger.info("reqid set to " + reqid); - conn.setRequestProperty("X-ECOMP-RequestID", reqid); - - boolean requestFailed = true; - int responseCode = conn.getResponseCode(); - if (responseCode == 200) { - requestFailed = false; - } - - StringBuilder response = new StringBuilder(); - - try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { - String inputLine = null; - - while ((inputLine = in.readLine()) != null) { - response.append(inputLine); - } - } - String responseStr = response.toString(); - if (responseStr != null) { - if (requestFailed) { - logger.error("requestFailed - responseStr=" + response); - throw new BadRequestException(responseStr); - } - } - String jsonResponseString = response.toString(); + String dcaeInventoryResponse = null; + String responseStr = queryDCAEInventory(fullUrl); JSONParser parser = new JSONParser(); - Object obj0 = parser.parse(jsonResponseString); - + Object obj0 = parser.parse(responseStr); JSONObject jsonObj = (JSONObject) obj0; - Long totalCount = (Long) jsonObj.get("totalCount"); - int numServices = totalCount.intValue(); - if (numServices == 0) { - daceInventoryResponse = null; - } else if (numServices > 0) { + if (numServices > 0) { JSONArray itemsArray = (JSONArray) jsonObj.get("items"); JSONObject dcaeServiceType0 = (JSONObject) itemsArray.get(0); - daceInventoryResponse = dcaeServiceType0.toString(); - logger.info(daceInventoryResponse); + dcaeInventoryResponse = dcaeServiceType0.toString(); + logger.info("getDcaeInformation, answer from DCAE inventory:" + dcaeInventoryResponse); } + LoggingUtils.setResponseContext("0", "Get Dcae Information success", this.getClass().getName()); LoggingUtils.setTimeContext(startTime, new Date()); metricsLogger.info("getDcaeInformation complete: number services returned=" + numServices); - return daceInventoryResponse; + return JacksonUtils.getObjectMapperInstance().readValue(dcaeInventoryResponse, DcaeInventoryResponse.class); } + private String queryDCAEInventory(String fullUrl) throws IOException, InterruptedException { + int retryInterval = 0; + int retryLimit = 1; + if (refProp.getStringValue(DCAE_INVENTORY_RETRY_LIMIT) != null) { + retryLimit = Integer.valueOf(refProp.getStringValue(DCAE_INVENTORY_RETRY_LIMIT)); + } + if (refProp.getStringValue(DCAE_INVENTORY_RETRY_INTERVAL) != null) { + retryInterval = Integer.valueOf(refProp.getStringValue(DCAE_INVENTORY_RETRY_INTERVAL)); + } + int i = 0; + while (i < retryLimit) { + i++; + try { + return DcaeHttpConnectionManager.doDcaeHttpQuery(fullUrl, "GET", null, null); + } catch (BadRequestException e) { + if (i == retryLimit) { + // reach the retry limit, but still failed to connect to + // DCAE + throw e; + } else { + // wait for a while and try to connect to DCAE again + Thread.sleep(retryInterval); + } + } + } + // normally it should not go to this branch. It should either return the + // DCAE query result, or throw exception + return null; + } + + /** + * Inserts a new DCAEServiceType or updates an existing instance. If the + * typeName is same second time(already exists) then the + * DCAEServiceTypeRequest is updated + * + * @param blueprintTemplate + * blueprint content + * @param owner + * owner of the data + * @param typeName + * The type/artifact Name + * @param typeVersion + * type version + * @param asdcServiceId + * The service UUID + * @param asdcResourceId + * The vf UUID + * @return The DCAE inventory type id + */ + public String createupdateDCAEServiceType(String blueprintTemplate, String owner, String typeName, int typeVersion, + String asdcServiceId, String asdcResourceId) { + Date startTime = new Date(); + LoggingUtils.setTargetContext("DCAE", "createDCAEServiceType"); + String typeId = null; + try { + ObjectNode dcaeServiceTypeRequest = JacksonUtils.getObjectMapperInstance().createObjectNode(); + dcaeServiceTypeRequest.put("blueprintTemplate", blueprintTemplate); + dcaeServiceTypeRequest.put("owner", owner); + dcaeServiceTypeRequest.put("typeName", typeName); + dcaeServiceTypeRequest.put("typeVersion", typeVersion); + dcaeServiceTypeRequest.put("asdcServiceId", asdcServiceId); + dcaeServiceTypeRequest.put("asdcResourceId", asdcResourceId); + String apiBodyString = dcaeServiceTypeRequest.toString(); + logger.info("Dcae api Body String - " + apiBodyString); + String url = refProp.getStringValue(DCAE_INVENTORY_URL) + "/dcae-service-types"; + String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(url, "POST", apiBodyString, + "application/json"); + // If the DCAEServiceTypeRequest is created successfully it will + // return a json object responce containing a node for newly created + // "typeId" + // The newly generated DCAEServiceTypeRequest can then be accessed + // via URL: https:///dcae-service-types/ + JSONParser parser = new JSONParser(); + Object obj0 = parser.parse(responseStr); + JSONObject jsonObj = (JSONObject) obj0; + typeId = (String) jsonObj.get("typeId"); // need to save this + // as + // service_type_id + // in model table + } catch (IOException | ParseException e) { + logger.error("Exception occurred during createupdateDCAEServiceType Operation with DCAE", e); + throw new BadRequestException("Exception occurred during createupdateDCAEServiceType Operation with DCAE", + e); + } finally { + if (typeId != null) { + LoggingUtils.setResponseContext("0", "Create update DCAE ServiceType success", + this.getClass().getName()); + } else { + LoggingUtils.setResponseContext("900", "Create update DCAE ServiceType failed", + this.getClass().getName()); + LoggingUtils.setErrorContext("900", "Create update DCAE ServiceType error"); + } + LoggingUtils.setTimeContext(startTime, new Date()); + metricsLogger.info("createupdateDCAEServiceType complete"); + } + return typeId; + } }