diff options
Diffstat (limited to 'dcaedt_be/src')
51 files changed, 2725 insertions, 1520 deletions
diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/BaseController.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/BaseController.java index 8b590ca..818a30d 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/BaseController.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/BaseController.java @@ -42,12 +42,12 @@ public abstract class BaseController { return request.getAttribute("requestId").toString(); } - Asset checkout(String userId, String uuid, AssetType assetType, String requestId) throws Exception { - return baseBusinessLogic.getSdcRestClient().changeAssetLifecycleState(userId, uuid, LifecycleOperationType.CHECKOUT.name(), null, assetType, requestId); + ResourceDetailed checkoutVfcmt(String userId, String uuid, String requestId) { + return baseBusinessLogic.getSdcRestClient().changeResourceLifecycleState(userId, uuid, LifecycleOperationType.CHECKOUT.name(), null, requestId); } - Asset checkin(String userId, String uuid, AssetType assetType, String requestId) throws Exception { - return baseBusinessLogic.getSdcRestClient().changeAssetLifecycleState(userId, uuid, LifecycleOperationType.CHECKIN.name(), "checking in " + assetType.name() + uuid, assetType, requestId); + ResourceDetailed checkinVfcmt(String userId, String uuid, String requestId) { + return baseBusinessLogic.getSdcRestClient().changeResourceLifecycleState(userId, uuid, LifecycleOperationType.CHECKIN.name(), "checking in vfcmt" + uuid, requestId); } @@ -55,7 +55,7 @@ public abstract class BaseController { return DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT != DcaeBeConstants.LifecycleStateEnum.findState(lifecycleState); } - void checkUserIfResourceCheckedOut(String userId, Asset asset) throws DcaeException { + void checkUserIfResourceCheckedOut(String userId, Asset asset) { if (DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT == DcaeBeConstants.LifecycleStateEnum.findState(asset.getLifecycleState())) { String lastUpdaterUserId = asset.getLastUpdaterUserId(); if (lastUpdaterUserId != null && !lastUpdaterUserId.equals(userId)) { @@ -67,7 +67,7 @@ public abstract class BaseController { } void checkVfcmtType(ResourceDetailed vfcmt) { - if (!"VFCMT".equals(vfcmt.getResourceType()) || !"Template".equals(vfcmt.getCategory())) { + if (AssetType.VFCMT != getValidAssetTypeOrNull(vfcmt.getResourceType()) || !"Template".equals(vfcmt.getCategory())) { ResponseFormat responseFormat = ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.RESOURCE_NOT_VFCMT_ERROR, null, vfcmt.getUuid()); throw new DcaeException(HttpStatus.BAD_REQUEST, responseFormat.getRequestError()); } @@ -77,4 +77,13 @@ public abstract class BaseController { errLogger.log(LogLevel.ERROR, this.getClass().getName(), e.getMessage()); return ErrConfMgr.INSTANCE.handleException(e, apiType, variables); } + + AssetType getValidAssetTypeOrNull(String type) { + try { + return AssetType.getAssetTypeByName(type); + } catch (IllegalArgumentException e) { + debugLogger.log(LogLevel.ERROR, this.getClass().getName(), "invalid asset type: {}. Error: {}", type, e); + return null; + } + } } diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/BlueprintController.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/BlueprintController.java index a12c6b8..5f4cee7 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/BlueprintController.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/BlueprintController.java @@ -1,239 +1,54 @@ package org.onap.sdc.dcae.composition.controller; -import org.apache.commons.lang.StringUtils; -import org.onap.sdc.common.onaplog.Enums.LogLevel; -import org.onap.sdc.dcae.composition.restmodels.MessageResponse; -import org.onap.sdc.dcae.catalog.asdc.ASDC; -import org.onap.sdc.dcae.catalog.asdc.ASDCUtils; -import org.onap.sdc.dcae.catalog.asdc.Blueprinter; -import org.onap.sdc.dcae.composition.restmodels.sdc.*; -import org.onap.sdc.dcae.utils.Normalizers; -import org.onap.sdc.dcae.composition.util.DcaeBeConstants; -import org.onap.sdc.dcae.enums.ArtifactType; +import org.onap.sdc.dcae.composition.impl.BlueprintBusinessLogic; import org.onap.sdc.dcae.enums.AssetType; -import org.onap.sdc.dcae.enums.LifecycleOperationType; -import org.onap.sdc.dcae.errormng.ActionStatus; -import org.onap.sdc.dcae.errormng.ErrConfMgr; -import org.onap.sdc.dcae.errormng.ErrConfMgr.ApiType; -import org.onap.sdc.dcae.utils.SdcRestClientUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.util.Base64Utils; -import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.*; import javax.annotation.PostConstruct; -import java.io.StringReader; -import java.net.URI; @RestController @EnableAutoConfiguration @CrossOrigin -public class BlueprintController extends BaseController{ - - @Autowired - private Blueprinter blueprinter; - - @Autowired - private ASDC asdc; - - private static final String CREATE_DESC = "creating new artifact blueprint on the service vfi"; - private static final String UPDATE_DESC = "updating artifact blueprint on the service vfi"; - +public class BlueprintController extends BaseController { + @Autowired + private BlueprintBusinessLogic blueprintBusinessLogic; @PostConstruct public void init(){ - URI sdcUri = URI.create(systemProperties.getProperties().getProperty(DcaeBeConstants.Config.URI)); - asdc.setUri(sdcUri); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "SDC uri: {}", sdcUri); - } - - /*** - * VFCMT - Resource, blueprint - as an artifact as an service. - * @param userId - * @param vfcmtUuid - * @param serviceUuid - * @param serviceInstanceName - * @param monitoringFlowType - * @return ResponseEntity - */ - @RequestMapping(value = "/createBluePrint/{VFCMTUuid}/{serviceUuid}/{instanceName}/{monitoringFlowType}", method = RequestMethod.POST) - public ResponseEntity createBluePrint(@RequestHeader("USER_ID") String userId, - @PathVariable("VFCMTUuid") String vfcmtUuid, - @PathVariable("serviceUuid") String serviceUuid, - @PathVariable("instanceName") String serviceInstanceName, - @PathVariable("monitoringFlowType") String monitoringFlowType, - @ModelAttribute("requestId") String requestId) { - try { - - ResourceDetailed vfcmt = baseBusinessLogic.getSdcRestClient().getResource(vfcmtUuid, requestId); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), vfcmt.toString()); - checkVfcmtType(vfcmt); - Artifact cdumpArtifactData = findCdumpArtifactData(vfcmt); - if (null != cdumpArtifactData) { - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Found the cdump (composition.yml) on top of VFCMT {}", vfcmtUuid); - String cdump = baseBusinessLogic.getSdcRestClient().getResourceArtifact(vfcmtUuid, cdumpArtifactData.getArtifactUUID(), requestId); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "---------------------------------------------------------------CDUMP: -----------------------------------------------------------------------------"); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), cdump); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "---------------------------------------------------------------------------------------------------------------------------------------------------"); - ASDCUtils utils = new ASDCUtils(asdc, blueprinter); - - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Going to use python procedure to create a blueprint...."); - String resultBlueprintCreation; - try{ - resultBlueprintCreation = utils.buildBlueprintViaToscaLab(new StringReader(cdump)).waitForResult().waitForResult(); - }catch (Exception e){ - return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.GENERATE_BLUEPRINT_ERROR, e.getMessage(), vfcmt.getName()); - } - if (StringUtils.isEmpty(resultBlueprintCreation)) { - return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.GENERATE_BLUEPRINT_ERROR, "", vfcmt.getName()); - } - - // 1806 US374595 flowType in cdump - String flowTypeFromCdump = StringUtils.substringBetween(cdump,"\"flowType\":\"","\""); - if(StringUtils.isNotBlank(flowTypeFromCdump)) { - monitoringFlowType = flowTypeFromCdump; - } - // saving to serviceVfInstance - Artifact savedBluePrint = saveBluePrint(userId, serviceUuid, serviceInstanceName, resultBlueprintCreation, monitoringFlowType, vfcmt.getName(), requestId); - if(savedBluePrint!=null){ - MessageResponse response = new MessageResponse(); - response.setSuccessResponse("Blueprint build complete \n. Blueprint="+savedBluePrint.getArtifactName()); - //1806 US374593 - certify VFCMT after BP generation - certifyVfcmt(vfcmt, requestId); - return new ResponseEntity<>(response, HttpStatus.OK); - } - else{ - return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.SUBMIT_BLUEPRINT_ERROR); - } - - }else{ - return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.MISSING_TOSCA_FILE, "", vfcmt.getName()); - } - } catch (Exception e) { - return handleException(e, ApiType.SUBMIT_BLUEPRINT); - } - } - - - /********************* private function ********************/ - - /** - * @param userId - * @param serviceUuid - * @param resourceInstanceName - * @param bluePrint - * @param monitoringFlowType - * @param vfcmtName - * @param requestId - * @return - * @throws Exception - */ - private Artifact saveBluePrint(String userId, String serviceUuid, String resourceInstanceName, String bluePrint, String monitoringFlowType, String vfcmtName, String requestId) throws Exception { - - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "BLUEPRINT:\n{}", bluePrint); - try { - ServiceDetailed service = baseBusinessLogic.getSdcRestClient().getService(serviceUuid, requestId); - //Validations - checkUserIfResourceCheckedOut(userId, service); - ResourceInstance vfi = findVfiOnService(service, resourceInstanceName); - if(null == vfi){ - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "VF instance {} not found on service {}", resourceInstanceName, serviceUuid); - return null; - } - - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), service.toString()); - - String normalizedArtifactLabel = Normalizers.normalizeArtifactLabel("blueprint-" + monitoringFlowType); - Artifact blueprintArtifact = CollectionUtils.isEmpty(vfi.getArtifacts()) ? null : vfi.getArtifacts().stream() - .filter(p -> normalizedArtifactLabel.equals(Normalizers.normalizeArtifactLabel(p.getArtifactLabel()))) - .findAny() - .orElse(null); - - boolean isNeed2Checkout = isNeedToCheckOut(service.getLifecycleState()); - if (isNeed2Checkout) { - Asset result = checkout(userId, serviceUuid, AssetType.SERVICE, requestId); - if (result != null) { - serviceUuid = result.getUuid(); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "New service after checkout is: {}", serviceUuid); - } - } - //update mode - if (null != blueprintArtifact) { - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Found that service {} already consist of {} ----> updateMode", serviceUuid, normalizedArtifactLabel); - blueprintArtifact.setDescription(UPDATE_DESC); - blueprintArtifact.setPayloadData(Base64Utils.encodeToString(bluePrint.getBytes())); - blueprintArtifact = baseBusinessLogic.getSdcRestClient().updateVfInstanceArtifact(userId, serviceUuid, Normalizers.normalizeComponentInstanceName(resourceInstanceName), blueprintArtifact, requestId); - //create mode - } else { - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Service {} does not consist {} ----> createMode", serviceUuid, normalizedArtifactLabel); - blueprintArtifact = SdcRestClientUtils.generateDeploymentArtifact(CREATE_DESC, generateBlueprintFileName(monitoringFlowType, vfcmtName), ArtifactType.DCAE_INVENTORY_BLUEPRINT.name(), normalizedArtifactLabel, bluePrint.getBytes()); - blueprintArtifact = baseBusinessLogic.getSdcRestClient().createVfInstanceArtifact(userId, serviceUuid, Normalizers.normalizeComponentInstanceName(resourceInstanceName), blueprintArtifact, requestId); - } - - //No need to check the service in in 1806 -// Asset blueprintAsJson = checkin(user_id, serviceUuid, AssetType.SERVICE); -// debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "service result after check-in: {}", blueprintAsJson.toString()); - - return blueprintArtifact; - - } catch (Exception e) { - errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Error occurred while trying to save blueprint {}", e.toString()); - throw e; - } - } - - /** - * - * @param monitoringFlowType - * @param vfcmtName - * @return - */ - private String generateBlueprintFileName(String monitoringFlowType, String vfcmtName) { - StringBuffer sb = new StringBuffer(); - sb.append(monitoringFlowType); - sb.append("."); - sb.append(Normalizers.normalizeComponentName(vfcmtName)); - sb.append("."); - sb.append(DcaeBeConstants.Composition.fileNames.EVENT_PROC_BP_YAML); - return sb.toString(); - } - - private ResourceInstance findVfiOnService(ServiceDetailed service, String vfiName) { - return null == service ? null : CollectionUtils.isEmpty(service.getResources()) ? null : service.getResources().stream().filter(p -> vfiName.equals(p.getResourceInstanceName())).findAny().orElse(null); - } - - private Artifact findCdumpArtifactData(ResourceDetailed vfcmt) { - return null == vfcmt ? null : CollectionUtils.isEmpty(vfcmt.getArtifacts()) ? null : vfcmt.getArtifacts().stream() - .filter(p -> DcaeBeConstants.Composition.fileNames.COMPOSITION_YML.equals(p.getArtifactName())).findAny().orElse(null); - } - - private void certifyVfcmt(ResourceDetailed vfcmt, String requestId){ - String state = vfcmt.getLifecycleState(); - if(null == state) { - debugLogger.log(LogLevel.ERROR, this.getClass().getName(), "Couldn't read Vfcmt lifecycle state"); - return; - } - DcaeBeConstants.LifecycleStateEnum lifeCycleState = DcaeBeConstants.LifecycleStateEnum.findState(state); - if(null == lifeCycleState) { - debugLogger.log(LogLevel.ERROR, this.getClass().getName(), "Undefined lifecycle state: {}", state); - return; - } - try{ - switch (lifeCycleState){ - case NOT_CERTIFIED_CHECKOUT: - baseBusinessLogic.getSdcRestClient().changeResourceLifecycleState(vfcmt.getLastUpdaterUserId(), vfcmt.getUuid(), LifecycleOperationType.CHECKIN.name(), "check in VFCMT after blueprint successful submission", requestId); - case NOT_CERTIFIED_CHECKIN: - baseBusinessLogic.getSdcRestClient().changeResourceLifecycleState(vfcmt.getLastUpdaterUserId(), vfcmt.getUuid(), LifecycleOperationType.CERTIFY.name(), "certify VFCMT after blueprint successful submission", requestId); - } - } - catch (Exception e){ - //informative only. no message to user (TBA) - debugLogger.log(LogLevel.ERROR, this.getClass().getName(), "Error occurred during vfcmt lifecycle operation: {}", e.toString()); - } } + /*** + * VFCMT - Resource, blueprint - as an artifact as an service. + * @param context + * @param userId + * @param vfcmtUuid + * @param serviceUuid + * @param instanceName + * @param requestId + * @return ResponseEntity + */ + @RequestMapping(value = "{context}/createBluePrint/{VFCMTUuid}/{serviceUuid}/{instanceName}", method = RequestMethod.POST) + public ResponseEntity createBlueprint(@RequestHeader("USER_ID") String userId, + @PathVariable String context, + @PathVariable("VFCMTUuid") String vfcmtUuid, + @PathVariable("serviceUuid") String serviceUuid, + @PathVariable("instanceName") String instanceName, + @ModelAttribute("requestId") String requestId) { + return blueprintBusinessLogic.generateAndSaveBlueprint(userId, context, vfcmtUuid, serviceUuid, instanceName, "", requestId); + } + + @Deprecated + @RequestMapping(value = "/createBluePrint/{VFCMTUuid}/{serviceUuid}/{instanceName}/{monitoringFlowType}", method = RequestMethod.POST) + public ResponseEntity createBluePrintWithFlowType(@RequestHeader("USER_ID") String userId, + @PathVariable("VFCMTUuid") String vfcmtUuid, + @PathVariable("serviceUuid") String serviceUuid, + @PathVariable("instanceName") String serviceInstanceName, + @PathVariable("monitoringFlowType") String monitoringFlowType, + @ModelAttribute("requestId") String requestId) { + return blueprintBusinessLogic.generateAndSaveBlueprint(userId, AssetType.SERVICE.name(), vfcmtUuid, serviceUuid, serviceInstanceName, monitoringFlowType, requestId); + } } diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/CompositionController.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/CompositionController.java index 5cba14f..3261ddc 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/CompositionController.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/CompositionController.java @@ -3,7 +3,9 @@ package org.onap.sdc.dcae.composition.controller; import org.json.JSONArray; import org.json.JSONException; import org.onap.sdc.common.onaplog.Enums.LogLevel; +import org.onap.sdc.dcae.composition.impl.CompositionBusinessLogic; import org.onap.sdc.dcae.composition.restmodels.MessageResponse; +import org.onap.sdc.dcae.composition.restmodels.ReferenceUUID; import org.onap.sdc.dcae.composition.restmodels.sdc.Artifact; import org.onap.sdc.dcae.composition.restmodels.sdc.Asset; import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceDetailed; @@ -11,17 +13,14 @@ import org.onap.sdc.dcae.catalog.Catalog; import org.onap.sdc.dcae.catalog.Catalog.*; import org.onap.sdc.dcae.catalog.engine.*; import org.onap.sdc.dcae.composition.util.DcaeBeConstants; -import org.onap.sdc.dcae.enums.ArtifactType; import org.onap.sdc.dcae.enums.LifecycleOperationType; import org.onap.sdc.dcae.errormng.ActionStatus; import org.onap.sdc.dcae.errormng.ErrConfMgr; import org.onap.sdc.dcae.errormng.ErrConfMgr.ApiType; -import org.onap.sdc.dcae.utils.SdcRestClientUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.util.Base64Utils; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.context.request.async.DeferredResult; @@ -37,302 +36,281 @@ import java.util.stream.Collectors; @RestController @EnableAutoConfiguration @CrossOrigin -public class CompositionController extends BaseController{ - - @Autowired - private CatalogController catalogController; - - @PostConstruct - public void init() { - catalogController.setDefaultCatalog(URI.create(systemProperties.getProperties().getProperty(DcaeBeConstants.Config.ASDC_CATALOG_URL))); - } - - @RequestMapping(value = { "/utils/clone/{assetType}/{sourceId}/{targetId}" }, method = {RequestMethod.GET }, produces = { "application/json" }) - public ResponseEntity clone(@RequestHeader("USER_ID") String userId, @PathVariable("assetType") String theAssetType, @PathVariable("sourceId") String theSourceId, @PathVariable("targetId") String theTargetId, - @ModelAttribute("requestId") String requestId) { - MessageResponse response = new MessageResponse(); - - try { - // fetch the source and assert it is a vfcmt containing clone worthy artifacts (composition + rules) - ResourceDetailed sourceVfcmt = baseBusinessLogic.getSdcRestClient().getResource(theSourceId, requestId); - checkVfcmtType(sourceVfcmt); - List<Artifact> artifactsToClone = CollectionUtils.isEmpty(sourceVfcmt.getArtifacts()) ? null : sourceVfcmt.getArtifacts().stream() - .filter(p -> DcaeBeConstants.Composition.fileNames.COMPOSITION_YML.equals(p.getArtifactName()) || p.getArtifactName().endsWith(DcaeBeConstants.Composition.fileNames.MAPPING_RULE_POSTFIX)) - .collect(Collectors.toList()); - if(CollectionUtils.isEmpty(artifactsToClone)) { - response.setSuccessResponse("Nothing to clone"); - return new ResponseEntity<>(response ,HttpStatus.NO_CONTENT); - } - - // fetch the target - ResourceDetailed vfcmt = baseBusinessLogic.getSdcRestClient().getResource(theTargetId, requestId); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), vfcmt.toString()); - checkVfcmtType(vfcmt); - checkUserIfResourceCheckedOut(userId, vfcmt); - boolean isTargetNeed2Checkout = isNeedToCheckOut(vfcmt.getLifecycleState()); - if (isTargetNeed2Checkout) { - ResourceDetailed targetVfcmt = baseBusinessLogic.getSdcRestClient().changeResourceLifecycleState(userId, theTargetId, LifecycleOperationType.CHECKOUT.name(), "checking out VFCMT before clone", requestId); - if(null == targetVfcmt){ - return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.GENERAL_ERROR); - } - theTargetId = targetVfcmt.getUuid(); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "New targetVfcmt (for artifact clone) after checkout is: {}", theTargetId); - } - - Map<String, Artifact> currentArtifacts = CollectionUtils.isEmpty(vfcmt.getArtifacts()) ? new HashMap<>() : vfcmt.getArtifacts().stream() - .collect(Collectors.toMap(Artifact::getArtifactName, Function.identity())); - - //TODO target VFCMT rule artifacts should be removed - for(Artifact artifactToClone : artifactsToClone) { - String payload = baseBusinessLogic.getSdcRestClient().getResourceArtifact(theSourceId, artifactToClone.getArtifactUUID(), requestId); - baseBusinessLogic.cloneArtifactToTarget(userId, theTargetId, payload, artifactToClone, currentArtifacts.get(artifactToClone.getArtifactName()), requestId); - } - - baseBusinessLogic.getSdcRestClient().changeResourceLifecycleState(userId, theTargetId, LifecycleOperationType.CHECKIN.name(), "check in VFCMT after clone", requestId); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Cloning {} from {} has finished successfully", theSourceId, theTargetId); - response.setSuccessResponse("Clone VFCMT complete"); - return new ResponseEntity<>(response, HttpStatus.OK); - } catch (Exception e) { - return handleException(e, ApiType.CLONE_VFCMT); - } - } - - @RequestMapping(value = "/elements", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json") - public DeferredResult<CatalogResponse> items(@RequestBody(required = false) ItemsRequest theRequest) { - - final ItemsRequest request = (theRequest == null) ? ItemsRequest.EMPTY_REQUEST : theRequest; - - Catalog catalog = catalogController.getCatalog(request.getCatalog()); - DeferredResult<CatalogResponse> result = new DeferredResult<CatalogResponse>(request.getTimeout()); - - catalog.rootsByLabel(request.getStartingLabel()) - .setHandler(catalogController.new CatalogHandler<Folders>(request, result) { - public CatalogResponse handleData(Folders theFolders) { - JSONArray ja = new JSONArray(); - if (theFolders != null) { - for (Folder folder : theFolders) { - ja.put(catalogController.patchData(catalog, folder.data())); - } - } - CatalogResponse response = new CatalogResponse(this.request); - try { - response.data().put("elements", ja); - } catch (JSONException e) { - errLogger.log(LogLevel.ERROR, this.getClass().getName(), "JSONException putting json elements to response {}", e); - } - return response; - } - }); - return result; - } - - @RequestMapping(value = "/{theItemId}/elements", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json") - public DeferredResult<CatalogResponse> items(@RequestBody(required = false) ItemsRequest theRequest, @PathVariable String theItemId) { - - final ItemsRequest request = (theRequest == null) ? ItemsRequest.EMPTY_REQUEST : theRequest; - - Catalog catalog = catalogController.getCatalog(request.getCatalog()); - DeferredResult<CatalogResponse> result = new DeferredResult<CatalogResponse>(request.getTimeout()); - - catalog - // .fetchFolderByItemId(theItemId) - .folder(theItemId).withParts().withPartAnnotations().withItems().withItemAnnotations().withItemModels() - .execute().setHandler(catalogController.new CatalogHandler<Folder>(request, result) { - public CatalogResponse handleData(Folder theFolder) { - CatalogResponse response = new CatalogResponse(this.request); - if (theFolder == null) { - return response; - } - - try { - Elements folders = theFolder.elements("parts", Folders.class); - if (folders != null) { - for (Object folder : folders) { - catalogController.patchData(catalog, ((Element) folder).data()); - // lots of ephemere proxies created here .. - Elements annotations = ((Element) folder).elements("annotations", - Annotations.class); - if (annotations != null) { - for (Object a : annotations) { - catalogController.patchData(catalog, ((Annotation) a).data()); - } - } - } - } - Elements items = theFolder.elements("items", Items.class); - if (items != null) { - for (Object i : items) { - catalogController.patchData(catalog, ((Element) i).data()); - // lots of ephemere proxies created here .. - Elements annotations = ((Element) i).elements("annotations", Annotations.class); - if (annotations != null) { - for (Object a : annotations) { - catalogController.patchData(catalog, ((Annotation) a).data()); - } - } - } - } - } catch (Exception x) { - errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Exception processing catalog {}", x); - return new CatalogError(this.request, "", x); - } - - try { - response.data().put("element", theFolder.data()); - } catch (JSONException e) { - errLogger.log(LogLevel.ERROR, this.getClass().getName(), "JSONException putting element to response {}", e); - } - return response; - } - }); - - return result; - } - - @RequestMapping(value = "/{theItemId}/model", method = { RequestMethod.POST,RequestMethod.GET }, produces = "application/json") - public DeferredResult model(@RequestBody(required = false) ElementRequest theRequest, - @PathVariable String theItemId) { - final ElementRequest request = (theRequest == null) ? ElementRequest.EMPTY_REQUEST : theRequest; - - Catalog catalog = catalogController.getCatalog(request.getCatalog()); - DeferredResult<CatalogResponse> result = new DeferredResult<>(request.getTimeout()); - - catalog - .item(theItemId).withModels().execute() - .setHandler(catalogController.new CatalogHandler<Item>(request, result) { - public CatalogResponse handleData(Item theItem) { - if (theItem == null) { - return new CatalogError(this.request, "No such item"); - } - Templates models = null; - try { - models = (Templates) theItem.elements("models", Templates.class); - if (models == null || models.isEmpty()) { - return new CatalogError(this.request, "Item has no models"); - } - if (models.size() > 1) { - return new CatalogError(this.request, "Item has more than one model !?"); - } - catalog.template(models.get(0).id()).withInputs().withOutputs().withNodes() - .withNodeProperties().withNodePropertiesAssignments().withNodeRequirements() - .withNodeCapabilities().withNodeCapabilityProperties() - .withNodeCapabilityPropertyAssignments().withPolicies().withPolicyProperties() - .withPolicyPropertiesAssignments().execute().setHandler( - catalogController.new CatalogHandler<Template>(this.request, this.result) { - public CatalogResponse handleData(Template theTemplate) { - CatalogResponse response = new CatalogResponse(this.request); - if (theTemplate != null) { - try { - response.data().put("model", catalogController - .patchData(catalog, theTemplate.data())); - } catch (JSONException e) { - errLogger.log(LogLevel.ERROR, this.getClass().getName(), "JSONException putting model to response {}", e); - } - } - return response; - } - }); - } catch (Exception e) { - handleException(e, ApiType.GET_MODEL, models.get(0).name()); - } - return null; - } - }); - - return result; - } - - @RequestMapping(value = "/{theItemId}/type/{theTypeName}", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json") - public DeferredResult<CatalogResponse> model(@RequestBody(required = false) ElementRequest theRequest, @PathVariable String theItemId, @PathVariable String theTypeName) { - final ElementRequest request = (theRequest == null) ? ElementRequest.EMPTY_REQUEST : theRequest; - - Catalog catalog = catalogController.getCatalog(request.getCatalog()); - DeferredResult<CatalogResponse> result = new DeferredResult<CatalogResponse>(request.getTimeout()); - - catalog.type(theItemId, theTypeName).withHierarchy().withCapabilities().withRequirements().execute() - .setHandler(catalogController.new CatalogHandler<Type>(request, result) { - public CatalogResponse handleData(Type theType) { - CatalogResponse response = new CatalogResponse(this.request); - if (theType != null) { - try { - response.data().put("type", catalogController.patchData(catalog, theType.data())); - } catch (JSONException e) { - errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Exception processing catalog {}", e); - } - } - return response; - } - }); - - return result; - } - - @RequestMapping(value = { "/getComposition/{vfcmtUuid}" }, method = { RequestMethod.GET }, produces = {"application/json" }) - public ResponseEntity getComposition(@PathVariable("vfcmtUuid") String vfcmtUuid, @ModelAttribute("requestId") String requestId) { - MessageResponse response = new MessageResponse(); - try { - ResourceDetailed vfcmt = baseBusinessLogic.getSdcRestClient().getResource(vfcmtUuid, requestId); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), vfcmt.toString()); - checkVfcmtType(vfcmt); - - Artifact compositionArtifact = CollectionUtils.isEmpty(vfcmt.getArtifacts()) ? null : vfcmt.getArtifacts().stream().filter(a -> DcaeBeConstants.Composition.fileNames.COMPOSITION_YML.equals(a.getArtifactName())).findAny().orElse(null); - - if(null == compositionArtifact){ - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Couldn't find {} in VFCMT artifacts", DcaeBeConstants.Composition.fileNames.COMPOSITION_YML); - response.setErrorResponse("No Artifacts"); - return new ResponseEntity<>(response, HttpStatus.NO_CONTENT); - } - - String artifact = baseBusinessLogic.getSdcRestClient().getResourceArtifact(vfcmtUuid, compositionArtifact.getArtifactUUID(), requestId); - - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "ARTIFACT: {}", artifact); - response.setSuccessResponse(artifact); - return new ResponseEntity<>(response, HttpStatus.OK); - } catch (Exception e) { - return handleException(e, ApiType.GET_CDUMP); - } - } - - @RequestMapping(value = "/saveComposition/{vfcmtUuid}", method = RequestMethod.POST) - public ResponseEntity saveComposition(@RequestHeader("USER_ID") String userId, @RequestBody String theCdump, @PathVariable("vfcmtUuid") String vfcmtUuid, @ModelAttribute("requestId") String requestId) { - - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "ARTIFACT CDUMP: {}", theCdump); - - try { - - ResourceDetailed vfcmt = baseBusinessLogic.getSdcRestClient().getResource(vfcmtUuid, requestId); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "VFCMT: {}", vfcmt); - - checkVfcmtType(vfcmt); - checkUserIfResourceCheckedOut(userId, vfcmt); - boolean isNeed2Checkout = isNeedToCheckOut(vfcmt.getLifecycleState()); - Artifact compositionArtifact = CollectionUtils.isEmpty(vfcmt.getArtifacts()) ? null : vfcmt.getArtifacts().stream().filter(a -> DcaeBeConstants.Composition.fileNames.COMPOSITION_YML.equals(a.getArtifactName())).findAny().orElse(null); - String resourceUuid = vfcmtUuid; // by default the resource is the original vfcmtId unless a checkout will be done - if (isNeed2Checkout) { - vfcmt = baseBusinessLogic.getSdcRestClient().changeResourceLifecycleState(userId, resourceUuid, LifecycleOperationType.CHECKOUT.name(), null, requestId); - if (vfcmt != null) { - resourceUuid = vfcmt.getUuid(); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "New resource after checkout is: {}", resourceUuid); - } - } - boolean isUpdateMode = null != compositionArtifact; - if (isUpdateMode) { - compositionArtifact.setDescription("updating composition file"); - compositionArtifact.setPayloadData(Base64Utils.encodeToString(theCdump.getBytes())); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "VFCMT {} does consist {} ----> updateMode", resourceUuid, DcaeBeConstants.Composition.fileNames.COMPOSITION_YML); - baseBusinessLogic.getSdcRestClient().updateResourceArtifact(userId, resourceUuid, compositionArtifact, requestId); - - } else { - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "VFCMT {} does not consist {} ----> createMode", resourceUuid, DcaeBeConstants.Composition.fileNames.COMPOSITION_YML); - compositionArtifact = SdcRestClientUtils.generateDeploymentArtifact("creating composition file", DcaeBeConstants.Composition.fileNames.COMPOSITION_YML, ArtifactType.DCAE_TOSCA.name(), "composition", theCdump.getBytes()); - baseBusinessLogic.getSdcRestClient().createResourceArtifact(userId, resourceUuid, compositionArtifact, requestId); - } - Asset result = checkin(userId, resourceUuid, org.onap.sdc.dcae.enums.AssetType.RESOURCE, requestId); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "vfcmt check-in result: {}", result); - - return new ResponseEntity<>(result, HttpStatus.OK); - } catch (Exception e) { - return handleException(e, ApiType.SAVE_CDUMP); - } - } -} +public class CompositionController extends BaseController { + + @Autowired private CatalogController catalogController; + + @Autowired private CompositionBusinessLogic compositionBusinessLogic; + + @PostConstruct public void init() { + catalogController.setDefaultCatalog(URI.create(systemProperties.getProperties().getProperty(DcaeBeConstants.Config.ASDC_CATALOG_URL))); + } + + @RequestMapping(value = { "/utils/clone/{assetType}/{sourceId}/{targetId}" }, method = { RequestMethod.GET }, produces = { "application/json" }) public ResponseEntity clone(@RequestHeader("USER_ID") String userId, + @PathVariable("assetType") String theAssetType, @PathVariable("sourceId") String theSourceId, @PathVariable("targetId") String theTargetId, @ModelAttribute("requestId") String requestId) { + MessageResponse response = new MessageResponse(); + + try { + // fetch the source and assert it is a vfcmt containing clone worthy artifacts (composition + rules) + ResourceDetailed sourceVfcmt = baseBusinessLogic.getSdcRestClient().getResource(theSourceId, requestId); + checkVfcmtType(sourceVfcmt); + List<Artifact> artifactsToClone = CollectionUtils.isEmpty(sourceVfcmt.getArtifacts()) ? + null : + sourceVfcmt.getArtifacts().stream().filter(p -> DcaeBeConstants.Composition.fileNames.COMPOSITION_YML.equals(p.getArtifactName()) || p.getArtifactName().endsWith(DcaeBeConstants.Composition.fileNames.MAPPING_RULE_POSTFIX)) + .collect(Collectors.toList()); + if (CollectionUtils.isEmpty(artifactsToClone)) { + response.setSuccessResponse("Nothing to clone"); + return new ResponseEntity<>(response, HttpStatus.NO_CONTENT); + } + + // fetch the target + ResourceDetailed vfcmt = baseBusinessLogic.getSdcRestClient().getResource(theTargetId, requestId); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), vfcmt.toString()); + checkVfcmtType(vfcmt); + checkUserIfResourceCheckedOut(userId, vfcmt); + boolean isTargetNeed2Checkout = isNeedToCheckOut(vfcmt.getLifecycleState()); + if (isTargetNeed2Checkout) { + ResourceDetailed targetVfcmt = baseBusinessLogic.getSdcRestClient().changeResourceLifecycleState(userId, theTargetId, LifecycleOperationType.CHECKOUT.name(), "checking out VFCMT before clone", requestId); + if (null == targetVfcmt) { + return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.GENERAL_ERROR); + } + theTargetId = targetVfcmt.getUuid(); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "New targetVfcmt (for artifact clone) after checkoutVfcmt is: {}", theTargetId); + } + + Map<String, Artifact> currentArtifacts = CollectionUtils.isEmpty(vfcmt.getArtifacts()) ? new HashMap<>() : vfcmt.getArtifacts().stream().collect(Collectors.toMap(Artifact::getArtifactName, Function.identity())); + + //TODO target VFCMT rule artifacts should be removed + for (Artifact artifactToClone : artifactsToClone) { + String payload = baseBusinessLogic.getSdcRestClient().getResourceArtifact(theSourceId, artifactToClone.getArtifactUUID(), requestId); + baseBusinessLogic.cloneArtifactToTarget(userId, theTargetId, payload, artifactToClone, currentArtifacts.get(artifactToClone.getArtifactName()), requestId); + } + + baseBusinessLogic.getSdcRestClient().changeResourceLifecycleState(userId, theTargetId, LifecycleOperationType.CHECKIN.name(), "check in VFCMT after clone", requestId); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Cloning {} from {} has finished successfully", theSourceId, theTargetId); + response.setSuccessResponse("Clone VFCMT complete"); + return new ResponseEntity<>(response, HttpStatus.OK); + } catch (Exception e) { + return handleException(e, ApiType.CLONE_VFCMT); + } + } + + @RequestMapping(value = "/elements", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json") public DeferredResult<CatalogResponse> items(@RequestBody(required = false) ItemsRequest theRequest) { + + final ItemsRequest request = (theRequest == null) ? ItemsRequest.EMPTY_REQUEST : theRequest; + + Catalog catalog = catalogController.getCatalog(request.getCatalog()); + DeferredResult<CatalogResponse> result = new DeferredResult<CatalogResponse>(request.getTimeout()); + + catalog.rootsByLabel(request.getStartingLabel()).setHandler(catalogController.new CatalogHandler<Folders>(request, result) { + public CatalogResponse handleData(Folders theFolders) { + JSONArray ja = new JSONArray(); + if (theFolders != null) { + for (Folder folder : theFolders) { + ja.put(catalogController.patchData(catalog, folder.data())); + } + } + CatalogResponse response = new CatalogResponse(this.request); + try { + response.data().put("elements", ja); + } catch (JSONException e) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), "JSONException putting json elements to response {}", e); + } + return response; + } + }); + return result; + } + + @RequestMapping(value = "/{theItemId}/elements", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json") public DeferredResult<CatalogResponse> items(@RequestBody(required = false) ItemsRequest theRequest, + @PathVariable String theItemId) { + + final ItemsRequest request = (theRequest == null) ? ItemsRequest.EMPTY_REQUEST : theRequest; + + Catalog catalog = catalogController.getCatalog(request.getCatalog()); + DeferredResult<CatalogResponse> result = new DeferredResult<CatalogResponse>(request.getTimeout()); + + catalog + // .fetchFolderByItemId(theItemId) + .folder(theItemId).withParts().withPartAnnotations().withItems().withItemAnnotations().withItemModels().execute().setHandler(catalogController.new CatalogHandler<Folder>(request, result) { + public CatalogResponse handleData(Folder theFolder) { + CatalogResponse response = new CatalogResponse(this.request); + if (theFolder == null) { + return response; + } + + try { + Elements folders = theFolder.elements("parts", Folders.class); + if (folders != null) { + for (Object folder : folders) { + catalogController.patchData(catalog, ((Element) folder).data()); + // lots of ephemere proxies created here .. + Elements annotations = ((Element) folder).elements("annotations", Annotations.class); + if (annotations != null) { + for (Object a : annotations) { + catalogController.patchData(catalog, ((Annotation) a).data()); + } + } + } + } + Elements items = theFolder.elements("items", Items.class); + if (items != null) { + for (Object i : items) { + catalogController.patchData(catalog, ((Element) i).data()); + // lots of ephemere proxies created here .. + Elements annotations = ((Element) i).elements("annotations", Annotations.class); + if (annotations != null) { + for (Object a : annotations) { + catalogController.patchData(catalog, ((Annotation) a).data()); + } + } + } + } + } catch (Exception x) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Exception processing catalog {}", x); + return new CatalogError(this.request, "", x); + } + + try { + response.data().put("element", theFolder.data()); + } catch (JSONException e) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), "JSONException putting element to response {}", e); + } + return response; + } + }); + + return result; + } + + @RequestMapping(value = "/{theItemId}/model", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json") public DeferredResult model(@RequestBody(required = false) ElementRequest theRequest, + @PathVariable String theItemId) { + final ElementRequest request = (theRequest == null) ? ElementRequest.EMPTY_REQUEST : theRequest; + + Catalog catalog = catalogController.getCatalog(request.getCatalog()); + DeferredResult<CatalogResponse> result = new DeferredResult<>(request.getTimeout()); + + catalog.item(theItemId).withModels().execute().setHandler(catalogController.new CatalogHandler<Item>(request, result) { + public CatalogResponse handleData(Item theItem) { + if (theItem == null) { + return new CatalogError(this.request, "No such item"); + } + Templates models = null; + try { + models = (Templates) theItem.elements("models", Templates.class); + if (models == null || models.isEmpty()) { + return new CatalogError(this.request, "Item has no models"); + } + if (models.size() > 1) { + return new CatalogError(this.request, "Item has more than one model !?"); + } + catalog.template(models.get(0).id()).withInputs().withOutputs().withNodes().withNodeProperties().withNodePropertiesAssignments().withNodeRequirements().withNodeCapabilities().withNodeCapabilityProperties() + .withNodeCapabilityPropertyAssignments().withPolicies().withPolicyProperties().withPolicyPropertiesAssignments().execute().setHandler(catalogController.new CatalogHandler<Template>(this.request, this.result) { + public CatalogResponse handleData(Template theTemplate) { + CatalogResponse response = new CatalogResponse(this.request); + if (theTemplate != null) { + try { + response.data().put("model", catalogController.patchData(catalog, theTemplate.data())); + } catch (JSONException e) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), "JSONException putting model to response {}", e); + } + } + return response; + } + }); + } catch (Exception e) { + handleException(e, ApiType.GET_MODEL, models.get(0).name()); + } + return null; + } + }); + + return result; + } + + @RequestMapping(value = "/{theItemId}/type/{theTypeName}", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json") public DeferredResult<CatalogResponse> model(@RequestBody(required = false) ElementRequest theRequest, + @PathVariable String theItemId, @PathVariable String theTypeName) { + final ElementRequest request = (theRequest == null) ? ElementRequest.EMPTY_REQUEST : theRequest; + + Catalog catalog = catalogController.getCatalog(request.getCatalog()); + DeferredResult<CatalogResponse> result = new DeferredResult<CatalogResponse>(request.getTimeout()); + + catalog.type(theItemId, theTypeName).withHierarchy().withCapabilities().withRequirements().execute().setHandler(catalogController.new CatalogHandler<Type>(request, result) { + public CatalogResponse handleData(Type theType) { + CatalogResponse response = new CatalogResponse(this.request); + if (theType != null) { + try { + response.data().put("type", catalogController.patchData(catalog, theType.data())); + } catch (JSONException e) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Exception processing catalog {}", e); + } + } + return response; + } + }); + + return result; + } + + @RequestMapping(value = { "/getComposition/{vfcmtUuid}" }, method = { RequestMethod.GET }, produces = { "application/json" }) public ResponseEntity getComposition(@PathVariable("vfcmtUuid") String vfcmtUuid, + @ModelAttribute("requestId") String requestId) { + MessageResponse response = new MessageResponse(); + try { + ResourceDetailed vfcmt = baseBusinessLogic.getSdcRestClient().getResource(vfcmtUuid, requestId); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), vfcmt.toString()); + checkVfcmtType(vfcmt); + + Artifact compositionArtifact = CollectionUtils.isEmpty(vfcmt.getArtifacts()) ? null : vfcmt.getArtifacts().stream().filter(a -> DcaeBeConstants.Composition.fileNames.COMPOSITION_YML.equals(a.getArtifactName())).findAny().orElse(null); + + if (null == compositionArtifact) { + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Couldn't find {} in VFCMT artifacts", DcaeBeConstants.Composition.fileNames.COMPOSITION_YML); + response.setErrorResponse("No Artifacts"); + return new ResponseEntity<>(response, HttpStatus.NO_CONTENT); + } + + String artifact = baseBusinessLogic.getSdcRestClient().getResourceArtifact(vfcmtUuid, compositionArtifact.getArtifactUUID(), requestId); + + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "ARTIFACT: {}", artifact); + response.setSuccessResponse(artifact); + return new ResponseEntity<>(response, HttpStatus.OK); + } catch (Exception e) { + return handleException(e, ApiType.GET_CDUMP); + } + } + + + @RequestMapping(value = { "/getMC/{vfcmtUuid}" }, method = { RequestMethod.GET }, produces = {"application/json" }) + public ResponseEntity getMC(@PathVariable String vfcmtUuid, @ModelAttribute String requestId) { + try { + return new ResponseEntity<>(compositionBusinessLogic.getDataAndComposition(vfcmtUuid, requestId), HttpStatus.OK); + } catch (Exception e) { + return handleException(e, ApiType.GET_VFCMT); + } + } + + @RequestMapping(value = "/saveComposition/{vfcmtUuid}", method = RequestMethod.POST) + public ResponseEntity saveComposition(@RequestHeader("USER_ID") String userId, @RequestBody String theCdump, @PathVariable("vfcmtUuid") String vfcmtUuid, @ModelAttribute("requestId") String requestId) { + + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "ARTIFACT CDUMP: {}", theCdump); + return compositionBusinessLogic.saveComposition(userId, vfcmtUuid, theCdump, requestId, true); + } + + @RequestMapping(value = "/{contextType}/{serviceUuid}/{vfiName}/saveComposition/{vfcmtUuid}", method = RequestMethod.POST) + public ResponseEntity updateComposition(@RequestHeader("USER_ID") String userId, @RequestBody String theCdump, + @PathVariable String contextType, @PathVariable String serviceUuid, @PathVariable String vfiName, @PathVariable String vfcmtUuid, @ModelAttribute String requestId) { + + ResponseEntity res = compositionBusinessLogic.saveComposition(userId, vfcmtUuid, theCdump, requestId, false); + if (HttpStatus.OK == res.getStatusCode()) { + ResourceDetailed vfcmt = (ResourceDetailed) res.getBody(); + if (!vfcmtUuid.equals(vfcmt.getUuid())) { + try { + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "New vfcmt major version created with id {} , adding new reference.", vfcmt.getUuid()); + baseBusinessLogic.getSdcRestClient().addExternalMonitoringReference(userId, contextType, serviceUuid, vfiName, new ReferenceUUID(vfcmt.getUuid()), requestId); + } catch (Exception e) { + return handleException(e, ApiType.SAVE_CDUMP); + } + } + } + return res; + } +}
\ No newline at end of file diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/LifecycleController.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/LifecycleController.java index 3007335..4fa8c18 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/LifecycleController.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/LifecycleController.java @@ -1,6 +1,6 @@ package org.onap.sdc.dcae.composition.controller; -import org.onap.sdc.dcae.composition.restmodels.sdc.Asset; +import org.onap.sdc.common.onaplog.Enums.LogLevel; import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceDetailed; import org.onap.sdc.dcae.enums.AssetType; import org.onap.sdc.dcae.enums.LifecycleOperationType; @@ -17,24 +17,20 @@ import java.util.UUID; @CrossOrigin public class LifecycleController extends BaseController { - private static final String VFCMT = "vfcmt"; - @RequestMapping(value={"/checkin/{assetType}/{uuid}"}, method={RequestMethod.PUT}, produces={"application/json"}) public ResponseEntity putCheckin( @PathVariable("assetType") String assetType, @PathVariable("uuid") UUID uuid, - @RequestHeader("USER_ID") String user_id, + @RequestHeader("USER_ID") String userId, @ModelAttribute("requestId") String requestId) { try { - switch (assetType) { - case VFCMT: - Asset res_checkin = checkin(user_id, uuid.toString(), AssetType.RESOURCE, requestId); - return new ResponseEntity<>(res_checkin, HttpStatus.OK); - - default: - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); - } + if (AssetType.VFCMT == getValidAssetTypeOrNull(assetType)) { + ResourceDetailed resCheckin = checkinVfcmt(userId, uuid.toString(), requestId); + return new ResponseEntity<>(resCheckin, HttpStatus.OK); + } else { + return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + } } catch (Exception e) { return handleException(e, ErrConfMgr.ApiType.CHECK_IN_RESOURCE); } @@ -44,17 +40,15 @@ public class LifecycleController extends BaseController { public ResponseEntity putCheckout( @PathVariable("assetType") String assetType, @PathVariable("uuid") UUID uuid, - @RequestHeader("USER_ID") String user_id, + @RequestHeader("USER_ID") String userId, @ModelAttribute("requestId") String requestId) { try { - switch (assetType) { - case VFCMT: - Asset asset = checkout(user_id, uuid.toString(), AssetType.RESOURCE, requestId); - return new ResponseEntity<>(asset, HttpStatus.OK); - - default: - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); + if (AssetType.VFCMT == getValidAssetTypeOrNull(assetType)) { + ResourceDetailed asset = checkoutVfcmt(userId, uuid.toString(), requestId); + return new ResponseEntity<>(asset, HttpStatus.OK); + } else { + return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } catch (Exception e) { return handleException(e, ErrConfMgr.ApiType.CHECK_OUT_RESOURCE); @@ -65,20 +59,20 @@ public class LifecycleController extends BaseController { public ResponseEntity putCertify( @PathVariable("assetType") String assetType, @PathVariable("uuid") String uuid, - @RequestHeader("USER_ID") String user_id, + @RequestHeader("USER_ID") String userId, @ModelAttribute("requestId") String requestId) { try { - switch (assetType) { - case VFCMT: - ResourceDetailed vfcmt = baseBusinessLogic.getSdcRestClient().changeResourceLifecycleState(user_id, uuid, LifecycleOperationType.CERTIFY.name(), "certifying VFCMT", requestId); - return new ResponseEntity<>(vfcmt, HttpStatus.OK); + if (AssetType.VFCMT == getValidAssetTypeOrNull(assetType)) { + ResourceDetailed vfcmt = baseBusinessLogic.getSdcRestClient().changeResourceLifecycleState(userId, uuid, LifecycleOperationType.CERTIFY.name(), "certifying VFCMT", requestId); + return new ResponseEntity<>(vfcmt, HttpStatus.OK); - default: + } else { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } catch (Exception e) { return handleException(e, ErrConfMgr.ApiType.CHECK_OUT_RESOURCE); } } + } diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/RuleEditorController.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/RuleEditorController.java index 3f5ff1a..8de8520 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/RuleEditorController.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/RuleEditorController.java @@ -1,89 +1,37 @@ package org.onap.sdc.dcae.composition.controller; -import com.google.gson.JsonParseException; -import org.apache.commons.collections.ListUtils; -import org.apache.commons.collections.MapUtils; -import org.apache.commons.lang3.StringUtils; import org.onap.sdc.common.onaplog.Enums.LogLevel; -import org.onap.sdc.dcae.composition.restmodels.sdc.Artifact; -import org.onap.sdc.dcae.composition.restmodels.sdc.Asset; -import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceDetailed; -import org.onap.sdc.dcae.composition.CompositionConfig; -import org.onap.sdc.dcae.utils.Normalizers; -import org.onap.sdc.dcae.composition.restmodels.ruleeditor.*; -import org.onap.sdc.dcae.composition.util.DcaeBeConstants; -import org.onap.sdc.dcae.enums.ArtifactType; -import org.onap.sdc.dcae.enums.AssetType; -import org.onap.sdc.dcae.errormng.ActionStatus; -import org.onap.sdc.dcae.errormng.ErrConfMgr; -import org.onap.sdc.dcae.errormng.ErrConfMgr.ApiType; -import org.onap.sdc.dcae.errormng.ServiceException; -import org.onap.sdc.dcae.rule.editor.impl.RulesBusinessLogic; -import org.onap.sdc.dcae.rule.editor.utils.RulesPayloadUtils; -import org.onap.sdc.dcae.utils.SdcRestClientUtils; -import org.onap.sdc.dcae.ves.VesDataItemsDefinition; -import org.onap.sdc.dcae.ves.VesDataTypeDefinition; -import org.onap.sdc.dcae.ves.VesSimpleTypesEnum; -import org.onap.sdc.dcae.ves.VesStructureLoader; +import org.onap.sdc.dcae.composition.impl.RuleEditorBusinessLogic; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.util.Base64Utils; -import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.*; -import java.util.*; -import java.util.Map.Entry; -import java.util.stream.Collectors; -import java.util.stream.Stream; -@RestController -@EnableAutoConfiguration -@CrossOrigin -@RequestMapping("/rule-editor") +@RestController +@EnableAutoConfiguration +@CrossOrigin +@RequestMapping("/rule-editor") public class RuleEditorController extends BaseController { private static final String EXCEPTION = "Exception {}"; - @Autowired - private CompositionConfig compositionConfig; @Autowired - private RulesBusinessLogic rulesBusinessLogic; + private RuleEditorBusinessLogic ruleEditorBusinessLogic; @RequestMapping(value = "/list-events-by-versions", method = RequestMethod.GET) public ResponseEntity getEventsByVersion() { - try { - - Map<String, Set<String>> eventsByVersions = VesStructureLoader.getAvailableVersionsAndEventTypes(); - - List<EventTypesByVersionUI> resBody = eventsByVersions.entrySet().stream().map(entry -> { - Set<String> events = entry.getValue().stream().filter(event -> !EventTypesByVersionUI.DEFAULT_EVENTS.contains(event)).collect(Collectors.toSet()); - return new EventTypesByVersionUI(entry.getKey(), events); - }).collect(Collectors.toList()); - - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Got a request to return all ves event types by versions {}", eventsByVersions); - return new ResponseEntity<>(resBody, HttpStatus.OK); - } catch (Exception e) { - errLogger.log(LogLevel.ERROR, this.getClass().getName(), EXCEPTION, e); - return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.VES_SCHEMA_NOT_FOUND); - } + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Starting getEventsByVersion"); + return ruleEditorBusinessLogic.getEventsByVersion(); } - @RequestMapping(value = { "/definition/{version:.*}/{eventType}" }, method = { RequestMethod.GET }, produces = { "application/json" }) + @RequestMapping(value = {"/definition/{version:.*}/{eventType}"}, method = {RequestMethod.GET}, produces = {"application/json"}) public ResponseEntity getDefinition(@PathVariable("version") String version, - @PathVariable("eventType") String eventType) { + @PathVariable("eventType") String eventType) { - try { - List<EventTypeDefinitionUI> result = getEventTypeDefinitionUIs(version, eventType); - - return new ResponseEntity<>(result, HttpStatus.OK); - - } catch (Exception e) { - errLogger.log(LogLevel.ERROR, this.getClass().getName(), EXCEPTION, e); - return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.VES_SCHEMA_NOT_FOUND); - } + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Starting getDefinition", version); + return ruleEditorBusinessLogic.getDefinition(version, eventType); } /** @@ -100,59 +48,16 @@ public class RuleEditorController extends BaseController { * 2. That the cdump holds a dcae component with such nid (to avoid orphan rules) * 3. Check that the fetched VFCMT is actually a VFCMT and not a regular VF */ - @RequestMapping(value = "/rule/{vfcmtUuid}/{dcaeCompLabel}/{nid}/{configParam}", method = { RequestMethod.POST }, produces = "application/json") + @RequestMapping(value = "/rule/{vfcmtUuid}/{dcaeCompLabel}/{nid}/{configParam:.*}", method = {RequestMethod.POST}, produces = "application/json") public ResponseEntity saveRule(@RequestBody String json, @ModelAttribute("requestId") String requestId, - @RequestHeader("USER_ID") String userId, - @PathVariable("vfcmtUuid") String vfcmtUuid, - @PathVariable("dcaeCompLabel") String dcaeCompLabel, - @PathVariable("nid") String nid, - @PathVariable("configParam") String configParam) { - try { - Rule rule = RulesPayloadUtils.parsePayloadToRule(json); - if (null == rule) { - return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.INVALID_RULE_FORMAT); - } - - List<ServiceException> errors = rulesBusinessLogic.validateRule(rule); - if(!errors.isEmpty()){ - return ErrConfMgr.INSTANCE.buildErrorArrayResponse(errors); - } - - ResourceDetailed vfcmt = baseBusinessLogic.getSdcRestClient().getResource(vfcmtUuid, requestId); - checkVfcmtType(vfcmt); - - if (CollectionUtils.isEmpty(vfcmt.getArtifacts())) { - return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.SAVE_RULE_FAILED); - } - - String artifactLabel = Normalizers.normalizeArtifactLabel(dcaeCompLabel + nid + configParam); - - // check for MappingRules artifact in existing artifacts - Artifact artifactFound = vfcmt.getArtifacts().stream() - .filter(a -> artifactLabel.equals(Normalizers.normalizeArtifactLabel(a.getArtifactLabel()))) - .findAny().orElse(null); - - // exception thrown if vfcmt is checked out and current user is not its owner - // performs vfcmt checkout if required - String vfcmtId = assertOwnershipOfVfcmtId(userId, vfcmt, requestId); - // new mappingRules artifact, validate nid exists in composition before creating new artifact - if (null == artifactFound) { - if(cdumpContainsNid(vfcmt, nid, requestId)) { - return saveNewRulesArtifact(rule, vfcmtId, generateMappingRulesFileName(dcaeCompLabel, nid, configParam), artifactLabel , userId, requestId); - } - return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.NODE_NOT_FOUND, "", dcaeCompLabel); - } - - //update artifact flow - append new rule or edit existing rule - return addOrEditRuleInArtifact(rule, vfcmtId, userId, artifactFound, requestId); - - } catch (JsonParseException je) { - errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Error: Rule format is invalid: {}", je); - return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.INVALID_RULE_FORMAT, "", je.getMessage()); - } catch (Exception e) { - return handleException(e, ErrConfMgr.ApiType.SAVE_RULE_ARTIFACT); - } + @RequestHeader("USER_ID") String userId, + @PathVariable("vfcmtUuid") String vfcmtUuid, + @PathVariable("dcaeCompLabel") String dcaeCompLabel, + @PathVariable("nid") String nid, + @PathVariable("configParam") String configParam) { + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Starting saveRule", json); + return ruleEditorBusinessLogic.saveRule(json, requestId, userId, vfcmtUuid, dcaeCompLabel, nid, configParam); } @@ -165,7 +70,7 @@ public class RuleEditorController extends BaseController { * @param configParam - the name of the DCAE Component configuration property the rule is linked to * @return json representing the rule editor UI */ - @RequestMapping(value = "/rule/{vfcmtUuid}/{dcaeCompLabel}/{nid}/{configParam}", method = { RequestMethod.GET }, produces = "application/json") + @RequestMapping(value = "/rule/{vfcmtUuid}/{dcaeCompLabel}/{nid}/{configParam}", method = {RequestMethod.GET}, produces = "application/json") public ResponseEntity getRules( @PathVariable("vfcmtUuid") String vfcmtUuid, @PathVariable("dcaeCompLabel") String dcaeCompLabel, @@ -173,28 +78,8 @@ public class RuleEditorController extends BaseController { @PathVariable("configParam") String configParam, @ModelAttribute("requestId") String requestId) { - try { - ResourceDetailed vfcmt = baseBusinessLogic.getSdcRestClient().getResource(vfcmtUuid, requestId); - if (CollectionUtils.isEmpty(vfcmt.getArtifacts())) { - return new ResponseEntity<>("{}", HttpStatus.OK); - } - String artifactLabel = Normalizers.normalizeArtifactLabel(dcaeCompLabel + nid + configParam); - - // check for MappingRules artifact in existing artifacts - Artifact artifactListed = vfcmt.getArtifacts().stream().filter(a -> artifactLabel.equals(Normalizers.normalizeArtifactLabel(a.getArtifactLabel()))).findAny().orElse(null); - if (null == artifactListed) { - return new ResponseEntity<>("{}", HttpStatus.OK); - } - String ruleFile = baseBusinessLogic.getSdcRestClient().getResourceArtifact(vfcmtUuid, artifactListed.getArtifactUUID(), requestId); - - // To avoid opening the file for reading we search for the eventType and SchemaVer from the artifact metadata's description - SchemaInfo schemainfo = RulesPayloadUtils.extractInfoFromDescription(artifactListed); - List<EventTypeDefinitionUI> schema = null == schemainfo? new ArrayList<>() : getEventTypeDefinitionUIs(schemainfo.getVersion(), schemainfo.getEventType()); - return new ResponseEntity<>(RulesPayloadUtils.buildSchemaAndRulesResponse(ruleFile, schema), HttpStatus.OK); - } catch (Exception e) { - return handleException(e, ApiType.GET_RULE_ARTIFACT); - } - + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Starting getRules", vfcmtUuid); + return ruleEditorBusinessLogic.getRules(vfcmtUuid, dcaeCompLabel, nid, configParam, requestId); } /** @@ -204,10 +89,10 @@ public class RuleEditorController extends BaseController { * @param dcaeCompLabel - the name of the DCAE Component which the rule is applied to * @param nid - A unique id of the DCAE Component which the rule is applied to - exists also in the cdump * @param configParam - the name of the DCAE Component configuration property the rule is linked to - * @param ruleUid - the unique id of the rule to delete + * @param ruleUid - the unique id of the rule to delete * @return operation result */ - @RequestMapping(value = "/rule/{vfcmtUuid}/{dcaeCompLabel}/{nid}/{configParam}/{ruleUid}", method = { RequestMethod.DELETE }, produces = "application/json") + @RequestMapping(value = "/rule/{vfcmtUuid}/{dcaeCompLabel}/{nid}/{configParam}/{ruleUid}", method = {RequestMethod.DELETE}, produces = "application/json") public ResponseEntity deleteRule( @RequestHeader("USER_ID") String userId, @PathVariable("vfcmtUuid") String vfcmtUuid, @@ -215,44 +100,10 @@ public class RuleEditorController extends BaseController { @PathVariable("nid") String nid, @PathVariable("configParam") String configParam, @PathVariable("ruleUid") String ruleUid, - @ModelAttribute("requestId") String requestId){ - - try { - ResourceDetailed vfcmt = baseBusinessLogic.getSdcRestClient().getResource(vfcmtUuid, requestId); - if (null == vfcmt.getArtifacts()) { - errLogger.log(LogLevel.ERROR, this.getClass().getName(), "VFCMT {} doesn't have artifacts", vfcmtUuid); - return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.DELETE_RULE_FAILED); - } - String artifactLabel = Normalizers.normalizeArtifactLabel(dcaeCompLabel + nid + configParam); - - // check for MappingRules artifact in existing artifacts - Artifact mappingRuleFile = vfcmt.getArtifacts().stream() - .filter(a -> artifactLabel.equals(Normalizers.normalizeArtifactLabel(a.getArtifactLabel()))) - .findAny().orElse(null); - - if (null == mappingRuleFile) { - errLogger.log(LogLevel.ERROR, this.getClass().getName(), "{} doesn't exist for VFCMT {}", artifactLabel, vfcmtUuid); - return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.DELETE_RULE_FAILED); - } - - String vfcmtId = assertOwnershipOfVfcmtId(userId, vfcmt, requestId); - String payload = baseBusinessLogic.getSdcRestClient().getResourceArtifact(vfcmtId, mappingRuleFile.getArtifactUUID(), requestId); - MappingRules rules = RulesPayloadUtils.parseMappingRulesArtifactPayload(payload); - Rule removedRule = rulesBusinessLogic.deleteRule(rules, ruleUid); - if(null == removedRule){ - errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Rule {} not found.", ruleUid); - return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.DELETE_RULE_FAILED); - } - if(rules.isEmpty()){ // if file doesn't contain any rules after last deletion -> let's delete the file - baseBusinessLogic.getSdcRestClient().deleteResourceArtifact(userId, vfcmtId, mappingRuleFile.getArtifactUUID(), requestId); - } else { - updateRulesArtifact(vfcmtId, userId, mappingRuleFile, rules, requestId); - } - return checkInAndReturnSaveArtifactResult(removedRule, vfcmtId, userId, requestId); - } catch (Exception e) { - return handleException(e, ApiType.SAVE_RULE_ARTIFACT); - } + @ModelAttribute("requestId") String requestId) { + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Starting deleteRule", vfcmtUuid); + return ruleEditorBusinessLogic.deleteRule(userId, vfcmtUuid, dcaeCompLabel, nid, configParam, ruleUid, requestId); } /** @@ -262,7 +113,7 @@ public class RuleEditorController extends BaseController { * @param dcaeCompLabel - the name of the DCAE Component which the rule is applied to * @param nid - A unique id of the DCAE Component which the rule is applied to - exists also in the cdump * @param configParam - the name of the DCAE Component configuration property the rule is linked to - * @param flowType - the mapping rules flow type (SNMP,Syslog,FOI) + * @param flowType - the mapping rules flow type (SNMP,Syslog,FOI) * @return translateJson representing the translated Rules * Validations: * 1. That the user is able to edit the VFCMT @@ -270,184 +121,25 @@ public class RuleEditorController extends BaseController { * 3. Check that the fetched VFCMT is actually a VFCMT and not a regular VF * @throws Exception */ - @RequestMapping(value = "/rule/translate/{vfcmtUuid}/{dcaeCompLabel}/{nid}/{configParam}", method = { RequestMethod.GET }, produces = "application/json") + @RequestMapping(value = "/rule/translate/{vfcmtUuid}/{dcaeCompLabel}/{nid}/{configParam}", method = {RequestMethod.GET}, produces = "application/json") public ResponseEntity translateRules(@PathVariable("vfcmtUuid") String vfcmtUuid, @ModelAttribute("requestId") String requestId, - @PathVariable("dcaeCompLabel") String dcaeCompLabel, - @PathVariable("nid") String nid, - @PathVariable("configParam") String configParam, - @RequestParam("flowType") String flowType) throws Exception { - - try { + @PathVariable("dcaeCompLabel") String dcaeCompLabel, + @PathVariable("nid") String nid, + @PathVariable("configParam") String configParam, + @RequestParam("flowType") String flowType) { - if (StringUtils.isBlank(flowType) || MapUtils.isEmpty(compositionConfig.getFlowTypesMap()) || null == compositionConfig.getFlowTypesMap().get(flowType)) { - return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.TRANSLATE_FAILED, "", "Flow type " + flowType + " not found"); - } - - // extract entry phase name and last phase name from configuration: - String entryPointPhaseName = compositionConfig.getFlowTypesMap().get(flowType).getEntryPointPhaseName(); - String lastPhaseName = compositionConfig.getFlowTypesMap().get(flowType).getLastPhaseName(); - - ResourceDetailed vfcmt = baseBusinessLogic.getSdcRestClient().getResource(vfcmtUuid, requestId); - checkVfcmtType(vfcmt); - - if (CollectionUtils.isEmpty(vfcmt.getArtifacts())) { - return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.TRANSLATE_FAILED, "", "No rules found on VFCMT " + vfcmtUuid); - } - String artifactLabel = Normalizers.normalizeArtifactLabel(dcaeCompLabel + nid + configParam); - - // check for MappingRules artifact in existing artifacts - Artifact rulesArtifact = vfcmt.getArtifacts().stream().filter(a -> artifactLabel.equals(Normalizers.normalizeArtifactLabel(a.getArtifactLabel()))).findAny().orElse(null); - - if (rulesArtifact == null) { - return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.TRANSLATE_FAILED, "", artifactLabel + " doesn't exist on VFCMT " + vfcmtUuid); - } - - String payload = baseBusinessLogic.getSdcRestClient().getResourceArtifact(vfcmtUuid, rulesArtifact.getArtifactUUID(), requestId); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Retrieved mapping rules artifact {}, start parsing rules...", artifactLabel); - MappingRules rules = RulesPayloadUtils.parseMappingRulesArtifactPayload(payload); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Finished parsing rules, calling validator..."); - List<ServiceException> errors = rulesBusinessLogic.validateRules(rules); - if (!errors.isEmpty()) { - return ErrConfMgr.INSTANCE.buildErrorArrayResponse(errors); - } - - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Validation completed successfully, calling translator..."); - String translateJson = rulesBusinessLogic.translateRules(rules, entryPointPhaseName, lastPhaseName, vfcmt.getName()); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Translation completed successfully"); - return new ResponseEntity<>(translateJson, HttpStatus.OK); - } catch (Exception e) { - return handleException(e, ApiType.SAVE_RULE_ARTIFACT); - } + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Starting translateRules", vfcmtUuid); + return ruleEditorBusinessLogic.translateRules(vfcmtUuid, requestId, dcaeCompLabel, nid, configParam, flowType); } - ///////////////////PRIVATE METHODS//////////////////////////////////////////////////////////////////////// - - private String assertOwnershipOfVfcmtId(String userId, ResourceDetailed vfcmt, String requestId) throws Exception { - checkUserIfResourceCheckedOut(userId, vfcmt); - String newVfcmtId = vfcmt.getUuid(); // may change after checking out a certified vfcmt - if (isNeedToCheckOut(vfcmt.getLifecycleState())) { - Asset result = checkout(userId, newVfcmtId, AssetType.RESOURCE, requestId); - if (result != null) { - newVfcmtId = result.getUuid(); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "New resource after checkout is: {}", newVfcmtId); - } - } - return newVfcmtId; - } - - - - // called after validating vfcmt.getArtifacts() is not null - private boolean cdumpContainsNid(ResourceDetailed vfcmt, String nid, String requestId) { - Artifact cdump = vfcmt.getArtifacts().stream() - .filter(a -> DcaeBeConstants.Composition.fileNames.COMPOSITION_YML.equalsIgnoreCase(a.getArtifactName())) - .findAny().orElse(null); - if (null == cdump || null == cdump.getArtifactUUID()) { - errLogger.log(LogLevel.ERROR, this.getClass().getName(), "No {} found on vfcmt {}", DcaeBeConstants.Composition.fileNames.COMPOSITION_YML, vfcmt.getUuid()); - return false; - } - try { - String artifact = baseBusinessLogic.getSdcRestClient().getResourceArtifact(vfcmt.getUuid(), cdump.getArtifactUUID(), requestId); - if (!artifact.contains("\"nid\":\""+nid)) { - errLogger.log(LogLevel.ERROR, this.getClass().getName(), "{} doesn't contain nid {}. Cannot save mapping rule file", DcaeBeConstants.Composition.fileNames.COMPOSITION_YML, nid); - return false; - } - } catch (Exception e) { - errLogger.log(LogLevel.ERROR, this.getClass().getName(), EXCEPTION, e); - return false; - } - return true; - } - - private ResponseEntity<String> saveNewRulesArtifact(Rule rule, String vfcmtUuid, String artifactFileName, String artifactLabel, String userId, String requestId) throws Exception { - MappingRules body = new MappingRules(rule); - Artifact artifact = SdcRestClientUtils.generateDeploymentArtifact(body.describe(), artifactFileName, ArtifactType.OTHER.name(), artifactLabel, body.convertToPayload()); - baseBusinessLogic.getSdcRestClient().createResourceArtifact(userId, vfcmtUuid, artifact, requestId); - return checkInAndReturnSaveArtifactResult(rule, vfcmtUuid, userId, requestId); - } - - private ResponseEntity addOrEditRuleInArtifact(Rule rule, String vfcmtUuid, String userId, Artifact rulesArtifact, String requestId) throws Exception { - String payload = baseBusinessLogic.getSdcRestClient().getResourceArtifact(vfcmtUuid, rulesArtifact.getArtifactUUID(), requestId); - MappingRules rules = RulesPayloadUtils.parseMappingRulesArtifactPayload(payload); - - // in case the rule id is passed but the rule doesn't exist on the mapping rule file: - if(!rulesBusinessLogic.addOrEditRule(rules, rule)) { - return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.SAVE_RULE_FAILED); - } - updateRulesArtifact(vfcmtUuid, userId, rulesArtifact, rules, requestId); - return checkInAndReturnSaveArtifactResult(rule, vfcmtUuid, userId, requestId); - } - - // regardless of check in result, return save artifact success - private ResponseEntity<String> checkInAndReturnSaveArtifactResult(Rule rule, String vfcmtUuid, String userId, String requestId) { - try { - checkin(userId, vfcmtUuid, AssetType.RESOURCE, requestId); - } catch (Exception e) { - // swallowing the exception intentionally since it is on the check in action - errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Error occurred while performing check in on VFCMT {}:{}", vfcmtUuid, e); - } - return new ResponseEntity<>(rule.toJson(), HttpStatus.OK); - } - - private void updateRulesArtifact(String vfcmtUuid, String userId, Artifact artifactInfo, MappingRules rules, String requestId) throws Exception { - artifactInfo.setPayloadData(Base64Utils.encodeToString(rules.convertToPayload())); - // POST must contain 'description' while GET returns 'artifactDescription' - artifactInfo.setDescription(artifactInfo.getArtifactDescription()); - baseBusinessLogic.getSdcRestClient().updateResourceArtifact(userId, vfcmtUuid, artifactInfo, requestId); - } - - - /** - * @param eventMapStream - * @param parent - * @param path - * @return - */ - private List<EventTypeDefinitionUI> convertToEventTypeDefinition(Stream<Entry<String, VesDataTypeDefinition>> eventMapStream, VesDataTypeDefinition parent, String path) { - - return eventMapStream.map(entry -> { - Map<String, VesDataTypeDefinition> properties = entry.getValue().getProperties(); - VesDataItemsDefinition items = entry.getValue().getItems(); - String newPath = path + "." + entry.getKey(); - List<EventTypeDefinitionUI> children = (properties == null) ? null : convertToEventTypeDefinition(properties.entrySet().stream(), entry.getValue(), newPath); - if(VesSimpleTypesEnum.ARRAY.getType().equals(entry.getValue().getType())) { - newPath += "[]"; - if(innerTypeIsComplex(items)) { - children = convertComplexArrayType(items, newPath); - } else if(innerTypeIsArray(items)) { - newPath += "[]"; - } - } - - boolean isRequired = (parent != null) ? parent.getRequired().contains(entry.getKey()) : false; - return new EventTypeDefinitionUI(entry.getKey(), children, isRequired, newPath); - }).collect(Collectors.toList()); - } - - private boolean innerTypeIsComplex(VesDataItemsDefinition items){ - return items != null && items.stream().anyMatch(p -> p.getProperties() != null); - } - - private boolean innerTypeIsArray(VesDataItemsDefinition items){ - return items != null && items.stream().anyMatch(p -> p.getItems() != null); - } - - private List<EventTypeDefinitionUI> convertComplexArrayType(VesDataItemsDefinition items, String path){ - return items.stream().map(item -> item.getProperties() != null ? convertToEventTypeDefinition(item.getProperties().entrySet().stream(), item, path) : new ArrayList<EventTypeDefinitionUI>()) - .flatMap(List::stream).collect(Collectors.toList()); - } - - - private String generateMappingRulesFileName(String dcaeCompLabel, String nid, String configParam) { - return dcaeCompLabel + "_" + nid + "_" + configParam + DcaeBeConstants.Composition.fileNames.MAPPING_RULE_POSTFIX; + @RequestMapping(value = "/getExistingRuleTargets/{vfcmtUuid}/{dcaeCompLabel}/{nid:.*}", method = {RequestMethod.GET}, produces = "application/json") + public ResponseEntity getExistingRuleTargets(@PathVariable("vfcmtUuid") String vfcmtUuid, @ModelAttribute("requestId") String requestId, + @PathVariable("dcaeCompLabel") String dcaeCompLabel, + @PathVariable("nid") String nid) { + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Starting getExistingRuleTargets ", vfcmtUuid); + return ruleEditorBusinessLogic.getExistingRuleTargets(vfcmtUuid, requestId, dcaeCompLabel, nid); } - private List<EventTypeDefinitionUI> getEventTypeDefinitionUIs(String version, String eventType) { - List<String> eventNamesToReturn = ListUtils.union(EventTypesByVersionUI.DEFAULT_EVENTS, Arrays.asList(eventType)); - Map<String, VesDataTypeDefinition> eventDefs = VesStructureLoader.getEventListenerDefinitionByVersion(version); - Stream<Entry<String, VesDataTypeDefinition>> filteredEvents = eventDefs.entrySet().stream().filter(entry -> eventNamesToReturn.contains(entry.getKey())); - return convertToEventTypeDefinition(filteredEvents, null, "event"); - } } diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/ServicesController.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/ServicesController.java index 257d1a9..b59f4a4 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/ServicesController.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/ServicesController.java @@ -1,37 +1,20 @@ package org.onap.sdc.dcae.composition.controller; import org.onap.sdc.common.onaplog.Enums.LogLevel; +import org.onap.sdc.dcae.composition.impl.ServiceBusinessLogic; import org.onap.sdc.dcae.composition.restmodels.AttachVFCMTServiceRequest; -import org.onap.sdc.dcae.composition.restmodels.DcaeMinimizedService; -import org.onap.sdc.dcae.composition.restmodels.MessageResponse; -import org.onap.sdc.dcae.composition.restmodels.sdc.*; -import org.onap.sdc.dcae.composition.util.DcaeBeConstants; -import org.onap.sdc.dcae.composition.util.DcaeBeConstants.LifecycleStateEnum; -import org.onap.sdc.dcae.enums.ArtifactType; -import org.onap.sdc.dcae.enums.LifecycleOperationType; -import org.onap.sdc.dcae.errormng.ActionStatus; -import org.onap.sdc.dcae.errormng.DcaeException; -import org.onap.sdc.dcae.errormng.ErrConfMgr; -import org.onap.sdc.dcae.errormng.ResponseFormat; -import org.onap.sdc.dcae.utils.SdcRestClientUtils; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.util.Base64Utils; -import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.*; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.stream.Collectors; - @RestController @EnableAutoConfiguration @CrossOrigin public class ServicesController extends BaseController { + @Autowired + private ServiceBusinessLogic serviceBusinessLogic; /*** * GET services list by VFCMT * @param userId @@ -40,19 +23,9 @@ public class ServicesController extends BaseController { */ @RequestMapping(value = { "/services/{vfcmtUuid}" }, method = { RequestMethod.GET }, produces = {"application/json" }) public ResponseEntity services(@RequestHeader("USER_ID") String userId, @PathVariable String vfcmtUuid, @ModelAttribute("requestId") String requestId) { - try { - ResourceDetailed vfcmt = baseBusinessLogic.getSdcRestClient().getResource(vfcmtUuid, requestId); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "GET ({}) Vfcmt form SDC: {}", vfcmtUuid, vfcmt); - checkVfcmtType(vfcmt); - checkUserIfResourceCheckedOut(userId, vfcmt); - List<Service> services = baseBusinessLogic.getSdcRestClient().getServices(requestId); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "GET services data from SDC: {}", services); - List<Service> uuids = filterServicesByUser(services, userId); - return new ResponseEntity<>(uuids, HttpStatus.OK); - } catch (Exception e) { - return handleException(e, ErrConfMgr.ApiType.GET_SERVICE); - } + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Starting services"); + return serviceBusinessLogic.services(userId,vfcmtUuid,requestId); } /*** @@ -62,22 +35,9 @@ public class ServicesController extends BaseController { */ @RequestMapping(value = { "/service/{theServiceId}" }, method = { RequestMethod.GET }, produces = {"application/json" }) public ResponseEntity service(@PathVariable String theServiceId, @ModelAttribute("requestId") String requestId) { - try { - ServiceDetailed service = baseBusinessLogic.getSdcRestClient().getService(theServiceId, requestId); - if (service != null) { - if(service.getResources()!=null){ - List<ResourceInstance> vfResourcesOnly = service.getResources().stream().filter(vfi -> vfi.getResoucreType().equals("VF")).collect(Collectors.toList()); - service.setResources(vfResourcesOnly); - }else{ - errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Service {} doesn't have any resources (e.g VFi's)", theServiceId); - } - } else { - errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Couldn't fetch service with uuid {} from SDC", theServiceId); - } - return new ResponseEntity<>(service, HttpStatus.OK); - } catch (Exception e) { - return handleException(e, ErrConfMgr.ApiType.GET_SERVICE); - } + + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Starting service"); + return serviceBusinessLogic.service(theServiceId,requestId); } @@ -87,6 +47,7 @@ public class ServicesController extends BaseController { * @param request * @return ResponseEntity */ + @Deprecated @RequestMapping(value = "/{vfcmtUuid}/attachment", method = RequestMethod.POST, produces = {"application/json" }) public ResponseEntity attachService( @PathVariable("vfcmtUuid") String vfcmtUuid, @@ -94,137 +55,15 @@ public class ServicesController extends BaseController { @RequestBody AttachVFCMTServiceRequest request, @ModelAttribute("requestId") String requestId) { - String serviceUuid = request.getServiceUuid(); - String vfiName = request.getInstanceName(); - String resourceUuid = vfcmtUuid; - MessageResponse response = new MessageResponse(); - - try { - ResourceDetailed vfcmt = baseBusinessLogic.getSdcRestClient().getResource(vfcmtUuid, requestId); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), vfcmt.toString()); - - checkVfcmtType(vfcmt); - verifyVfiExists(serviceUuid, vfiName, requestId); - - boolean isUpdateMode = false; - Artifact artifactObj = null; - - String reference = serviceUuid + "/resources/" + vfiName; - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "*****************************************"); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Reference between service and vfi {}", reference); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "*****************************************"); - - if(!CollectionUtils.isEmpty(vfcmt.getArtifacts())){ - artifactObj = vfcmt.getArtifacts().stream().filter(a -> DcaeBeConstants.Composition.fileNames.SVC_REF.equals(a.getArtifactName())).findAny().orElse(null); - isUpdateMode = null != artifactObj; - } - - if (isNeedToCheckOut(vfcmt.getLifecycleState())) { - vfcmt = baseBusinessLogic.getSdcRestClient().changeResourceLifecycleState(userId, vfcmtUuid, LifecycleOperationType.CHECKOUT.name(), null, requestId); - if (vfcmt != null) { - resourceUuid = vfcmt.getUuid(); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "New vfcmt uuid after checkout is: {}", resourceUuid); - } - } - - if(isUpdateMode){ - updateReferenceArtifact(userId, resourceUuid, artifactObj, reference, requestId); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Artifact {} updated with content: {}", reference, DcaeBeConstants.Composition.fileNames.SVC_REF, reference); - }else{ - Artifact artifact = SdcRestClientUtils.generateDeploymentArtifact("createReferenceArtifact", DcaeBeConstants.Composition.fileNames.SVC_REF, ArtifactType.DCAE_TOSCA.name(), "servicereference", reference.getBytes()); - baseBusinessLogic.getSdcRestClient().createResourceArtifact(userId, resourceUuid, artifact, requestId); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Artifact {} created with content: {}", DcaeBeConstants.Composition.fileNames.SVC_REF, reference); - } - checkin(userId, resourceUuid, org.onap.sdc.dcae.enums.AssetType.RESOURCE, requestId); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Attachment of reference={} in VFCMT {} has finished successfully", reference, resourceUuid); - - response.setSuccessResponse("Artifact updated"); - return new ResponseEntity<>(response, HttpStatus.OK); - } catch (Exception e) { - return handleException(e, ErrConfMgr.ApiType.ATTACH_TO_SERVICE); - } + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Starting attachService"); + return serviceBusinessLogic.attachService(vfcmtUuid,userId,request,requestId); } @RequestMapping(value = { "/{vfcmtUuid}/attachment" }, method = { RequestMethod.GET }, produces = {"application/json" }) public ResponseEntity getAttachedService(@PathVariable("vfcmtUuid") String vfcmtUuid, @ModelAttribute("requestId") String requestId) { - - MessageResponse response = new MessageResponse(); - - try { - ResourceDetailed vfcmt = baseBusinessLogic.getSdcRestClient().getResource(vfcmtUuid, requestId); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), vfcmt.toString()); - checkVfcmtType(vfcmt); - String artifact = "No Artifacts"; - - if (!CollectionUtils.isEmpty(vfcmt.getArtifacts())) { - Artifact artifactObj = vfcmt.getArtifacts().stream().filter(a -> DcaeBeConstants.Composition.fileNames.SVC_REF.equals(a.getArtifactName())).findAny().orElse(null); - if (null != artifactObj) - artifact = baseBusinessLogic.getSdcRestClient().getResourceArtifact(vfcmtUuid, artifactObj.getArtifactUUID(), requestId); - } - response.setSuccessResponse(artifact); - return new ResponseEntity<>(response, HttpStatus.OK); - } catch (Exception e) { - return handleException(e, ErrConfMgr.ApiType.GET_VFCMT); - } - } - - /**** PRIVATE METHODS ****/ - - private void updateReferenceArtifact(String userId, String VFCMTUuid, Artifact artifactObj, String reference, String requestId) throws Exception { - artifactObj.setDescription("updateReferenceArtifact"); - artifactObj.setPayloadData(Base64Utils.encodeToString(reference.getBytes())); - baseBusinessLogic.getSdcRestClient().updateResourceArtifact(userId, VFCMTUuid, artifactObj, requestId); - } - - - /** - * - * @param lastUpdaterUserId - * @param services - * @param userId - * @return - */ - - //TODO move method to ci tests - public List<DcaeMinimizedService> parseAndFilterServicesByUser(String lastUpdaterUserId, List<LinkedHashMap<String, String>> services, String userId) { - List<DcaeMinimizedService> uuids = null; - if (services != null) { - //services.stream().filter(predicate) - uuids = services.stream() - .map(x -> new DcaeMinimizedService(x.get("uuid"), x.get("name"), x.get("lastUpdaterUserId"), x.get("lifecycleState"), x.get("version"), x.get("invariantUUID"))) - .collect(Collectors.groupingBy(DcaeMinimizedService::getInvariantUUID)).values().stream() - .map(p -> p.stream() - .sorted(Comparator.comparing(DcaeMinimizedService::getVersionAsFloat).reversed())).map(p -> p.collect(Collectors.toList())).map(p -> p.get(0)) - .filter(x -> (!(!x.getLastUpdaterUserId().equals(userId) && x.getLifeCycleState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())))) - .sorted(Comparator.comparing(DcaeMinimizedService::getName)).collect(Collectors.toList()); - } - return uuids; - } - private List<Service> filterServicesByUser(List<Service> services, String userId) { - return CollectionUtils.isEmpty(services) ? new ArrayList<>() : services.stream() - .collect(Collectors.groupingBy(Service::getInvariantUUID)).values().stream() - .map(p -> p.stream() - .sorted(Comparator.comparing(Service::versionAsFloat).reversed())).map(p -> p.collect(Collectors.toList())).map(p -> p.get(0)) - .filter(x -> (!(!x.getLastUpdaterUserId().equals(userId) && x.getLifecycleState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())))) - .sorted(Comparator.comparing(Service::getName)).collect(Collectors.toList()); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Starting getAttachedService"); + return serviceBusinessLogic.getAttachedService(vfcmtUuid,requestId); } - /** - * - * @param serviceUuid - * @param vfiName - * @param requestId - * @throws Exception - */ - private void verifyVfiExists(String serviceUuid, String vfiName, String requestId) throws Exception { - ServiceDetailed service = baseBusinessLogic.getSdcRestClient().getService(serviceUuid, requestId); - boolean isServiceContainsVfi = null != service && !CollectionUtils.isEmpty(service.getResources()) && service.getResources().stream() - .filter(vfi -> "VF".equals(vfi.getResoucreType())) - .anyMatch(vfi -> vfiName.equals(vfi.getResourceInstanceName())); - if (!isServiceContainsVfi) { - ResponseFormat responseFormat = ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.VFI_FETCH_ERROR, null, serviceUuid, vfiName); - throw new DcaeException(HttpStatus.NOT_FOUND, responseFormat.getRequestError()); - } - } } diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/VfcmtController.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/VfcmtController.java index 0e1b209..7d64dad 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/VfcmtController.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/controller/VfcmtController.java @@ -8,6 +8,7 @@ import org.onap.sdc.dcae.composition.restmodels.ImportVFCMTRequest; import org.onap.sdc.dcae.composition.restmodels.sdc.ExternalReferencesMap; import org.onap.sdc.dcae.composition.restmodels.sdc.Resource; import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceDetailed; +import org.onap.sdc.dcae.enums.AssetType; import org.onap.sdc.dcae.errormng.ErrConfMgr.ApiType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -23,14 +24,14 @@ import java.util.List; public class VfcmtController extends BaseController{ - @Autowired - private VfcmtBusinessLogic vfcmtBusinessLogic; + @Autowired + private VfcmtBusinessLogic vfcmtBusinessLogic; @Autowired private ReferenceBusinessLogic referenceBusinessLogic; - private static final String VFCMT = "VFCMT"; - private static final String TEMPLATE = "Template"; + private static final String TEMPLATE = "Template"; private static final String BASE_MONITORING_TEMPLATE = "Base Monitoring Template"; + private static final String MONITORING_TEMPLATE = "Monitoring Template"; @@ -56,7 +57,7 @@ public class VfcmtController extends BaseController{ @RequestMapping(value = { "/getResourcesByCategory" }, method = { RequestMethod.GET }, produces = {"application/json" }) public ResponseEntity getResourcesByCategory(@ModelAttribute("requestId") String requestId) { try { - List<Resource> resources = baseBusinessLogic.getSdcRestClient().getResources(VFCMT, null, null, requestId); + List<Resource> resources = baseBusinessLogic.getSdcRestClient().getResources(AssetType.VFCMT.name(), TEMPLATE, MONITORING_TEMPLATE, requestId); return new ResponseEntity<>(resources, HttpStatus.OK); } catch (Exception e) { return handleException(e, ApiType.GET_ALL_VFCMTS); @@ -85,7 +86,7 @@ public class VfcmtController extends BaseController{ @RequestMapping(value = { "/getResourcesByMonitoringTemplateCategory" }, method = { RequestMethod.GET }, produces = {"application/json" }) public ResponseEntity getResourcesByMonitoringTemplateCategory(@ModelAttribute("requestId") String requestId) { try { - List<Resource> resources = baseBusinessLogic.getSdcRestClient().getResources(VFCMT, TEMPLATE, BASE_MONITORING_TEMPLATE, requestId); + List<Resource> resources = baseBusinessLogic.getSdcRestClient().getResources(AssetType.VFCMT.name(), TEMPLATE, BASE_MONITORING_TEMPLATE, requestId); return new ResponseEntity<>(resources, HttpStatus.OK); } catch (Exception e) { return handleException(e, ApiType.GET_ALL_VFCMTS); @@ -100,7 +101,7 @@ public class VfcmtController extends BaseController{ */ @RequestMapping(value = "/createVFCMT", method = RequestMethod.POST, produces = {"application/json" }) public ResponseEntity createVFCMT(@RequestHeader("USER_ID") String userId, @RequestBody CreateVFCMTRequest request, @ModelAttribute("requestId") String requestId) { - vfcmtBusinessLogic.addSdcMandatoryFields(request, userId); + vfcmtBusinessLogic.addSdcMandatoryFields(request, userId); try { ResourceDetailed response = baseBusinessLogic.getSdcRestClient().createResource(userId, request, requestId); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "createVFCMT after post: {}", response); @@ -122,28 +123,28 @@ public class VfcmtController extends BaseController{ } - /*** - * Clone or import existing VFCMT and attach to selected service/resource - * @param userId - * @param request - * @return ResponseEntity - */ - @RequestMapping(value = "/importMC", method = RequestMethod.POST, produces = {"application/json" }) - public ResponseEntity importMC(@RequestHeader("USER_ID") String userId, @RequestBody ImportVFCMTRequest request, @ModelAttribute("requestId") String requestId) { - return vfcmtBusinessLogic.importMC(userId, request, requestId); - } + /*** + * Clone or import existing VFCMT and attach to selected service/resource + * @param userId + * @param request + * @return ResponseEntity + */ + @RequestMapping(value = "/importMC", method = RequestMethod.POST, produces = {"application/json" }) + public ResponseEntity importMC(@RequestHeader("USER_ID") String userId, @RequestBody ImportVFCMTRequest request, @ModelAttribute("requestId") String requestId) { + return vfcmtBusinessLogic.importMC(userId, request, requestId); + } /*** * GET a list of Monitoring Components of a service by uuid and version - * @param context the context type of this request + * @param contextType the context type of this request * @param uuid the uuid of the type requested * @param version the version of the entity requested * @return ResponseEntity */ - @RequestMapping(value = { "/{context}/{uuid}/{version}/monitoringComponents" }, method = { RequestMethod.GET }, produces = {"application/json" }) - public ResponseEntity getMonitoringComponents(@PathVariable String context, @PathVariable String uuid, @PathVariable String version, @ModelAttribute("requestId") String requestId) { + @RequestMapping(value = { "/{contextType}/{uuid}/{version}/monitoringComponents" }, method = { RequestMethod.GET }, produces = {"application/json" }) + public ResponseEntity getMonitoringComponents(@PathVariable String contextType, @PathVariable String uuid, @PathVariable String version, @ModelAttribute("requestId") String requestId) { try { - ExternalReferencesMap mcRefs = baseBusinessLogic.getSdcRestClient().getMonitoringReferences(context, uuid, version, requestId); + ExternalReferencesMap mcRefs = baseBusinessLogic.getSdcRestClient().getMonitoringReferences(contextType, uuid, version, requestId); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Got monitoring references map from SDC: {}", mcRefs.values()); return new ResponseEntity<>(referenceBusinessLogic.fetchMonitoringComponents(mcRefs, requestId), HttpStatus.OK); } catch (Exception e) { @@ -151,33 +152,33 @@ public class VfcmtController extends BaseController{ } } - @RequestMapping(value = { "/{context}/{serviceUuid}/{vfiName}/{vfcmtUuid}/deleteVfcmtReference" }, method = { RequestMethod.DELETE }, produces = {"application/json" }) - public ResponseEntity deleteVfcmtReference(@RequestHeader("USER_ID") String userId, @PathVariable String context, @PathVariable String serviceUuid, @PathVariable String vfiName, @PathVariable String vfcmtUuid, @ModelAttribute String requestId) { + @RequestMapping(value = { "/{contextType}/{serviceUuid}/{vfiName}/{vfcmtUuid}/deleteVfcmtReference" }, method = { RequestMethod.DELETE }, produces = {"application/json" }) + public ResponseEntity deleteVfcmtReference(@RequestHeader("USER_ID") String userId, @PathVariable String contextType, @PathVariable String serviceUuid, @PathVariable String vfiName, @PathVariable String vfcmtUuid, @ModelAttribute String requestId) { try { - referenceBusinessLogic.deleteVfcmtReference(userId, context, serviceUuid, vfiName, vfcmtUuid, requestId); + referenceBusinessLogic.deleteVfcmtReference(userId, contextType, serviceUuid, vfiName, vfcmtUuid, requestId); return new ResponseEntity<>(HttpStatus.OK); } catch (Exception e) { return handleException(e, ApiType.DELETE_VFCMT_REFERENCE); } } - @RequestMapping(value = { "/{context}/{monitoringComponentName}/{serviceUuid}/{vfiName}/{vfcmtUuid}/deleteVfcmtReference" }, method = { RequestMethod.DELETE }, produces = {"application/json" }) - public ResponseEntity deleteVfcmtReferenceWithBlueprint(@RequestHeader("USER_ID") String userId, @PathVariable String context, @PathVariable String monitoringComponentName, @PathVariable String serviceUuid, @PathVariable String vfiName, @PathVariable String vfcmtUuid, @ModelAttribute String requestId) { + @RequestMapping(value = { "/{contextType}/{monitoringComponentName}/{serviceUuid}/{vfiName}/{vfcmtUuid}/deleteVfcmtReference" }, method = { RequestMethod.DELETE }, produces = {"application/json" }) + public ResponseEntity deleteVfcmtReferenceWithBlueprint(@RequestHeader("USER_ID") String userId, @PathVariable String contextType, @PathVariable String monitoringComponentName, @PathVariable String serviceUuid, @PathVariable String vfiName, @PathVariable String vfcmtUuid, @ModelAttribute String requestId) { try { - referenceBusinessLogic.deleteVfcmtReference(userId, context, serviceUuid, vfiName, vfcmtUuid, requestId); + referenceBusinessLogic.deleteVfcmtReference(userId, contextType, serviceUuid, vfiName, vfcmtUuid, requestId); } catch (Exception e) { return handleException(e, ApiType.DELETE_VFCMT_REFERENCE); } - return referenceBusinessLogic.deleteVfcmtReferenceBlueprint(userId, context, monitoringComponentName, serviceUuid, vfiName, vfcmtUuid, requestId); + return referenceBusinessLogic.deleteVfcmtReferenceBlueprint(userId, contextType, monitoringComponentName, serviceUuid, vfiName, vfcmtUuid, requestId); } - @RequestMapping(value = { "/getVfcmtReferenceData/{vfcmtUuid}" }, method = { RequestMethod.GET }, produces = {"application/json" }) - public ResponseEntity getVfcmtReferenceData(@PathVariable String vfcmtUuid, @ModelAttribute String requestId) { - try { - return vfcmtBusinessLogic.getVfcmtReferenceData(vfcmtUuid, requestId); - } catch (Exception e) { - return handleException(e, ApiType.GET_VFCMT); - } - } + @RequestMapping(value = { "/getVfcmtReferenceData/{vfcmtUuid}" }, method = { RequestMethod.GET }, produces = {"application/json" }) + public ResponseEntity getVfcmtReferenceData(@PathVariable String vfcmtUuid, @ModelAttribute String requestId) { + try { + return vfcmtBusinessLogic.getVfcmtReferenceData(vfcmtUuid, requestId); + } catch (Exception e) { + return handleException(e, ApiType.GET_VFCMT); + } + } } diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/BaseBusinessLogic.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/BaseBusinessLogic.java index f26c885..bfec7ed 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/BaseBusinessLogic.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/BaseBusinessLogic.java @@ -1,15 +1,31 @@ package org.onap.sdc.dcae.composition.impl; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang.StringUtils; +import org.onap.sdc.common.onaplog.Enums.LogLevel; import org.onap.sdc.common.onaplog.OnapLoggerDebug; import org.onap.sdc.common.onaplog.OnapLoggerError; import org.onap.sdc.dcae.client.ISdcClient; -import org.onap.sdc.dcae.composition.restmodels.sdc.Artifact; -import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceDetailed; +import org.onap.sdc.dcae.composition.restmodels.CreateMcResponse; +import org.onap.sdc.dcae.composition.restmodels.VfcmtData; +import org.onap.sdc.dcae.composition.restmodels.sdc.*; +import org.onap.sdc.dcae.composition.util.DcaeBeConstants; +import org.onap.sdc.dcae.enums.AssetType; +import org.onap.sdc.dcae.enums.LifecycleOperationType; +import org.onap.sdc.dcae.errormng.ActionStatus; +import org.onap.sdc.dcae.errormng.DcaeException; +import org.onap.sdc.dcae.errormng.ErrConfMgr; +import org.onap.sdc.dcae.errormng.ResponseFormat; +import org.onap.sdc.dcae.utils.Normalizers; import org.onap.sdc.dcae.utils.SdcRestClientUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.util.Base64Utils; -import org.springframework.util.CollectionUtils; + +import java.io.IOException; @Component public class BaseBusinessLogic { @@ -19,31 +35,130 @@ public class BaseBusinessLogic { protected static OnapLoggerError errLogger = OnapLoggerError.getInstance(); protected static OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance(); - public ISdcClient getSdcRestClient() { - return sdcRestClient; - } - - void setSdcRestClient(ISdcClient sdcRestClient) { - this.sdcRestClient = sdcRestClient; - } - - Artifact cloneArtifactToTarget(String userId, String targetId, String payload, Artifact artifactToClone, String requestId) throws Exception { - Artifact cloned = SdcRestClientUtils.generateDeploymentArtifact(artifactToClone.getArtifactDescription(), artifactToClone.getArtifactName(), artifactToClone.getArtifactType(), artifactToClone.getArtifactLabel(), payload.getBytes()); - return sdcRestClient.createResourceArtifact(userId, targetId, cloned, requestId); - } - - public void cloneArtifactToTarget(String userId, String targetId, String payload, Artifact artifactToClone, Artifact artifactToOverride, String requestId) throws Exception{ - if (null != artifactToOverride) { - artifactToOverride.setDescription(artifactToOverride.getArtifactDescription()); - artifactToOverride.setPayloadData(Base64Utils.encodeToString(payload.getBytes())); - sdcRestClient.updateResourceArtifact(userId, targetId, artifactToOverride, requestId); - } else { - cloneArtifactToTarget(userId, targetId, payload, artifactToClone, requestId); - } - } - - Artifact findArtifactDataByArtifactName(ResourceDetailed vfcmt, String artifactName) { - return null == vfcmt ? null : CollectionUtils.isEmpty(vfcmt.getArtifacts()) ? null : vfcmt.getArtifacts().stream() - .filter(p -> artifactName.equals(p.getArtifactName())).findAny().orElse(null); - } + public ISdcClient getSdcRestClient() { + return sdcRestClient; + } + + void setSdcRestClient(ISdcClient sdcRestClient) { + this.sdcRestClient = sdcRestClient; + } + + Artifact cloneArtifactToTarget(String userId, String targetId, String payload, Artifact artifactToClone, String requestId) throws JsonProcessingException { + Artifact cloned = SdcRestClientUtils.generateDeploymentArtifact(artifactToClone.getArtifactDescription(), artifactToClone.getArtifactName(), artifactToClone.getArtifactType(), artifactToClone.getArtifactLabel(), payload.getBytes()); + return sdcRestClient.createResourceArtifact(userId, targetId, cloned, requestId); + } + + public void cloneArtifactToTarget(String userId, String targetId, String payload, Artifact artifactToClone, Artifact artifactToOverride, String requestId) throws JsonProcessingException { + if (null != artifactToOverride) { + artifactToOverride.setDescription(artifactToOverride.getArtifactDescription()); + artifactToOverride.setPayloadData(Base64Utils.encodeToString(payload.getBytes())); + sdcRestClient.updateResourceArtifact(userId, targetId, artifactToOverride, requestId); + } else { + cloneArtifactToTarget(userId, targetId, payload, artifactToClone, requestId); + } + } + + Artifact findArtifactDataByArtifactName(ResourceDetailed vfcmt, String artifactName) { + if (null == vfcmt || null == vfcmt.getArtifacts()) { + return null; + } + return vfcmt.getArtifacts().stream() + .filter(p -> artifactName.equals(p.getArtifactName())).findAny().orElse(null); + } + + Artifact findCdumpArtifactData(ResourceDetailed vfcmt) { + return findArtifactDataByArtifactName(vfcmt, DcaeBeConstants.Composition.fileNames.COMPOSITION_YML); + } + + void rollBack(String userId, ResourceDetailed newVfcmt, String requestId) { + if (null != newVfcmt) { + try { + sdcRestClient.changeResourceLifecycleState(userId, newVfcmt.getUuid(), LifecycleOperationType.UNDO_CHECKOUT.getValue(), "DCAE rollback", requestId); + } catch (Exception e) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(),"Failed rolling back Monitoring Component. ID:{}", newVfcmt.getUuid()); + debugLogger.log(LogLevel.ERROR, this.getClass().getName(),"Failed rolling back Monitoring Component:{}", e); + } + } + } + + CreateMcResponse buildVfcmtAndCdumpResponse(VfcmtData vfcmt, String cdumpPayload) throws IOException { + return new CreateMcResponse(vfcmt, new ObjectMapper().readValue(cdumpPayload, Object.class)); + } + + public Artifact fetchCdump(ResourceDetailed vfcmt, String requestId) { + Artifact cdumpArtifactData = findCdumpArtifactData(vfcmt); + if (null != cdumpArtifactData) { + String cdumpPayload = sdcRestClient.getResourceArtifact(vfcmt.getUuid(), cdumpArtifactData.getArtifactUUID(), requestId); + cdumpArtifactData.setPayloadData(cdumpPayload); + } + return cdumpArtifactData; + } + + String generateBlueprintFileName(String monitoringFlowType, String vfcmtName) { + return monitoringFlowType + .concat(".") + .concat(Normalizers.normalizeComponentName(vfcmtName)) + .concat(".") + .concat(DcaeBeConstants.Composition.fileNames.EVENT_PROC_BP_YAML); + } + + ResourceInstance findVfiOnService(ServiceDetailed service, String vfiName) { + if (null == service || null == service.getResources()) { + return null; + } + return service.getResources().stream() + .filter(p -> Normalizers.normalizeComponentInstanceName(vfiName).equals(Normalizers.normalizeComponentInstanceName(p.getResourceInstanceName()))).findAny().orElse(null); + } + + public String extractFlowTypeFromCdump(String cdump) { + return StringUtils.substringBetween(cdump,"\"flowType\":\"","\""); + } + + // TODO - reuse + + ResourceDetailed checkinVfcmt(String userId, String uuid, String requestId) { + return getSdcRestClient().changeResourceLifecycleState(userId, uuid, LifecycleOperationType.CHECKIN.name(), "checking in vfcmt" + uuid, requestId); + } + ResourceDetailed checkoutVfcmt(String userId, String uuid, String requestId) { + return getSdcRestClient().changeResourceLifecycleState(userId, uuid, LifecycleOperationType.CHECKOUT.name(), null, requestId); + } + + // TODO - remove from BaseController + + void checkUserIfResourceCheckedOut(String userId, Asset asset) { + if (DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT == DcaeBeConstants.LifecycleStateEnum.findState(asset.getLifecycleState())) { + String lastUpdaterUserId = asset.getLastUpdaterUserId(); + if (lastUpdaterUserId != null && !lastUpdaterUserId.equals(userId)) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), "User conflicts. Operation not allowed for user {} on resource checked out by {}", userId, lastUpdaterUserId); + ResponseFormat responseFormat = ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.USER_CONFLICT, null, userId, asset.getName(), lastUpdaterUserId); + throw new DcaeException(HttpStatus.FORBIDDEN, responseFormat.getRequestError()); + } + } + } + + boolean isNeedToCheckOut(String lifecycleState) { + return DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT != DcaeBeConstants.LifecycleStateEnum.findState(lifecycleState); + } + + void checkVfcmtType(ResourceDetailed vfcmt) { + if (AssetType.VFCMT != getValidAssetTypeOrNull(vfcmt.getResourceType()) || !"Template".equals(vfcmt.getCategory())) { + ResponseFormat responseFormat = ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.RESOURCE_NOT_VFCMT_ERROR, null, vfcmt.getUuid()); + throw new DcaeException(HttpStatus.BAD_REQUEST, responseFormat.getRequestError()); + } + } + + AssetType getValidAssetTypeOrNull(String type) { + try { + return AssetType.getAssetTypeByName(type); + } catch (IllegalArgumentException e) { + debugLogger.log(LogLevel.ERROR, this.getClass().getName(), "invalid asset type: {}. Error: {}", type, e); + return null; + } + } + + ResponseEntity handleException(Exception e, ErrConfMgr.ApiType apiType, String... variables){ + errLogger.log(LogLevel.ERROR, this.getClass().getName(), e.getMessage()); + return ErrConfMgr.INSTANCE.handleException(e, apiType, variables); + } + } diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/BlueprintBusinessLogic.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/BlueprintBusinessLogic.java new file mode 100644 index 0000000..0ccb6d8 --- /dev/null +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/BlueprintBusinessLogic.java @@ -0,0 +1,98 @@ +package org.onap.sdc.dcae.composition.impl; + +import org.apache.commons.lang.StringUtils; +import org.onap.sdc.common.onaplog.Enums.LogLevel; +import org.onap.sdc.dcae.catalog.asdc.ASDC; +import org.onap.sdc.dcae.catalog.asdc.ASDCUtils; +import org.onap.sdc.dcae.catalog.asdc.Blueprinter; +import org.onap.sdc.dcae.composition.restmodels.MessageResponse; +import org.onap.sdc.dcae.composition.restmodels.VfcmtData; +import org.onap.sdc.dcae.composition.restmodels.sdc.Artifact; +import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceDetailed; +import org.onap.sdc.dcae.composition.util.DcaeBeConstants; +import org.onap.sdc.dcae.composition.util.SystemProperties; +import org.onap.sdc.dcae.errormng.ActionStatus; +import org.onap.sdc.dcae.errormng.ErrConfMgr; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.io.StringReader; +import java.net.URI; + +@Component +public class BlueprintBusinessLogic extends BaseBusinessLogic { + + @Autowired + private Blueprinter blueprinter; + @Autowired + private ASDC asdc; + @Autowired + private SystemProperties systemProperties; + @Autowired private CompositionBusinessLogic compositionBusinessLogic; + + + @PostConstruct + public void init() { + URI sdcUri = URI.create(systemProperties.getProperties().getProperty(DcaeBeConstants.Config.URI)); + asdc.setUri(sdcUri); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "SDC uri: {}", sdcUri); + } + + public ResponseEntity generateAndSaveBlueprint(String userId, String context, String vfcmtUuid, String serviceUuid, String vfiName, String flowType, String requestId) { + try { + // prepare - fetch vfcmt and cdump + ResourceDetailed vfcmt = getSdcRestClient().getResource(vfcmtUuid, requestId); + Artifact cdumpArtifactData = fetchCdump(vfcmt, requestId); + if (null == cdumpArtifactData) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Composition not found on vfcmt {}", vfcmtUuid); + return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.MISSING_TOSCA_FILE, "", vfcmt.getName()); + } + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Found the cdump (composition.yml) on top of VFCMT {}", vfcmtUuid); + String cdump = cdumpArtifactData.getPayloadData(); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Going to use python procedure to create a blueprint...."); + String resultBlueprintCreation = generateBlueprintViaToscaLab(cdump); + if (StringUtils.isEmpty(resultBlueprintCreation)) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Error occurred during blueprint generation"); + return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.GENERATE_BLUEPRINT_ERROR, "", vfcmt.getName()); + } + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "BLUEPRINT:\n{}", resultBlueprintCreation); + + // 1806 US374595 flowType in cdump + String flowTypeFromCdump = extractFlowTypeFromCdump(cdump); + + // support backward compatibility + if(StringUtils.isBlank(flowTypeFromCdump)) { + flowTypeFromCdump = flowType; + } + + VfcmtData vfcmtData = new VfcmtData(vfcmt, vfiName, flowTypeFromCdump, serviceUuid); + Artifact blueprintArtifactResult = compositionBusinessLogic.submitComposition(userId, context, vfcmtData, resultBlueprintCreation, requestId); + if (null == blueprintArtifactResult) { + return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.SUBMIT_BLUEPRINT_ERROR); + } + + MessageResponse response = new MessageResponse(); + response.setSuccessResponse("Blueprint build complete \n. Blueprint=" + blueprintArtifactResult.getArtifactName()); + return new ResponseEntity<>(response, HttpStatus.OK); + } catch (Exception e) { + return handleException(e, ErrConfMgr.ApiType.SUBMIT_BLUEPRINT); + } + } + + private String generateBlueprintViaToscaLab(String cdump) { + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "---------------------------------------------------------------CDUMP: -----------------------------------------------------------------------------"); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), cdump); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "---------------------------------------------------------------------------------------------------------------------------------------------------"); + ASDCUtils utils = new ASDCUtils(asdc, blueprinter); + String resultBlueprintCreation = null; + try{ + resultBlueprintCreation = utils.buildBlueprintViaToscaLab(new StringReader(cdump)).waitForResult().waitForResult(); + }catch (Exception e){ + errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Generate blueprint via tosca lab error: {}", e); + } + return resultBlueprintCreation; + } +} diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/CompositionBusinessLogic.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/CompositionBusinessLogic.java new file mode 100644 index 0000000..e81ffe0 --- /dev/null +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/CompositionBusinessLogic.java @@ -0,0 +1,169 @@ +package org.onap.sdc.dcae.composition.impl; + +import com.fasterxml.jackson.core.JsonProcessingException; +import org.onap.sdc.common.onaplog.Enums.LogLevel; +import org.onap.sdc.dcae.composition.restmodels.CreateMcResponse; +import org.onap.sdc.dcae.composition.restmodels.VfcmtData; +import org.onap.sdc.dcae.composition.restmodels.sdc.Artifact; +import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceDetailed; +import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceInstance; +import org.onap.sdc.dcae.composition.restmodels.sdc.ServiceDetailed; +import org.onap.sdc.dcae.composition.util.DcaeBeConstants; +import org.onap.sdc.dcae.enums.ArtifactType; +import org.onap.sdc.dcae.enums.LifecycleOperationType; +import org.onap.sdc.dcae.errormng.ActionStatus; +import org.onap.sdc.dcae.errormng.ErrConfMgr; +import org.onap.sdc.dcae.utils.Normalizers; +import org.onap.sdc.dcae.utils.SdcRestClientUtils; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.util.Base64Utils; +import org.springframework.util.CollectionUtils; + +import java.io.IOException; +import java.util.Collections; +import java.util.List; + +@Component +public class CompositionBusinessLogic extends BaseBusinessLogic { + + private static final String CREATE_DESC = "creating new artifact blueprint on the service vfi"; + private static final String UPDATE_DESC = "updating artifact blueprint on the service vfi"; + + public CreateMcResponse getDataAndComposition(String vfcmtUuid, String requestId) throws IOException { + ResourceDetailed vfcmt = sdcRestClient.getResource(vfcmtUuid, requestId); + Artifact composition = fetchCdump(vfcmt, requestId); + return buildVfcmtAndCdumpResponse(new VfcmtData(vfcmt), composition.getPayloadData()); + } + + // 1806 US399018 update composition - assumes an artifact already exists (create mode flag for backward compatibility) + public ResponseEntity saveComposition(String userId, String vfcmtUuid, String updatedPayload, String requestId, boolean allowCreateNew) { + + boolean undoCheckoutOnFailure = false; + ResourceDetailed vfcmt = null; + try { + vfcmt = sdcRestClient.getResource(vfcmtUuid, requestId); + Artifact artifactData = findCdumpArtifactData(vfcmt); + if (null == artifactData && !allowCreateNew) { + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Composition not found on vfcmt {}", vfcmt.getUuid()); + return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.MISSING_TOSCA_FILE, "", vfcmt.getName()); + } + if (DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT != DcaeBeConstants.LifecycleStateEnum.findState(vfcmt.getLifecycleState())) { + vfcmt = sdcRestClient.changeResourceLifecycleState(userId, vfcmt.getUuid(), LifecycleOperationType.CHECKOUT.name(), null, requestId); + undoCheckoutOnFailure = true; + } + if (null == artifactData) { + artifactData = SdcRestClientUtils.generateDeploymentArtifact("creating composition file", DcaeBeConstants.Composition.fileNames.COMPOSITION_YML, ArtifactType.DCAE_TOSCA.name(), "composition", updatedPayload.getBytes()); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "creating new composition artifact for MC: {}", vfcmt.getUuid()); + sdcRestClient.createResourceArtifact(userId, vfcmt.getUuid(), artifactData, requestId); + } else { + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "updating composition artifact for MC: {}", vfcmt.getUuid()); + artifactData.setDescription("updating composition"); + artifactData.setPayloadData(Base64Utils.encodeToString(updatedPayload.getBytes())); + sdcRestClient.updateResourceArtifact(userId, vfcmt.getUuid(), artifactData, requestId); + } + return new ResponseEntity<>(sdcRestClient.changeResourceLifecycleState(userId, vfcmt.getUuid(), LifecycleOperationType.CHECKIN.name(), "auto checkin after save composition", requestId), HttpStatus.OK); + } catch (Exception e) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Save composition failed: {}", e); + if(undoCheckoutOnFailure) { + rollBack(userId, vfcmt, requestId); + } + return ErrConfMgr.INSTANCE.handleException(e, ErrConfMgr.ApiType.SAVE_CDUMP); + } + } + + public Artifact submitComposition(String userId, String context, VfcmtData vfcmtData, String resultBlueprintCreation, String requestId) throws JsonProcessingException { + + // get service / find vfi + ServiceDetailed service = sdcRestClient.getAssetMetadata(context, vfcmtData.getServiceUuid(), requestId); + ResourceInstance vfi = findVfiOnService(service, vfcmtData.getVfiName()); + if(null == vfi){ + errLogger.log(LogLevel.ERROR, this.getClass().getName(), "VF instance {} not found on service {}", vfcmtData.getVfiName(), vfcmtData.getServiceUuid()); + return null; + } + // look for existing blueprint details + //1802,1806 US412711 - Allow multiple BP from the same flow type on a single VFi - identify existing blueprint by name - for backward compatibility + String artifactName = generateBlueprintFileName(vfcmtData.getFlowType(), vfcmtData.getName()); + Artifact blueprintArtifact = findExistingBlueprint(vfi, artifactName); + + // save blueprint as instance artifact + // create mode + if(null == blueprintArtifact) { + String artifactLabel = "blueprint-".concat(vfcmtData.getFlowType()).concat("-").concat(Normalizers.normalizeComponentName(vfcmtData.getName())); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Service {} does not consist {} ----> createMode", vfcmtData.getServiceUuid(), artifactLabel); + blueprintArtifact = SdcRestClientUtils.generateDeploymentArtifact(CREATE_DESC, artifactName , ArtifactType.DCAE_INVENTORY_BLUEPRINT.name(), artifactLabel, resultBlueprintCreation.getBytes()); + blueprintArtifact = sdcRestClient.createInstanceArtifact(userId, context, vfcmtData.getServiceUuid(), Normalizers.normalizeComponentInstanceName(vfcmtData.getVfiName()), blueprintArtifact, requestId); + // update mode + } else { + blueprintArtifact = updateBlueprint(userId, context, vfcmtData.getServiceUuid(), vfcmtData.getVfiName(), blueprintArtifact, resultBlueprintCreation, requestId); + // TODO should this be safe? + //1806 US390018 - remove reference to previous version + deletePreviousReference(userId, context, service, vfcmtData, requestId); + } + //1806 US374593 - certify VFCMT after BP generation + certifyVfcmt(userId, vfcmtData, requestId); + return blueprintArtifact; + } + + + private Artifact updateBlueprint(String userId, String context, String serviceUuid, String vfiName, Artifact blueprintArtifact, String payload, String requestId) throws JsonProcessingException { + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Found that service {} already consist of {} ----> updateMode", serviceUuid, blueprintArtifact.getArtifactLabel()); + blueprintArtifact.setDescription(UPDATE_DESC); + blueprintArtifact.setPayloadData(Base64Utils.encodeToString(payload.getBytes())); + return sdcRestClient.updateInstanceArtifact(userId, context, serviceUuid, Normalizers.normalizeComponentInstanceName(vfiName), blueprintArtifact, requestId); + } + + private Artifact findExistingBlueprint(ResourceInstance vfi, String artifactName) { + return CollectionUtils.isEmpty(vfi.getArtifacts()) ? null : vfi.getArtifacts().stream() + .filter(p -> Normalizers.normalizeArtifactLabel(artifactName).equals(Normalizers.normalizeArtifactLabel(p.getArtifactName()))) + .findAny() + .orElse(null); + } + + //TODO should this be safe or throw? + private void deletePreviousReference(String userId, String context, ServiceDetailed service, VfcmtData newReferencedMc, String requestId) { + String normalizedInstanceName = Normalizers.normalizeComponentInstanceName(newReferencedMc.getVfiName()); + List<String> vfiRefs = sdcRestClient.getMonitoringReferences(context, service.getUuid(), service.getVersion(), requestId).get(normalizedInstanceName); + if (null != vfiRefs && 1 < vfiRefs.size()) { + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Found {} external monitoring references for vfi {} on service {}:{}", vfiRefs.size(), newReferencedMc.getVfiName(), service.getUuid(), vfiRefs); + Collections.synchronizedList(vfiRefs).parallelStream() + .filter(p -> !newReferencedMc.getUuid().equals(p)) + .filter(p -> newReferencedMc.getInvariantUUID().equals(sdcRestClient.getResource(p, requestId).getInvariantUUID())) + .forEach(id -> sdcRestClient.deleteExternalMonitoringReference(userId, context, service.getUuid(), normalizedInstanceName, id, requestId)); + } else { + // this shouldn't happen - there should be at least two references registered to the vfi + debugLogger.log(LogLevel.WARN, this.getClass().getName(), "Sum Ting Wong. References found: {}", vfiRefs); + } + } + + private void certifyVfcmt(String userId, VfcmtData vfcmt, String requestId) { + String state = vfcmt.getLifecycleState(); + if(null == state) { + debugLogger.log(LogLevel.ERROR, this.getClass().getName(), "Couldn't read Vfcmt lifecycle state"); + return; + } + DcaeBeConstants.LifecycleStateEnum lifeCycleState = DcaeBeConstants.LifecycleStateEnum.findState(state); + if(null == lifeCycleState) { + debugLogger.log(LogLevel.ERROR, this.getClass().getName(), "Undefined lifecycle state: {}", state); + return; + } + try{ + switch (lifeCycleState){ + case NOT_CERTIFIED_CHECKOUT: + sdcRestClient.changeResourceLifecycleState(userId, vfcmt.getUuid(), LifecycleOperationType.CHECKIN.name(), "check in VFCMT after blueprint successful submission", requestId); + sdcRestClient.changeResourceLifecycleState(userId, vfcmt.getUuid(), LifecycleOperationType.CERTIFY.name(), "certify VFCMT after blueprint successful submission", requestId); + break; + case NOT_CERTIFIED_CHECKIN: + sdcRestClient.changeResourceLifecycleState(userId, vfcmt.getUuid(), LifecycleOperationType.CERTIFY.name(), "certify VFCMT after blueprint successful submission", requestId); + break; + default: + } + } + catch (Exception e){ + //informative only. no message to user (TBA) + debugLogger.log(LogLevel.ERROR, this.getClass().getName(), "Error occurred during vfcmt lifecycle operation: {}", e); + } + } + +} diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/ReferenceBusinessLogic.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/ReferenceBusinessLogic.java index d229b67..1396cc9 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/ReferenceBusinessLogic.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/ReferenceBusinessLogic.java @@ -2,7 +2,6 @@ package org.onap.sdc.dcae.composition.impl; import org.onap.sdc.common.onaplog.Enums.LogLevel; import org.onap.sdc.dcae.composition.restmodels.MonitoringComponent; -import org.onap.sdc.dcae.composition.restmodels.sdc.Artifact; import org.onap.sdc.dcae.composition.restmodels.sdc.ExternalReferencesMap; import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceInstance; import org.onap.sdc.dcae.composition.restmodels.sdc.ServiceDetailed; @@ -12,6 +11,7 @@ import org.onap.sdc.dcae.utils.Normalizers; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; import java.util.*; @@ -25,23 +25,27 @@ public class ReferenceBusinessLogic extends BaseBusinessLogic { try { String normalizedVfiName = Normalizers.normalizeComponentInstanceName(vfiName); ServiceDetailed serviceDetailed = sdcRestClient.getService(serviceUuid, requestId); - Optional<ResourceInstance> resourceInstance = serviceDetailed.getResources().stream().filter(item -> item.getResourceInstanceName().equalsIgnoreCase(vfiName)).findAny(); - if (resourceInstance.isPresent() && resourceInstance.get().getArtifacts() != null) { - Optional<Artifact> artifact = resourceInstance.get().getArtifacts().stream().filter(item -> item.getArtifactName().contains(monitoringComponentName)).findAny(); - artifact.ifPresent(artifact1 -> sdcRestClient.deleteInstanceResourceArtifact(userId, context, serviceUuid, normalizedVfiName, artifact1.getArtifactUUID(), requestId)); + ResourceInstance resourceInstance = findVfiOnService(serviceDetailed, vfiName); + if (resourceInstance != null && resourceInstance.getArtifacts() != null) { + String artifactNameEndsWith = generateBlueprintFileName("", monitoringComponentName); + resourceInstance.getArtifacts().stream() + .filter(item -> StringUtils.endsWithIgnoreCase(item.getArtifactName(), artifactNameEndsWith)) + .findAny() + .ifPresent(artifact -> sdcRestClient.deleteInstanceArtifact(userId, context, serviceUuid, normalizedVfiName, artifact.getArtifactUUID(), requestId)); } } catch (Exception e) { debugLogger.log(LogLevel.DEBUG, this.getClass().getName(),"Failed to delete blueprint with serviceUuid {}, vfcmtUuid . message: {} ", serviceUuid, vfcmtUuid, e); - return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.DELETE_BLUEPRINT_FAILED); + return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.DELETE_BLUEPRINT_FAILED, e.getMessage()); } return new ResponseEntity<>(HttpStatus.OK); } + public void deleteVfcmtReference(String userId, String context, String serviceUuid, String vfiName, String vfcmtUuid, String requestId) { debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Going to delete vfcmt reference, vfiName = {}", vfiName); String normalizedVfiName = Normalizers.normalizeComponentInstanceName(vfiName); - sdcRestClient.deleteExternalMonitoringReference(userId, context, serviceUuid, normalizedVfiName, vfcmtUuid, requestId); - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Finished to delete vfcmt reference. serviceUuid {}, vfcmtUuid {}", serviceUuid, vfcmtUuid); + sdcRestClient.deleteExternalMonitoringReference(userId, context, serviceUuid, normalizedVfiName, vfcmtUuid, requestId); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Finished to delete vfcmt reference. serviceUuid {}, vfcmtUuid {}", serviceUuid, vfcmtUuid); } // 1806 US381853 Return a list of monitoring components by external reference id. Support partial success @@ -70,5 +74,4 @@ public class ReferenceBusinessLogic extends BaseBusinessLogic { return result; } - } diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/RuleEditorBusinessLogic.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/RuleEditorBusinessLogic.java new file mode 100644 index 0000000..d17a6bf --- /dev/null +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/RuleEditorBusinessLogic.java @@ -0,0 +1,389 @@ +package org.onap.sdc.dcae.composition.impl; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.google.gson.JsonParseException; +import org.apache.commons.collections.ListUtils; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.onap.sdc.common.onaplog.Enums.LogLevel; +import org.onap.sdc.dcae.composition.CompositionConfig; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.*; +import org.onap.sdc.dcae.composition.restmodels.sdc.Artifact; +import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceDetailed; +import org.onap.sdc.dcae.composition.util.DcaeBeConstants; +import org.onap.sdc.dcae.enums.ArtifactType; +import org.onap.sdc.dcae.errormng.ActionStatus; +import org.onap.sdc.dcae.errormng.ErrConfMgr; +import org.onap.sdc.dcae.errormng.ServiceException; +import org.onap.sdc.dcae.rule.editor.impl.RulesBusinessLogic; +import org.onap.sdc.dcae.rule.editor.utils.RulesPayloadUtils; +import org.onap.sdc.dcae.utils.Normalizers; +import org.onap.sdc.dcae.utils.SdcRestClientUtils; +import org.onap.sdc.dcae.ves.VesDataItemsDefinition; +import org.onap.sdc.dcae.ves.VesDataTypeDefinition; +import org.onap.sdc.dcae.ves.VesSimpleTypesEnum; +import org.onap.sdc.dcae.ves.VesStructureLoader; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.util.Base64Utils; +import org.springframework.util.CollectionUtils; +import org.springframework.web.bind.annotation.*; + +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@Component +public class RuleEditorBusinessLogic extends BaseBusinessLogic { + + @Autowired + private RulesBusinessLogic rulesBusinessLogic; + @Autowired + private CompositionConfig compositionConfig; + + private static final String EXCEPTION = "Exception {}"; + + public ResponseEntity saveRule(String json, String requestId, String userId, String vfcmtUuid, String dcaeCompLabel, String nid, String configParam) { + + try { + Rule rule = RulesPayloadUtils.parsePayloadToRule(json); + if (null == rule) { + return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.INVALID_RULE_FORMAT); + } + + List<ServiceException> errors = rulesBusinessLogic.validateRule(rule); + if (!errors.isEmpty()) { + return ErrConfMgr.INSTANCE.buildErrorArrayResponse(errors); + } + + ResourceDetailed vfcmt = getSdcRestClient().getResource(vfcmtUuid, requestId); + checkVfcmtType(vfcmt); + + if (CollectionUtils.isEmpty(vfcmt.getArtifacts())) { + return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.SAVE_RULE_FAILED); + } + + String artifactLabel = Normalizers.normalizeArtifactLabel(dcaeCompLabel + nid + configParam); + + // check for MappingRules artifact in existing artifacts + Artifact artifactFound = vfcmt.getArtifacts().stream() + .filter(a -> artifactLabel.equals(Normalizers.normalizeArtifactLabel(a.getArtifactLabel()))) + .findAny().orElse(null); + + // exception thrown if vfcmt is checked out and current user is not its owner + // performs checkoutVfcmt if required + String vfcmtId = assertOwnershipOfVfcmtId(userId, vfcmt, requestId); + // new mappingRules artifact, validate nid exists in composition before creating new artifact + if (null == artifactFound) { + if (cdumpContainsNid(vfcmt, nid, requestId)) { + return saveNewRulesArtifact(rule, vfcmtId, generateMappingRulesFileName(dcaeCompLabel, nid, configParam), artifactLabel, userId, requestId); + } + return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.NODE_NOT_FOUND, "", dcaeCompLabel); + } + + //update artifact flow - append new rule or edit existing rule + return addOrEditRuleInArtifact(rule, vfcmtId, userId, artifactFound, requestId); + + } catch (JsonParseException je) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Error: Rule format is invalid: {}", je); + return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.INVALID_RULE_FORMAT, "", je.getMessage()); + } catch (Exception e) { + return ErrConfMgr.INSTANCE.handleException(e, ErrConfMgr.ApiType.SAVE_RULE_ARTIFACT); + } + + } + + public ResponseEntity getRules(String vfcmtUuid, String dcaeCompLabel, String nid, String configParam, String requestId) { + + try { + ResourceDetailed vfcmt = getSdcRestClient().getResource(vfcmtUuid, requestId); + if (CollectionUtils.isEmpty(vfcmt.getArtifacts())) { + return new ResponseEntity<>("{}", HttpStatus.OK); + } + String artifactLabel = Normalizers.normalizeArtifactLabel(dcaeCompLabel + nid + configParam); + + // check for MappingRules artifact in existing artifacts + Artifact artifactListed = vfcmt.getArtifacts().stream().filter(a -> artifactLabel.equals(Normalizers.normalizeArtifactLabel(a.getArtifactLabel()))).findAny().orElse(null); + if (null == artifactListed) { + return new ResponseEntity<>("{}", HttpStatus.OK); + } + String ruleFile = getSdcRestClient().getResourceArtifact(vfcmtUuid, artifactListed.getArtifactUUID(), requestId); + + // To avoid opening the file for reading we search for the eventType and SchemaVer from the artifact metadata's description + SchemaInfo schemainfo = RulesPayloadUtils.extractInfoFromDescription(artifactListed); + List<EventTypeDefinitionUI> schema = null == schemainfo ? new ArrayList<>() : getEventTypeDefinitionUIs(schemainfo.getVersion(), schemainfo.getEventType()); + return new ResponseEntity<>(RulesPayloadUtils.buildSchemaAndRulesResponse(ruleFile, schema), HttpStatus.OK); + } catch (Exception e) { + return ErrConfMgr.INSTANCE.handleException(e, ErrConfMgr.ApiType.GET_RULE_ARTIFACT); + } + + } + + public ResponseEntity deleteRule(String userId, String vfcmtUuid, String dcaeCompLabel, String nid, String configParam, String ruleUid, String requestId) { + + try { + ResourceDetailed vfcmt = getSdcRestClient().getResource(vfcmtUuid, requestId); + if (null == vfcmt.getArtifacts()) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), "VFCMT {} doesn't have artifacts", vfcmtUuid); + return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.DELETE_RULE_FAILED); + } + String artifactLabel = Normalizers.normalizeArtifactLabel(dcaeCompLabel + nid + configParam); + + // check for MappingRules artifact in existing artifacts + Artifact mappingRuleFile = vfcmt.getArtifacts().stream() + .filter(a -> artifactLabel.equals(Normalizers.normalizeArtifactLabel(a.getArtifactLabel()))) + .findAny().orElse(null); + + if (null == mappingRuleFile) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), "{} doesn't exist for VFCMT {}", artifactLabel, vfcmtUuid); + return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.DELETE_RULE_FAILED); + } + + String vfcmtId = assertOwnershipOfVfcmtId(userId, vfcmt, requestId); + String payload = getSdcRestClient().getResourceArtifact(vfcmtId, mappingRuleFile.getArtifactUUID(), requestId); + MappingRules rules = RulesPayloadUtils.parseMappingRulesArtifactPayload(payload); + Rule removedRule = rulesBusinessLogic.deleteRule(rules, ruleUid); + if (null == removedRule) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Rule {} not found.", ruleUid); + return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.DELETE_RULE_FAILED); + } + if (rules.isEmpty()) { // if file doesn't contain any rules after last deletion -> let's delete the file + getSdcRestClient().deleteResourceArtifact(userId, vfcmtId, mappingRuleFile.getArtifactUUID(), requestId); + } else { + updateRulesArtifact(vfcmtId, userId, mappingRuleFile, rules, requestId); + } + return checkInAndReturnSaveArtifactResult(removedRule, vfcmtId, userId, requestId); + } catch (Exception e) { + return ErrConfMgr.INSTANCE.handleException(e, ErrConfMgr.ApiType.SAVE_RULE_ARTIFACT); + } + + } + + public ResponseEntity translateRules(String vfcmtUuid, String requestId, String dcaeCompLabel, String nid, String configParam, String flowType) { + + try { + + if (StringUtils.isBlank(flowType) || MapUtils.isEmpty(compositionConfig.getFlowTypesMap()) || null == compositionConfig.getFlowTypesMap().get(flowType)) { + return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.TRANSLATE_FAILED, "", "Flow type " + flowType + " not found"); + } + + // extract entry phase name and last phase name from configuration: + String entryPointPhaseName = compositionConfig.getFlowTypesMap().get(flowType).getEntryPointPhaseName(); + String lastPhaseName = compositionConfig.getFlowTypesMap().get(flowType).getLastPhaseName(); + + ResourceDetailed vfcmt = getSdcRestClient().getResource(vfcmtUuid, requestId); + checkVfcmtType(vfcmt); + + if (CollectionUtils.isEmpty(vfcmt.getArtifacts())) { + return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.TRANSLATE_FAILED, "", "No rules found on VFCMT " + vfcmtUuid); + } + String artifactLabel = Normalizers.normalizeArtifactLabel(dcaeCompLabel + nid + configParam); + + // check for MappingRules artifact in existing artifacts + Artifact rulesArtifact = vfcmt.getArtifacts().stream().filter(a -> artifactLabel.equals(Normalizers.normalizeArtifactLabel(a.getArtifactLabel()))).findAny().orElse(null); + + if (rulesArtifact == null) { + return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.TRANSLATE_FAILED, "", artifactLabel + " doesn't exist on VFCMT " + vfcmtUuid); + } + + String payload = getSdcRestClient().getResourceArtifact(vfcmtUuid, rulesArtifact.getArtifactUUID(), requestId); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Retrieved mapping rules artifact {}, start parsing rules...", artifactLabel); + MappingRules rules = RulesPayloadUtils.parseMappingRulesArtifactPayload(payload); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Finished parsing rules, calling validator..."); + List<ServiceException> errors = rulesBusinessLogic.validateRules(rules); + if (!errors.isEmpty()) { + return ErrConfMgr.INSTANCE.buildErrorArrayResponse(errors); + } + + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Validation completed successfully, calling translator..."); + String translateJson = rulesBusinessLogic.translateRules(rules, entryPointPhaseName, lastPhaseName, vfcmt.getName()); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Translation completed successfully"); + return new ResponseEntity<>(translateJson, HttpStatus.OK); + } catch (Exception e) { + return ErrConfMgr.INSTANCE.handleException(e, ErrConfMgr.ApiType.SAVE_RULE_ARTIFACT); + } + } + + public ResponseEntity getExistingRuleTargets(String vfcmtUuid, String requestId, String dcaeCompLabel, String nid) { + + try { + ResourceDetailed vfcmt = getSdcRestClient().getResource(vfcmtUuid, requestId); + if (CollectionUtils.isEmpty(vfcmt.getArtifacts())) { + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "getExistingRuleTargets - no rules found! returning zero response."); + return new ResponseEntity<>("{}", HttpStatus.OK); + } + String artifactNameStartWith = dcaeCompLabel + "_" + nid + "_"; + + List<String> artifactWithRules = vfcmt.getArtifacts().stream().filter(artifact -> + artifact.getArtifactName().startsWith(artifactNameStartWith)) + .map(artifact -> StringUtils.substringBetween(artifact.getArtifactName(), artifactNameStartWith, DcaeBeConstants.Composition.fileNames.MAPPING_RULE_POSTFIX)).collect(Collectors.toList()); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "getExistingRuleTargets completed successfully"); + return new ResponseEntity<>(artifactWithRules, HttpStatus.OK); + } catch (Exception e) { + debugLogger.log(LogLevel.ERROR, this.getClass().getName(), "getExistingRuleTargets had exception", e); + return ErrConfMgr.INSTANCE.handleException(e, ErrConfMgr.ApiType.GET_RULE_ARTIFACT); + } + } + + public ResponseEntity getDefinition(String version, String eventType) { + + try { + List<EventTypeDefinitionUI> result = getEventTypeDefinitionUIs(version, eventType); + + return new ResponseEntity<>(result, HttpStatus.OK); + + } catch (Exception e) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), EXCEPTION, e); + return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.VES_SCHEMA_NOT_FOUND); + } + } + + public ResponseEntity getEventsByVersion() { + try { + + Map<String, Set<String>> eventsByVersions = VesStructureLoader.getAvailableVersionsAndEventTypes(); + + List<EventTypesByVersionUI> resBody = eventsByVersions.entrySet().stream().map(entry -> { + Set<String> events = entry.getValue().stream().filter(event -> !EventTypesByVersionUI.DEFAULT_EVENTS.contains(event)).collect(Collectors.toSet()); + return new EventTypesByVersionUI(entry.getKey(), events); + }).collect(Collectors.toList()); + + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Got a request to return all ves event types by versions {}", eventsByVersions); + return new ResponseEntity<>(resBody, HttpStatus.OK); + + } catch (Exception e) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), EXCEPTION, e); + return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.VES_SCHEMA_NOT_FOUND); + } + } + + ///////////////////PRIVATE METHODS//////////////////////////////////////////////////////////////////////// + + private String assertOwnershipOfVfcmtId(String userId, ResourceDetailed vfcmt, String requestId) { + checkUserIfResourceCheckedOut(userId, vfcmt); + String newVfcmtId = vfcmt.getUuid(); // may change after checking out a certified vfcmt + if (isNeedToCheckOut(vfcmt.getLifecycleState())) { + ResourceDetailed result = checkoutVfcmt(userId, newVfcmtId, requestId); + if (result != null) { + newVfcmtId = result.getUuid(); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "New resource after checkoutVfcmt is: {}", newVfcmtId); + } + } + return newVfcmtId; + } + + // called after validating vfcmt.getArtifacts() is not null + private boolean cdumpContainsNid(ResourceDetailed vfcmt, String nid, String requestId) { + Artifact cdump = vfcmt.getArtifacts().stream() + .filter(a -> DcaeBeConstants.Composition.fileNames.COMPOSITION_YML.equalsIgnoreCase(a.getArtifactName())) + .findAny().orElse(null); + if (null == cdump || null == cdump.getArtifactUUID()) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), "No {} found on vfcmt {}", DcaeBeConstants.Composition.fileNames.COMPOSITION_YML, vfcmt.getUuid()); + return false; + } + try { + String artifact = getSdcRestClient().getResourceArtifact(vfcmt.getUuid(), cdump.getArtifactUUID(), requestId); + if (!artifact.contains("\"nid\":\"" + nid)) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), "{} doesn't contain nid {}. Cannot save mapping rule file", DcaeBeConstants.Composition.fileNames.COMPOSITION_YML, nid); + return false; + } + } catch (Exception e) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), EXCEPTION, e); + return false; + } + return true; + } + + private ResponseEntity<String> saveNewRulesArtifact(Rule rule, String vfcmtUuid, String artifactFileName, String artifactLabel, String userId, String requestId) throws JsonProcessingException { + MappingRules body = new MappingRules(rule); + Artifact artifact = SdcRestClientUtils.generateDeploymentArtifact(body.describe(), artifactFileName, ArtifactType.OTHER.name(), artifactLabel, body.convertToPayload()); + getSdcRestClient().createResourceArtifact(userId, vfcmtUuid, artifact, requestId); + return checkInAndReturnSaveArtifactResult(rule, vfcmtUuid, userId, requestId); + } + + private ResponseEntity addOrEditRuleInArtifact(Rule rule, String vfcmtUuid, String userId, Artifact rulesArtifact, String requestId) throws JsonProcessingException { + String payload = getSdcRestClient().getResourceArtifact(vfcmtUuid, rulesArtifact.getArtifactUUID(), requestId); + MappingRules rules = RulesPayloadUtils.parseMappingRulesArtifactPayload(payload); + + // in case the rule id is passed but the rule doesn't exist on the mapping rule file: + if (!rulesBusinessLogic.addOrEditRule(rules, rule)) { + return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.SAVE_RULE_FAILED); + } + updateRulesArtifact(vfcmtUuid, userId, rulesArtifact, rules, requestId); + return checkInAndReturnSaveArtifactResult(rule, vfcmtUuid, userId, requestId); + } + + // regardless of check in result, return save artifact success + private ResponseEntity<String> checkInAndReturnSaveArtifactResult(Rule rule, String vfcmtUuid, String userId, String requestId) { + try { + checkinVfcmt(userId, vfcmtUuid, requestId); + } catch (Exception e) { + // swallowing the exception intentionally since it is on the check in action + errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Error occurred while performing check in on VFCMT {}:{}", vfcmtUuid, e); + } + return new ResponseEntity<>(rule.toJson(), HttpStatus.OK); + } + + private void updateRulesArtifact(String vfcmtUuid, String userId, Artifact artifactInfo, MappingRules rules, String requestId) throws JsonProcessingException { + artifactInfo.setPayloadData(Base64Utils.encodeToString(rules.convertToPayload())); + // POST must contain 'description' while GET returns 'artifactDescription' + artifactInfo.setDescription(artifactInfo.getArtifactDescription()); + getSdcRestClient().updateResourceArtifact(userId, vfcmtUuid, artifactInfo, requestId); + } + + + /** + * @param eventMapStream + * @param parent + * @param path + * @return + */ + private List<EventTypeDefinitionUI> convertToEventTypeDefinition(Stream<Map.Entry<String, VesDataTypeDefinition>> eventMapStream, VesDataTypeDefinition parent, String path) { + + return eventMapStream.map(entry -> { + Map<String, VesDataTypeDefinition> properties = entry.getValue().getProperties(); + VesDataItemsDefinition items = entry.getValue().getItems(); + String newPath = path + "." + entry.getKey(); + List<EventTypeDefinitionUI> children = (properties == null) ? null : convertToEventTypeDefinition(properties.entrySet().stream(), entry.getValue(), newPath); + if (VesSimpleTypesEnum.ARRAY.getType().equals(entry.getValue().getType())) { + newPath += "[]"; + if (innerTypeIsComplex(items)) { + children = convertComplexArrayType(items, newPath); + } else if (innerTypeIsArray(items)) { + newPath += "[]"; + } + } + + boolean isRequired = (parent != null) ? parent.getRequired().contains(entry.getKey()) : false; + return new EventTypeDefinitionUI(entry.getKey(), children, isRequired, newPath); + }).collect(Collectors.toList()); + } + + private boolean innerTypeIsComplex(VesDataItemsDefinition items) { + return items != null && items.stream().anyMatch(p -> p.getProperties() != null); + } + + private boolean innerTypeIsArray(VesDataItemsDefinition items) { + return items != null && items.stream().anyMatch(p -> p.getItems() != null); + } + + private List<EventTypeDefinitionUI> convertComplexArrayType(VesDataItemsDefinition items, String path) { + return items.stream().map(item -> item.getProperties() != null ? convertToEventTypeDefinition(item.getProperties().entrySet().stream(), item, path) : new ArrayList<EventTypeDefinitionUI>()) + .flatMap(List::stream).collect(Collectors.toList()); + } + + + private String generateMappingRulesFileName(String dcaeCompLabel, String nid, String configParam) { + return dcaeCompLabel + "_" + nid + "_" + configParam + DcaeBeConstants.Composition.fileNames.MAPPING_RULE_POSTFIX; + } + + private List<EventTypeDefinitionUI> getEventTypeDefinitionUIs(String version, String eventType) { + List<String> eventNamesToReturn = ListUtils.union(EventTypesByVersionUI.DEFAULT_EVENTS, Arrays.asList(eventType)); + Map<String, VesDataTypeDefinition> eventDefs = VesStructureLoader.getEventListenerDefinitionByVersion(version); + Stream<Map.Entry<String, VesDataTypeDefinition>> filteredEvents = eventDefs.entrySet().stream().filter(entry -> eventNamesToReturn.contains(entry.getKey())); + + return convertToEventTypeDefinition(filteredEvents, null, "event"); + } +} diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/ServiceBusinessLogic.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/ServiceBusinessLogic.java new file mode 100644 index 0000000..d04c67a --- /dev/null +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/ServiceBusinessLogic.java @@ -0,0 +1,194 @@ +package org.onap.sdc.dcae.composition.impl; + + import org.onap.sdc.common.onaplog.Enums.LogLevel; + import org.onap.sdc.dcae.composition.restmodels.AttachVFCMTServiceRequest; + import org.onap.sdc.dcae.composition.restmodels.DcaeMinimizedService; + import org.onap.sdc.dcae.composition.restmodels.MessageResponse; + import org.onap.sdc.dcae.composition.restmodels.sdc.*; + import org.onap.sdc.dcae.composition.util.DcaeBeConstants; + import org.onap.sdc.dcae.enums.ArtifactType; + import org.onap.sdc.dcae.enums.LifecycleOperationType; + import org.onap.sdc.dcae.errormng.ActionStatus; + import org.onap.sdc.dcae.errormng.DcaeException; + import org.onap.sdc.dcae.errormng.ErrConfMgr; + import org.onap.sdc.dcae.errormng.ResponseFormat; + import org.onap.sdc.dcae.utils.SdcRestClientUtils; + import org.springframework.http.HttpStatus; + import org.springframework.http.ResponseEntity; + import org.springframework.stereotype.Component; + import org.springframework.util.Base64Utils; + import org.springframework.util.CollectionUtils; + + import java.util.ArrayList; + import java.util.Comparator; + import java.util.LinkedHashMap; + import java.util.List; + import java.util.stream.Collectors; + +@Component +public class ServiceBusinessLogic extends BaseBusinessLogic { + + + public ResponseEntity services(String userId, String vfcmtUuid, String requestId) { + try { + ResourceDetailed vfcmt = getSdcRestClient().getResource(vfcmtUuid, requestId); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "GET ({}) Vfcmt form SDC: {}", vfcmtUuid, vfcmt); + checkVfcmtType(vfcmt); + checkUserIfResourceCheckedOut(userId, vfcmt); + + List<Service> services = getSdcRestClient().getServices(requestId); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "GET services data from SDC: {}", services); + List<Service> uuids = filterServicesByUser(services, userId); + return new ResponseEntity<>(uuids, HttpStatus.OK); + } catch (Exception e) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), e.getMessage()); + return ErrConfMgr.INSTANCE.handleException(e, ErrConfMgr.ApiType.GET_SERVICE); + } + } + + public ResponseEntity service(String theServiceId, String requestId) { + try { + ServiceDetailed service = getSdcRestClient().getService(theServiceId, requestId); + if (service != null) { + if(service.getResources()!=null){ + List<ResourceInstance> vfResourcesOnly = service.getResources().stream().filter(vfi -> vfi.getResoucreType().equals("VF")).collect(Collectors.toList()); + service.setResources(vfResourcesOnly); + }else{ + errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Service {} doesn't have any resources (e.g VFi's)", theServiceId); + } + } else { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Couldn't fetch service with uuid {} from SDC", theServiceId); + } + return new ResponseEntity<>(service, HttpStatus.OK); + } catch (Exception e) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), e.getMessage()); + return ErrConfMgr.INSTANCE.handleException(e, ErrConfMgr.ApiType.GET_SERVICE); + } + } + + + public ResponseEntity attachService( String vfcmtUuid, String userId, AttachVFCMTServiceRequest request, String requestId) { + + String serviceUuid = request.getServiceUuid(); + String vfiName = request.getInstanceName(); + String resourceUuid = vfcmtUuid; + MessageResponse response = new MessageResponse(); + + try { + ResourceDetailed vfcmt = getSdcRestClient().getResource(vfcmtUuid, requestId); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), vfcmt.toString()); + + checkVfcmtType(vfcmt); + verifyVfiExists(serviceUuid, vfiName, requestId); + + boolean isUpdateMode = false; + Artifact artifactObj = null; + + String reference = serviceUuid + "/resources/" + vfiName; + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "*****************************************"); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Reference between service and vfi {}", reference); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "*****************************************"); + + if(!CollectionUtils.isEmpty(vfcmt.getArtifacts())){ + artifactObj = vfcmt.getArtifacts().stream().filter(a -> DcaeBeConstants.Composition.fileNames.SVC_REF.equals(a.getArtifactName())).findAny().orElse(null); + isUpdateMode = null != artifactObj; + } + + if (isNeedToCheckOut(vfcmt.getLifecycleState())) { + vfcmt = getSdcRestClient().changeResourceLifecycleState(userId, vfcmtUuid, LifecycleOperationType.CHECKOUT.name(), null, requestId); + if (vfcmt != null) { + resourceUuid = vfcmt.getUuid(); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "New vfcmt uuid after checkoutVfcmt is: {}", resourceUuid); + } + } + + if(isUpdateMode){ + updateReferenceArtifact(userId, resourceUuid, artifactObj, reference, requestId); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Artifact {} updated with content: {}", reference, DcaeBeConstants.Composition.fileNames.SVC_REF, reference); + }else{ + Artifact artifact = SdcRestClientUtils.generateDeploymentArtifact("createReferenceArtifact", DcaeBeConstants.Composition.fileNames.SVC_REF, ArtifactType.DCAE_TOSCA.name(), "servicereference", reference.getBytes()); + getSdcRestClient().createResourceArtifact(userId, resourceUuid, artifact, requestId); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Artifact {} created with content: {}", DcaeBeConstants.Composition.fileNames.SVC_REF, reference); + } + checkinVfcmt(userId, resourceUuid, requestId); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Attachment of reference={} in VFCMT {} has finished successfully", reference, resourceUuid); + + response.setSuccessResponse("Artifact updated"); + return new ResponseEntity<>(response, HttpStatus.OK); + } catch (Exception e) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), e.getMessage()); + return ErrConfMgr.INSTANCE.handleException(e, ErrConfMgr.ApiType.ATTACH_TO_SERVICE); + } + } + + public ResponseEntity getAttachedService(String vfcmtUuid, String requestId) { + + MessageResponse response = new MessageResponse(); + + try { + ResourceDetailed vfcmt = getSdcRestClient().getResource(vfcmtUuid, requestId); + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), vfcmt.toString()); + checkVfcmtType(vfcmt); + String artifact = "No Artifacts"; + + if (!CollectionUtils.isEmpty(vfcmt.getArtifacts())) { + Artifact artifactObj = vfcmt.getArtifacts().stream().filter(a -> DcaeBeConstants.Composition.fileNames.SVC_REF.equals(a.getArtifactName())).findAny().orElse(null); + if (null != artifactObj) { + artifact = getSdcRestClient().getResourceArtifact(vfcmtUuid, artifactObj.getArtifactUUID(), requestId); + } + } + response.setSuccessResponse(artifact); + return new ResponseEntity<>(response, HttpStatus.OK); + } catch (Exception e) { + errLogger.log(LogLevel.ERROR, this.getClass().getName(), e.getMessage()); + return ErrConfMgr.INSTANCE.handleException(e, ErrConfMgr.ApiType.GET_VFCMT); + } + } + + /**** PRIVATE METHODS ****/ + + private void updateReferenceArtifact(String userId, String VFCMTUuid, Artifact artifactObj, String reference, String requestId) throws Exception { + artifactObj.setDescription("updateReferenceArtifact"); + artifactObj.setPayloadData(Base64Utils.encodeToString(reference.getBytes())); + getSdcRestClient().updateResourceArtifact(userId, VFCMTUuid, artifactObj, requestId); + } + + + + //TODO move method to ci tests + public List<DcaeMinimizedService> parseAndFilterServicesByUser(String lastUpdaterUserId, List<LinkedHashMap<String, String>> services, String userId) { + List<DcaeMinimizedService> uuids = null; + if (services != null) { + //services.stream().filter(predicate) + uuids = services.stream() + .map(x -> new DcaeMinimizedService(x.get("uuid"), x.get("name"), x.get("lastUpdaterUserId"), x.get("lifecycleState"), x.get("version"), x.get("invariantUUID"))) + .collect(Collectors.groupingBy(DcaeMinimizedService::getInvariantUUID)).values().stream() + .map(p -> p.stream() + .sorted(Comparator.comparing(DcaeMinimizedService::getVersionAsFloat).reversed())).map(p -> p.collect(Collectors.toList())).map(p -> p.get(0)) + .filter(x -> (!(!x.getLastUpdaterUserId().equals(userId) && x.getLifeCycleState().equals(DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())))) + .sorted(Comparator.comparing(DcaeMinimizedService::getName)).collect(Collectors.toList()); + } + return uuids; + } + + private List<Service> filterServicesByUser(List<Service> services, String userId) { + return CollectionUtils.isEmpty(services) ? new ArrayList<>() : services.stream() + .collect(Collectors.groupingBy(Service::getInvariantUUID)).values().stream() + .map(p -> p.stream() + .sorted(Comparator.comparing(Service::versionAsFloat).reversed())).map(p -> p.collect(Collectors.toList())).map(p -> p.get(0)) + .filter(x -> (!(!x.getLastUpdaterUserId().equals(userId) && x.getLifecycleState().equals(DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())))) + .sorted(Comparator.comparing(Service::getName)).collect(Collectors.toList()); + } + + + private void verifyVfiExists(String serviceUuid, String vfiName, String requestId) throws Exception { + ServiceDetailed service = getSdcRestClient().getService(serviceUuid, requestId); + boolean isServiceContainsVfi = null != service && !CollectionUtils.isEmpty(service.getResources()) && service.getResources().stream() + .filter(vfi -> "VF".equals(vfi.getResoucreType())) + .anyMatch(vfi -> vfiName.equals(vfi.getResourceInstanceName())); + if (!isServiceContainsVfi) { + ResponseFormat responseFormat = ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.VFI_FETCH_ERROR, null, serviceUuid, vfiName); + throw new DcaeException(HttpStatus.NOT_FOUND, responseFormat.getRequestError()); + } + } +} diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/VfcmtBusinessLogic.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/VfcmtBusinessLogic.java index e68a8ee..4093555 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/VfcmtBusinessLogic.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/VfcmtBusinessLogic.java @@ -1,15 +1,19 @@ package org.onap.sdc.dcae.composition.impl; -import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.core.JsonProcessingException; import org.apache.commons.lang.StringUtils; import org.onap.sdc.common.onaplog.Enums.LogLevel; -import org.onap.sdc.dcae.composition.restmodels.*; +import org.onap.sdc.dcae.composition.restmodels.CreateVFCMTRequest; +import org.onap.sdc.dcae.composition.restmodels.ImportVFCMTRequest; +import org.onap.sdc.dcae.composition.restmodels.ReferenceUUID; +import org.onap.sdc.dcae.composition.restmodels.VfcmtData; import org.onap.sdc.dcae.composition.restmodels.sdc.Artifact; import org.onap.sdc.dcae.composition.restmodels.sdc.ExternalReferencesMap; import org.onap.sdc.dcae.composition.restmodels.sdc.Resource; import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceDetailed; import org.onap.sdc.dcae.composition.util.DcaeBeConstants; import org.onap.sdc.dcae.enums.ArtifactType; +import org.onap.sdc.dcae.enums.AssetType; import org.onap.sdc.dcae.enums.LifecycleOperationType; import org.onap.sdc.dcae.errormng.ActionStatus; import org.onap.sdc.dcae.errormng.ErrConfMgr; @@ -20,7 +24,7 @@ import org.springframework.stereotype.Component; import org.springframework.util.Base64Utils; import java.io.IOException; -import java.util.*; +import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -30,7 +34,6 @@ import static org.onap.sdc.dcae.composition.util.DcaeBeConstants.LifecycleStateE @Component public class VfcmtBusinessLogic extends BaseBusinessLogic { - private static final String VFCMT = "VFCMT"; private static final String TEMPLATE = "Template"; private static final String MONITORING_TEMPLATE = "Monitoring Template"; private static final String DEFAULTICON = "defaulticon"; @@ -42,21 +45,20 @@ public class VfcmtBusinessLogic extends BaseBusinessLogic { errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Missing information"); return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.INVALID_CONTENT); } - return cloneMcAndAddServiceReference(userId, request, requestId); + return cloneMcAndAddServiceReference(userId, request, requestId, false); } //1806 US388513 collect existing VFCMT data - flowType from cdump artifact and external reference from svc_reference artifact. If cdump not found - return error - - public ResponseEntity getVfcmtReferenceData(String vfcmtUuid, String requestId) throws Exception { - ResourceDetailed vfcmt = sdcRestClient.getResource(vfcmtUuid, requestId); - Artifact artifactData = findCdumpArtifactData(vfcmt); + public ResponseEntity getVfcmtReferenceData(String vfcmtUuid, String requestId) { + ResourceDetailed vfcmt = getSdcRestClient().getResource(vfcmtUuid, requestId); + Artifact artifactData = fetchCdump(vfcmt, requestId); if(null == artifactData) { debugLogger.log(LogLevel.DEBUG, this.getClass().getName(),"No composition found on vfcmt {}", vfcmtUuid); return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.MISSING_TOSCA_FILE, "", vfcmt.getName()); } VfcmtData vfcmtData = new VfcmtData(vfcmt); //fetch cdump payload - String payload = getSdcRestClient().getResourceArtifact(vfcmtUuid, artifactData.getArtifactUUID(), requestId); + String payload = artifactData.getPayloadData(); //extract and set flowType from cdump payload debugLogger.log(LogLevel.DEBUG, this.getClass().getName(),"Looking for flowType definition in cdump"); vfcmtData.setFlowType(StringUtils.substringBetween(payload,"\"flowType\":\"","\"")); @@ -74,7 +76,6 @@ public class VfcmtBusinessLogic extends BaseBusinessLogic { return new ResponseEntity<>(vfcmtData, HttpStatus.OK); } - //1806 US388525 import or clone VFCMT - always pass the flowType - update will only take place if missing from cdump public ResponseEntity importMC(String userId, ImportVFCMTRequest request, String requestId) { if(!validateMCRequestFields(request)) { @@ -83,7 +84,7 @@ public class VfcmtBusinessLogic extends BaseBusinessLogic { } // option 1 - clone if(request.isCloneVFCMT()) { - return cloneMcAndAddServiceReference(userId, request, requestId); + return cloneMcAndAddServiceReference(userId, request, requestId, request.isUpdateFlowType()); } ResourceDetailed vfcmt = null; @@ -91,11 +92,12 @@ public class VfcmtBusinessLogic extends BaseBusinessLogic { // fetch vfcmt and cdump try { vfcmt = sdcRestClient.getResource(request.getTemplateUuid(), requestId); - Artifact cdumpArtifactData = fetchCdumpAndSetFlowType(vfcmt, request.getFlowType(), requestId); + Artifact cdumpArtifactData = fetchCdump(vfcmt, requestId); if (null == cdumpArtifactData) { errLogger.log(LogLevel.ERROR, this.getClass().getName(), "No cdump found for monitoring component {}", vfcmt.getUuid()); return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.MISSING_TOSCA_FILE, "", vfcmt.getName()); } + String cdumpPayload = cdumpArtifactData.getPayloadData(); // option 2 - edit original cdump - requires check out @@ -104,7 +106,9 @@ public class VfcmtBusinessLogic extends BaseBusinessLogic { vfcmt = sdcRestClient.changeResourceLifecycleState(userId, vfcmt.getUuid(), LifecycleOperationType.CHECKOUT.name(), "checking out VFCMT", requestId); undoCheckoutOnFailure = true; } + cdumpArtifactData.setDescription("updating flowType on cdump"); + cdumpPayload = cdumpArtifactData.getPayloadData().replaceFirst("\\{", "{\"flowType\":\"" + request.getFlowType() + "\","); cdumpArtifactData.setPayloadData(Base64Utils.encodeToString(cdumpPayload.getBytes())); sdcRestClient.updateResourceArtifact(userId, vfcmt.getUuid(), cdumpArtifactData, requestId); } @@ -114,7 +118,7 @@ public class VfcmtBusinessLogic extends BaseBusinessLogic { // this will not throw an exception checkinVfcmtAfterClone(userId, vfcmt, requestId); } - return new ResponseEntity<>(buildVfcmtAndCdumpResponse(vfcmt, request.getVfiName(), request.getFlowType(), cdumpPayload), HttpStatus.OK); + return new ResponseEntity<>(buildVfcmtAndCdumpResponse(new VfcmtData(vfcmt, request.getVfiName(), extractFlowTypeFromCdump(cdumpPayload)), cdumpPayload), HttpStatus.OK); } catch (Exception e) { errLogger.log(LogLevel.ERROR,this.getClass().getName(),"Failed updating Monitoring Component:{}", e.getMessage()); if(undoCheckoutOnFailure) { @@ -122,7 +126,6 @@ public class VfcmtBusinessLogic extends BaseBusinessLogic { } return ErrConfMgr.INSTANCE.handleException(e, ErrConfMgr.ApiType.CREATE_NEW_VFCMT); } - } private boolean validateMCRequestFields(CreateVFCMTRequest request) { @@ -140,25 +143,15 @@ public class VfcmtBusinessLogic extends BaseBusinessLogic { } - private void rollBack(String userId, ResourceDetailed newVfcmt, String requestId) { - if (null != newVfcmt) { - try { - getSdcRestClient().changeResourceLifecycleState(userId, newVfcmt.getUuid(), LifecycleOperationType.UNDO_CHECKOUT.getValue(), "DCAE rollback", requestId); - } catch (Exception e) { - errLogger.log(LogLevel.ERROR,this.getClass().getName(),"Failed rolling back Monitoring Component. ID:{}", newVfcmt.getUuid()); - debugLogger.log(LogLevel.ERROR,this.getClass().getName(),"Failed rolling back Monitoring Component:{}", e); - } - } - } - private ResponseEntity cloneMcAndAddServiceReference(String userId, CreateVFCMTRequest request, String requestId) { + private ResponseEntity cloneMcAndAddServiceReference(String userId, CreateVFCMTRequest request, String requestId, boolean updateFlowType) { addSdcMandatoryFields(request, userId); ResourceDetailed newVfcmt = null; try { // Retrieve the Template VFCMT from SDC - use the template UUID provided from UI ResourceDetailed templateMC = sdcRestClient.getResource(request.getTemplateUuid(), requestId); // Download the CDUMP file from the template VFCMT - Artifact cdumpArtifactData = fetchCdumpAndSetFlowType(templateMC, request.getFlowType(), requestId); + Artifact cdumpArtifactData = updateFlowType ? fetchCdumpAndSetFlowType(templateMC, request.getFlowType(), requestId) : fetchCdump(templateMC, requestId); if (null == cdumpArtifactData) { errLogger.log(LogLevel.ERROR,this.getClass().getName(),"No cdump found for template {} while creating monitoring component", templateMC.getUuid()); return ErrConfMgr.INSTANCE.buildErrorResponse(ActionStatus.MISSING_TOSCA_FILE, "", templateMC.getName()); @@ -176,7 +169,7 @@ public class VfcmtBusinessLogic extends BaseBusinessLogic { // this will not throw an exception checkinVfcmtAfterClone(userId, newVfcmt, requestId); - return new ResponseEntity<>(buildVfcmtAndCdumpResponse(newVfcmt, request.getVfiName(), request.getFlowType(), cdumpPayload), HttpStatus.OK); + return new ResponseEntity<>(buildVfcmtAndCdumpResponse(new VfcmtData(newVfcmt, request.getVfiName(), extractFlowTypeFromCdump(cdumpPayload)), cdumpPayload), HttpStatus.OK); } catch (Exception e) { errLogger.log(LogLevel.ERROR,this.getClass().getName(),"Failed creating Monitoring Component:{}", e.getMessage()); rollBack(userId, newVfcmt, requestId); @@ -184,9 +177,6 @@ public class VfcmtBusinessLogic extends BaseBusinessLogic { } } - private CreateMcResponse buildVfcmtAndCdumpResponse(ResourceDetailed vfcmt, String vfiName, String flowType, String cdumpPayload) throws IOException { - return new CreateMcResponse(new VfcmtData(vfcmt, vfiName, flowType), new ObjectMapper().readValue(cdumpPayload, Object.class)); - } private void checkinVfcmtAfterClone(String userId, ResourceDetailed vfcmt, String requestId) { try { @@ -196,12 +186,7 @@ public class VfcmtBusinessLogic extends BaseBusinessLogic { } } - - private Artifact findCdumpArtifactData(ResourceDetailed vfcmt) { - return findArtifactDataByArtifactName(vfcmt, DcaeBeConstants.Composition.fileNames.COMPOSITION_YML); - } - - private void cloneRuleArtifacts(String userId, ResourceDetailed templateMC, String newVfcmtUuid, String requestId) throws Exception { + private void cloneRuleArtifacts(String userId, ResourceDetailed templateMC, String newVfcmtUuid, String requestId) throws JsonProcessingException { // handle rule artifacts using java 7 for-loop - exception propagation to calling method for(Artifact artifact : templateMC.getArtifacts()) { if(artifact.getArtifactName().endsWith(DcaeBeConstants.Composition.fileNames.MAPPING_RULE_POSTFIX)) { @@ -211,21 +196,17 @@ public class VfcmtBusinessLogic extends BaseBusinessLogic { } // fetch the vfcmt cdump artifact payload and insert the flowType. Return the artifact with updated payload or null (artifact doesn't exist) - private Artifact fetchCdumpAndSetFlowType(ResourceDetailed vfcmt, String flowType, String requestId) throws Exception { - Artifact cdumpArtifactData = findCdumpArtifactData(vfcmt); - if (null != cdumpArtifactData) { - String cdumpPayload = sdcRestClient.getResourceArtifact(vfcmt.getUuid(), cdumpArtifactData.getArtifactUUID(), requestId); - // Add flowType data to cdump if provided - if(!cdumpPayload.contains("\"flowType\":\"") && StringUtils.isNotBlank(flowType)) { - cdumpPayload = cdumpPayload.replaceFirst("\\{", "{\"flowType\":\"" + flowType + "\","); - } + private Artifact fetchCdumpAndSetFlowType(ResourceDetailed vfcmt, String flowType, String requestId) throws IOException { + Artifact cdumpArtifactData = fetchCdump(vfcmt, requestId); + if (null != cdumpArtifactData && null != cdumpArtifactData.getPayloadData() && !cdumpArtifactData.getPayloadData().contains("\"flowType\":\"")) { + String cdumpPayload = cdumpArtifactData.getPayloadData().replaceFirst("\\{", "{\"flowType\":\"" + flowType + "\","); cdumpArtifactData.setPayloadData(cdumpPayload); } return cdumpArtifactData; } // backward compatibility (very backward) - private void createReferenceArtifact(String userId, CreateVFCMTRequest request, String newVfcmtUuid, String requestId) throws Exception { + private void createReferenceArtifact(String userId, CreateVFCMTRequest request, String newVfcmtUuid, String requestId) throws JsonProcessingException { String referencePayload = request.getServiceUuid() + "/resources/" + request.getVfiName(); Artifact refArtifact = SdcRestClientUtils.generateDeploymentArtifact("createReferenceArtifact", DcaeBeConstants.Composition.fileNames.SVC_REF, ArtifactType.DCAE_TOSCA.name(), "servicereference", referencePayload.getBytes()); sdcRestClient.createResourceArtifact(userId, newVfcmtUuid, refArtifact, requestId); @@ -238,7 +219,7 @@ public class VfcmtBusinessLogic extends BaseBusinessLogic { ExternalReferencesMap connectedVfcmts; try { connectedVfcmts = getSdcRestClient().getMonitoringReferences(contextType, uuid, version, requestId); - resources = getSdcRestClient().getResources(VFCMT, TEMPLATE, MONITORING_TEMPLATE, requestId); + resources = getSdcRestClient().getResources(AssetType.VFCMT.name(), TEMPLATE, MONITORING_TEMPLATE, requestId); } catch (Exception e) { errLogger.log(LogLevel.ERROR,this.getClass().getName(),"Exception getVfcmtsForMigration {}", e); debugLogger.log(LogLevel.DEBUG,this.getClass().getName(),"Exception getVfcmtsForMigration {}", e); @@ -268,7 +249,7 @@ public class VfcmtBusinessLogic extends BaseBusinessLogic { public void addSdcMandatoryFields(CreateVFCMTRequest createRequest, String user) { createRequest.setContactId(user); createRequest.setIcon(DEFAULTICON); - createRequest.setResourceType(VFCMT); + createRequest.setResourceType(AssetType.VFCMT.name()); createRequest.setVendorName(VENDOR_NAME); createRequest.setVendorRelease(VENDOR_RELEASE); if (StringUtils.isBlank(createRequest.getCategory())) { diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/filter/LoggingFilter.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/filter/LoggingFilter.java index 919d244..84ce0b7 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/filter/LoggingFilter.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/filter/LoggingFilter.java @@ -1,21 +1,6 @@ package org.onap.sdc.dcae.filter; -import static java.net.HttpURLConnection.HTTP_BAD_METHOD; -import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; -import static java.net.HttpURLConnection.HTTP_CLIENT_TIMEOUT; -import static java.net.HttpURLConnection.HTTP_CONFLICT; -import static java.net.HttpURLConnection.HTTP_ENTITY_TOO_LARGE; -import static java.net.HttpURLConnection.HTTP_FORBIDDEN; -import static java.net.HttpURLConnection.HTTP_GONE; -import static java.net.HttpURLConnection.HTTP_LENGTH_REQUIRED; -import static java.net.HttpURLConnection.HTTP_NOT_ACCEPTABLE; -import static java.net.HttpURLConnection.HTTP_NOT_FOUND; -import static java.net.HttpURLConnection.HTTP_PAYMENT_REQUIRED; -import static java.net.HttpURLConnection.HTTP_PRECON_FAILED; -import static java.net.HttpURLConnection.HTTP_PROXY_AUTH; -import static java.net.HttpURLConnection.HTTP_REQ_TOO_LONG; -import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; -import static java.net.HttpURLConnection.HTTP_UNSUPPORTED_TYPE; +import static java.net.HttpURLConnection.*; import java.io.IOException; import java.util.Locale; @@ -32,126 +17,129 @@ import javax.servlet.http.HttpServletResponse; import org.apache.http.impl.EnglishReasonPhraseCatalog; import org.onap.sdc.common.onaplog.OnapLoggerAudit; +import org.onap.sdc.common.onaplog.OnapLoggerDebug; import org.onap.sdc.common.onaplog.OnapMDCWrapper; import org.onap.sdc.common.onaplog.Enums.OnapLoggerErrorCode; import org.onap.sdc.common.onaplog.Enums.LogLevel; public class LoggingFilter implements Filter { - - private static final String serviceName = "DCAE-D-BE"; - - private OnapMDCWrapper commonLoggerArgs = OnapMDCWrapper.getInstance(); - private OnapLoggerAudit auditLogger = OnapLoggerAudit.getInstance(); - - public LoggingFilter() { - super(); - } - - - @Override - public void destroy() {} - - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) - throws IOException, ServletException { - - boolean shouldLogRequest = true; - - try { - if (request instanceof HttpServletRequest) { - HttpServletRequest httpRequest = (HttpServletRequest) request; - if (httpRequest.getServletPath().equals("/healthCheck")) { - shouldLogRequest = false; - } - - if (shouldLogRequest) { - beforeHandle(httpRequest); - } - } - } catch (Exception e) { - // TODO: log problem with extracting parameters or writing to log - } - - filterChain.doFilter(request, response); // handle request - - try { - if (response instanceof HttpServletResponse && shouldLogRequest) { - afterHandle((HttpServletResponse) response); - } - } catch (Exception e) { - // TODO: log problem with extracting parameters or writing to log - } - } - - - private void beforeHandle(HttpServletRequest request) { - - String requestId = getRequestId(request); - request.setAttribute("requestId", requestId); // making requestId available for the API controllers - commonLoggerArgs - .clear() - .startTimer() - .setRemoteHost(request.getRemoteAddr()) - .setServiceName(serviceName) - .setPartnerName(getPartnerName(request.getHeader("USER_ID"), request.getHeader("user-agent"))) - .setKeyRequestId(requestId) - .setAutoServerIPAddress(request.getLocalAddr()) - .setOptCustomField1(request.getProtocol()) - .setOptCustomField2(request.getMethod()) - .setOptCustomField3(request.getServletPath()); - - } - - - private static String getRequestId(HttpServletRequest request) { - String requestId = request.getHeader("X-ECOMP-RequestID"); - return isNullOrEmpty(requestId) - ? UUID.randomUUID().toString() - : requestId; - } - - - private void afterHandle(HttpServletResponse response) { - String responseDesc = EnglishReasonPhraseCatalog.INSTANCE.getReason(response.getStatus(), Locale.ENGLISH); - commonLoggerArgs - .stopTimer() - .setResponseCode(getLoggingErrorCode(response.getStatus()).getErrorCode()) - .setResponseDesc(responseDesc) - .setOptCustomField4(Integer.toString(response.getStatus())); - - auditLogger - .setStatusCode(Integer.toString(response.getStatus())) - .log(LogLevel.INFO, this.getClass().getName(), responseDesc); - } - - - private OnapLoggerErrorCode getLoggingErrorCode(int httpResponseCode) { - if (isSuccessError(httpResponseCode)) { - return OnapLoggerErrorCode.SUCCESS; - } - else if (isSchemaError(httpResponseCode)) { - return OnapLoggerErrorCode.SCHEMA_ERROR; - } - else if (isDataError(httpResponseCode)) { - return OnapLoggerErrorCode.DATA_ERROR; - } - else if (isPermissionsError(httpResponseCode)) { - return OnapLoggerErrorCode.PERMISSION_ERROR; - } - else if (isTimeoutOrAvailabilityError(httpResponseCode)) { - return OnapLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR; - } - else if (isBusinessProcessError(httpResponseCode)) { - return OnapLoggerErrorCode.BUSINESS_PROCESS_ERROR; - } - else { - return OnapLoggerErrorCode.UNKNOWN_ERROR; - } - } - - - private boolean isTimeoutOrAvailabilityError(int httpResponseCode) { + + private static final String SERVICE_NAME = "DCAE-D-BE"; + + private OnapMDCWrapper commonLoggerArgs = OnapMDCWrapper.getInstance(); + private OnapLoggerAudit auditLogger = OnapLoggerAudit.getInstance(); + private OnapLoggerDebug onapLoggerDebug = OnapLoggerDebug.getInstance(); + + public LoggingFilter() { + super(); + } + + + @Override + public void destroy() { + // We have nothing to destroy + } + + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) + throws IOException, ServletException { + + boolean shouldLogRequest = true; + + try { + if (request instanceof HttpServletRequest) { + HttpServletRequest httpRequest = (HttpServletRequest) request; + if ("/healthCheck".equals(httpRequest.getServletPath())) { + shouldLogRequest = false; + } + + if (shouldLogRequest) { + beforeHandle(httpRequest); + } + } + } catch (Exception e) { + onapLoggerDebug.log(LogLevel.DEBUG,this.getClass().getName(),"Exception:{}",e); + } + + filterChain.doFilter(request, response); // handle request + + try { + if (response instanceof HttpServletResponse && shouldLogRequest) { + afterHandle((HttpServletResponse) response); + } + } catch (Exception e) { + onapLoggerDebug.log(LogLevel.DEBUG,this.getClass().getName(),"Exception:{}",e); + } + } + + + private void beforeHandle(HttpServletRequest request) { + String requestId = getRequestId(request); + request.setAttribute("requestId", requestId); // making requestId available for the API controllers + commonLoggerArgs + .clear() + .startTimer() + .setRemoteHost(request.getRemoteAddr()) + .setServiceName(SERVICE_NAME) + .setPartnerName(getPartnerName(request.getHeader("USER_ID"), request.getHeader("user-agent"))) + .setKeyRequestId(requestId) + .setAutoServerIPAddress(request.getLocalAddr()) + .setOptCustomField1(request.getProtocol()) + .setOptCustomField2(request.getMethod()) + .setOptCustomField3(request.getServletPath()); + + } + + + private static String getRequestId(HttpServletRequest request) { + String requestId = request.getHeader("X-ECOMP-RequestID"); + return isNullOrEmpty(requestId) + ? UUID.randomUUID().toString() + : requestId; + } + + + private void afterHandle(HttpServletResponse response) { + String responseDesc = EnglishReasonPhraseCatalog.INSTANCE.getReason(response.getStatus(), Locale.ENGLISH); + commonLoggerArgs + .stopTimer() + .setResponseCode(getLoggingErrorCode(response.getStatus()).getErrorCode()) + .setResponseDesc(responseDesc) + .setOptCustomField4(Integer.toString(response.getStatus())); + + auditLogger + .setStatusCode(Integer.toString(response.getStatus())) + .log(LogLevel.INFO, this.getClass().getName(), responseDesc); + } + + + private OnapLoggerErrorCode getLoggingErrorCode(int httpResponseCode) { + if (isSuccessError(httpResponseCode)) { + return OnapLoggerErrorCode.SUCCESS; + } + else if (isSchemaError(httpResponseCode)) { + return OnapLoggerErrorCode.SCHEMA_ERROR; + } + else if (isDataError(httpResponseCode)) { + return OnapLoggerErrorCode.DATA_ERROR; + } + else if (isPermissionsError(httpResponseCode)) { + return OnapLoggerErrorCode.PERMISSION_ERROR; + } + else if (isTimeoutOrAvailabilityError(httpResponseCode)) { + return OnapLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR; + } + else if (isBusinessProcessError(httpResponseCode)) { + return OnapLoggerErrorCode.BUSINESS_PROCESS_ERROR; + } + else { + return OnapLoggerErrorCode.UNKNOWN_ERROR; + } + } + + + private boolean isTimeoutOrAvailabilityError(int httpResponseCode) { switch (httpResponseCode) { case HTTP_BAD_REQUEST: @@ -160,9 +148,9 @@ public class LoggingFilter implements Filter { case HTTP_CLIENT_TIMEOUT: case HTTP_GONE: return true; + default: + return false; } - - return false; } private boolean isPermissionsError(int httpResponseCode) { @@ -173,9 +161,9 @@ public class LoggingFilter implements Filter { case HTTP_BAD_METHOD: case HTTP_PROXY_AUTH: return true; + default: + return false; } - - return false; } private boolean isDataError(int httpResponseCode) { @@ -188,19 +176,13 @@ public class LoggingFilter implements Filter { case HTTP_ENTITY_TOO_LARGE: case HTTP_UNSUPPORTED_TYPE: return true; + default: + return false; } - - return false; } private boolean isSchemaError(int httpResponseCode) { - - switch (httpResponseCode) { - case HTTP_CONFLICT: - return true; - } - - return false; + return httpResponseCode == HTTP_CONFLICT; } private boolean isSuccessError(int httpResponseCode) { @@ -212,13 +194,13 @@ public class LoggingFilter implements Filter { } private String getPartnerName(String userId, String userAgent) { - return (isNullOrEmpty(userId)) - ? getClientApplication(userAgent) - : userId; + return isNullOrEmpty(userId) + ? getClientApplication(userAgent) + : userId; } private String getClientApplication(String userAgent) { - if (userAgent != null && userAgent.length() > 0) { + if (userAgent != null && userAgent.length() > 0) { if (userAgent.toLowerCase().contains("firefox")) { return "fireFox_FE"; } @@ -234,14 +216,15 @@ public class LoggingFilter implements Filter { return userAgent; } return ""; - } - + } - private static boolean isNullOrEmpty(String str) { - return (str == null || str.isEmpty()); + private static boolean isNullOrEmpty(String str) { + return str == null || str.isEmpty(); } - @Override - public void init(FilterConfig config) throws ServletException {} + @Override + public void init(FilterConfig config) { + // We have nothing to do when initializing + } } diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/enums/RuleEditorElementType.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/enums/RuleEditorElementType.java index 0bec7d8..a5e4a39 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/enums/RuleEditorElementType.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/enums/RuleEditorElementType.java @@ -2,34 +2,26 @@ package org.onap.sdc.dcae.rule.editor.enums; import java.util.Arrays; -import org.onap.sdc.dcae.rule.editor.translators.ConditionGroupTranslator; -import org.onap.sdc.dcae.rule.editor.translators.ConditionTranslator; -import org.onap.sdc.dcae.rule.editor.translators.CopyActionTranslator; -import org.onap.sdc.dcae.rule.editor.translators.DateFormatterTranslator; -import org.onap.sdc.dcae.rule.editor.translators.FieldConditionTranslator; -import org.onap.sdc.dcae.rule.editor.translators.IRuleElementTranslator; -import org.onap.sdc.dcae.rule.editor.translators.MapActionTranslator; -import org.onap.sdc.dcae.rule.editor.translators.MappingRulesTranslator; -import org.onap.sdc.dcae.rule.editor.translators.RegexActionTranslator; -import org.onap.sdc.dcae.rule.editor.translators.RuleTranslator; -import org.onap.sdc.dcae.rule.editor.validators.ActionValidator; -import org.onap.sdc.dcae.rule.editor.validators.ConcatActionValidator; -import org.onap.sdc.dcae.rule.editor.validators.ConditionGroupValidator; -import org.onap.sdc.dcae.rule.editor.validators.ConditionValidator; -import org.onap.sdc.dcae.rule.editor.validators.DateFormatterValidator; -import org.onap.sdc.dcae.rule.editor.validators.IRuleElementValidator; -import org.onap.sdc.dcae.rule.editor.validators.MapActionValidator; -import org.onap.sdc.dcae.rule.editor.validators.RuleValidator; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.LogEventAction; +import org.onap.sdc.dcae.rule.editor.translators.*; +import org.onap.sdc.dcae.rule.editor.validators.*; public enum RuleEditorElementType { - COPY("Copy", ActionValidator.getInstance(), CopyActionTranslator.getInstance()), + COPY("Copy", CopyActionValidator.getInstance(), CopyActionTranslator.getInstance()), CONCAT("Concat", ConcatActionValidator.getInstance(), CopyActionTranslator.getInstance()), MAP("Map", MapActionValidator.getInstance(), MapActionTranslator.getInstance()), - REGEX("Regex", ActionValidator.getInstance(), RegexActionTranslator.getInstance()), + REGEX("Regex", CopyActionValidator.getInstance(), RegexActionTranslator.getInstance()), DATE_FORMATTER("DateFormatter", DateFormatterValidator.getInstance(), DateFormatterTranslator.getInstance()), + //1806 US390049 additional hp processors support + CLEAR("Clear", ClearActionValidator.getInstance(), ClearActionTranslator.getInstance()), + REPLACE_TEXT("ReplaceText", ReplaceActionValidator.getInstance(), ReplaceActionTranslator.getInstance()), + LOG_EVENT("LogEvent", LogEventValidator.getInstance(), LogEventTranslator.getInstance()), + LOG_TEXT("LogText", LogTextValidator.getInstance(), LogTextTranslator.getInstance()), + CONDITION("Condition", ConditionValidator.getInstance(), ConditionTranslator.getInstance()), FIELD_CONDITION("FieldCondition", ConditionValidator.getInstance(), FieldConditionTranslator.getInstance()), CONDITION_GROUP("ConditionGroup", ConditionGroupValidator.getInstance(), ConditionGroupTranslator.getInstance()), + RULE("Rule", RuleValidator.getInstance(), RuleTranslator.getInstance()), MAPPING_RULES("MappingRules", null, MappingRulesTranslator.getInstance()); diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/impl/RulesBusinessLogic.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/impl/RulesBusinessLogic.java index 849ad42..5270a18 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/impl/RulesBusinessLogic.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/impl/RulesBusinessLogic.java @@ -31,8 +31,9 @@ public class RulesBusinessLogic { public List<ServiceException> validateRule(Rule rule) { List<ResponseFormat> errors = new ArrayList<>(); - if(ruleValidator.validate(rule, errors)) + if(ruleValidator.validate(rule, errors)) { detectAndResolveActionDependencies(rule, errors); + } return errors.stream().map(r -> r.getRequestError().getServiceException()).collect(Collectors.toList()); } @@ -49,8 +50,9 @@ public class RulesBusinessLogic { public boolean addOrEditRule(MappingRules rules, Rule rule) { // in case the rule id is passed but the rule doesn't exist on the mapping rule file: - if(StringUtils.isNotBlank(rule.getUid()) && !rules.ruleExists(rule)) + if(StringUtils.isNotBlank(rule.getUid()) && !rules.ruleExists(rule)) { return false; + } rules.addOrReplaceRule(rule); return true; } @@ -72,8 +74,9 @@ public class RulesBusinessLogic { List<T> resolvable = dependentItems.stream() .filter(i -> !dependencyDetector.apply(i, dependentItems)) .collect(Collectors.toList()); - if(CollectionUtils.isEmpty(resolvable)) + if(CollectionUtils.isEmpty(resolvable)) { break; + } dependentItems.removeAll(resolvable); } return dependentItems; @@ -98,7 +101,7 @@ public class RulesBusinessLogic { if(!CollectionUtils.isEmpty(dependentActions)) { List<BaseAction> nonResolvable = detectCircularDependenciesByDependencyDefinition(dependentActions, BaseAction::hasDependencies); if (!CollectionUtils.isEmpty(nonResolvable)) { - errors.add(ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.ACTION_DEPENDENCY, null, nonResolvable.stream().map(BaseAction::getTarget).collect(Collectors.joining(", ")))); + errors.add(ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.ACTION_DEPENDENCY, null, nonResolvable.stream().map(BaseAction::strippedTarget).collect(Collectors.joining(", ")))); return; } List<BaseAction> actions = reorderItemsByDependencyDefinition(rule.getActions(), BaseAction::referencesTarget); @@ -128,14 +131,15 @@ public class RulesBusinessLogic { List<BaseAction> allActions = dependentRules.stream().map(Rule::getActions).flatMap(List::stream).collect(Collectors.toList()); // option 1: circular dependency between actions List<BaseAction> nonResolvable = detectCircularDependenciesByDependencyDefinition(allActions, BaseAction::hasDependencies); - if(CollectionUtils.isEmpty(nonResolvable)) + if(CollectionUtils.isEmpty(nonResolvable)) { // option 2: circular dependency between rules - collect dependent actions and condition dependencies nonResolvable = dependentRules.stream() .map(r -> r.findDependencies(dependentRules)) .flatMap(List::stream) .collect(Collectors.toList()); + } return nonResolvable.stream() - .map(BaseAction::getTarget) + .map(BaseAction::strippedTarget) .collect(Collectors.joining(", ")); } diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/ActionTranslator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/ActionTranslator.java new file mode 100644 index 0000000..0ad33ce --- /dev/null +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/ActionTranslator.java @@ -0,0 +1,15 @@ +package org.onap.sdc.dcae.rule.editor.translators; + +import org.onap.sdc.common.onaplog.Enums.LogLevel; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.BaseAction; + +import java.util.List; + +abstract class ActionTranslator<A extends BaseAction> implements IRuleElementTranslator<A> { + + boolean addToHpJsonProcessors(A action, List<Object> processors, boolean asNewProcessor){ + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Translating {} action", action.getActionType()); + processors.add(translateToHpJson(action)); + return true; + } +} diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/ClearActionTranslator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/ClearActionTranslator.java new file mode 100644 index 0000000..31a3fdc --- /dev/null +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/ClearActionTranslator.java @@ -0,0 +1,30 @@ +package org.onap.sdc.dcae.rule.editor.translators; + +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.UnaryFieldAction; + +import java.util.List; + +public class ClearActionTranslator extends ActionTranslator<UnaryFieldAction> { + + private static ClearActionTranslator clearActionTranslator = new ClearActionTranslator(); + + public static ClearActionTranslator getInstance() { + return clearActionTranslator; + } + + private ClearActionTranslator(){} + + public Object translateToHpJson(UnaryFieldAction action) { + return new ClearActionTranslation(action); + } + + + private class ClearActionTranslation extends ProcessorTranslation { + private List<String> fields; + + ClearActionTranslation(UnaryFieldAction action) { + clazz = "Clear"; + fields = action.getFromValues(); + } + } +} diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/ConditionGroupTranslator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/ConditionGroupTranslator.java index 093c239..86f55c9 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/ConditionGroupTranslator.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/ConditionGroupTranslator.java @@ -19,7 +19,7 @@ public class ConditionGroupTranslator implements IRuleElementTranslator<Conditio private ConditionGroupTranslator(){} - public Translation translateToHpJson(ConditionGroup conditionGroup) { + public Object translateToHpJson(ConditionGroup conditionGroup) { String clazz = ConditionTypeEnum.getTypeByName(conditionGroup.getType()).getFilterClass(); FiltersTranslation translation = new FiltersTranslation(clazz, conditionGroup.getChildren().stream() .map(this::getTranslation) @@ -34,12 +34,12 @@ public class ConditionGroupTranslator implements IRuleElementTranslator<Conditio ValidationUtils.validateNotEmpty(OperatorTypeEnum.getTypeByName(((Condition)condition).getOperator()).getModifiedType()) ? FieldConditionTranslator.getInstance() : ConditionTranslator.getInstance(); } - private Translation getTranslation(BaseCondition condition) { + private Object getTranslation(BaseCondition condition) { return getConditionTranslator(condition).translateToHpJson(condition); } private void flattenNestedFilters(FiltersTranslation filtersTranslation, String clazz) { - Map<Boolean, List<Translation>> partitioned = filtersTranslation.filters.stream().collect(Collectors.partitioningBy(f -> clazz.equals(((ProcessorTranslation) f).clazz))); + Map<Boolean, List<Object>> partitioned = filtersTranslation.filters.stream().collect(Collectors.partitioningBy(f -> clazz.equals(((ProcessorTranslation) f).clazz))); filtersTranslation.filters.removeAll(partitioned.get(Boolean.TRUE)); filtersTranslation.filters.addAll(partitioned.get(Boolean.TRUE).stream().map(f -> ((FiltersTranslation) f).filters).flatMap(List::stream).collect(Collectors.toList())); } diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/ConditionTranslator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/ConditionTranslator.java index f93101b..aa30fc3 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/ConditionTranslator.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/ConditionTranslator.java @@ -31,7 +31,7 @@ public class ConditionTranslator implements IRuleElementTranslator<Condition> { } } - public Translation translateToHpJson(Condition condition) { + public Object translateToHpJson(Condition condition) { return 1 == condition.getRight().size() ? new StringFilterTranslation(condition) : new FiltersTranslation(ConditionTypeEnum.ANY.getFilterClass(), condition.getRight().stream() .map(r -> new StringFilterTranslation(condition, r)).collect(Collectors.toList())); } diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/CopyActionTranslator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/CopyActionTranslator.java index 9d02c8e..4226eba 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/CopyActionTranslator.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/CopyActionTranslator.java @@ -1,15 +1,13 @@ package org.onap.sdc.dcae.rule.editor.translators; import org.onap.sdc.common.onaplog.Enums.LogLevel; -import org.onap.sdc.dcae.composition.restmodels.ruleeditor.BaseAction; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.BaseCopyAction; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.onap.sdc.dcae.composition.restmodels.ruleeditor.BaseAction; - -public class CopyActionTranslator<A extends BaseAction> implements IRuleElementTranslator<A>{ +public class CopyActionTranslator extends ActionTranslator<BaseCopyAction> { private static CopyActionTranslator copyActionTranslator = new CopyActionTranslator(); @@ -19,20 +17,19 @@ public class CopyActionTranslator<A extends BaseAction> implements IRuleElementT CopyActionTranslator(){} - public Translation translateToHpJson(A action) { + public Object translateToHpJson(BaseCopyAction action) { return new CopyActionSetTranslation(action.getTarget(), action.getFromValue()); } - void addToHpJsonProcessors(A action, List<Translation> processors) { - processors.add(translateToHpJson(action)); - } - - public boolean addToHpJsonProcessors(A action, List<Translation> processors, boolean asNewProcessor) { + @Override + public boolean addToHpJsonProcessors(BaseCopyAction action, List<Object> processors, boolean asNewProcessor) { debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Translating {} action. New Processor: {}", action.getActionType(), asNewProcessor); - if(asNewProcessor) - addToHpJsonProcessors(action, processors); - else - ((CopyActionSetTranslation) processors.get(processors.size()-1)).updates.put(action.getTarget(), action.getFromValue()); + if(asNewProcessor) { + processors.add(translateToHpJson(action)); + } + else { + ((CopyActionSetTranslation) processors.get(processors.size() - 1)).updates.put(action.getTarget(), action.getFromValue()); + } return false; } diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/DateFormatterTranslator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/DateFormatterTranslator.java index 89f0def..449dbf0 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/DateFormatterTranslator.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/DateFormatterTranslator.java @@ -1,11 +1,8 @@ package org.onap.sdc.dcae.rule.editor.translators; -import org.onap.sdc.common.onaplog.Enums.LogLevel; -import java.util.List; - import org.onap.sdc.dcae.composition.restmodels.ruleeditor.DateFormatterAction; -public class DateFormatterTranslator extends CopyActionTranslator<DateFormatterAction> { +public class DateFormatterTranslator extends ActionTranslator<DateFormatterAction> { private static DateFormatterTranslator dateFormatterTranslator = new DateFormatterTranslator(); @@ -34,15 +31,7 @@ public class DateFormatterTranslator extends CopyActionTranslator<DateFormatterA } } - @Override - public boolean addToHpJsonProcessors(DateFormatterAction action, List<Translation> processors, boolean asNewProcessor) { - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Translating date formatter action"); - addToHpJsonProcessors(action, processors); - return true; - } - - @Override - public Translation translateToHpJson(DateFormatterAction action){ + public Object translateToHpJson(DateFormatterAction action){ return new DateFormatterTranslation(action); } diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/FieldConditionTranslator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/FieldConditionTranslator.java index ef2949e..dddbc89 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/FieldConditionTranslator.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/FieldConditionTranslator.java @@ -37,7 +37,7 @@ public class FieldConditionTranslator implements IRuleElementTranslator<Conditio } } - public Translation translateToHpJson(Condition condition) { + public Object translateToHpJson(Condition condition) { return 1 == condition.getRight().size() ? new FieldFilterTranslation(condition) : new MultiFieldFilterTranslation(condition); } } diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/IRuleElementTranslator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/IRuleElementTranslator.java index dac818d..97269ef 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/IRuleElementTranslator.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/IRuleElementTranslator.java @@ -12,30 +12,28 @@ public interface IRuleElementTranslator<T> { OnapLoggerError errLogger = OnapLoggerError.getInstance(); OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance(); - Translation translateToHpJson(T element); + Object translateToHpJson(T element); - abstract class Translation { - } - class ProcessorTranslation extends Translation { + class ProcessorTranslation { @SerializedName("class") protected String clazz; } class FiltersTranslation extends ProcessorTranslation { - protected List<Translation> filters; + protected List<Object> filters; - protected FiltersTranslation(String clazz, List<Translation> filters) { + protected FiltersTranslation(String clazz, List<Object> filters) { this.clazz = clazz; this.filters = filters; } } - class RuleTranslation extends Translation { + class RuleTranslation { protected String phase; - protected Translation filter; - protected List<Translation> processors = new ArrayList<>(); + protected Object filter; + protected List<Object> processors = new ArrayList<>(); } class RunPhaseProcessorsTranslation extends ProcessorTranslation { diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/LogEventTranslator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/LogEventTranslator.java new file mode 100644 index 0000000..8c29070 --- /dev/null +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/LogEventTranslator.java @@ -0,0 +1,28 @@ +package org.onap.sdc.dcae.rule.editor.translators; + +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.LogEventAction; + +public class LogEventTranslator extends ActionTranslator<LogEventAction> { + + private static LogEventTranslator logEventTranslator = new LogEventTranslator(); + + public static LogEventTranslator getInstance() { + return logEventTranslator; + } + + private LogEventTranslator(){} + + public Object translateToHpJson(LogEventAction action) { + return new LogEventTranslation(action); + } + + + private class LogEventTranslation extends ProcessorTranslation { + String title; + + LogEventTranslation(LogEventAction action) { + clazz = "LogEvent"; + title = action.getTitle(); + } + } +} diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/LogTextTranslator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/LogTextTranslator.java new file mode 100644 index 0000000..a9ed5bb --- /dev/null +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/LogTextTranslator.java @@ -0,0 +1,33 @@ +package org.onap.sdc.dcae.rule.editor.translators; + +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.LogTextAction; + +public class LogTextTranslator extends ActionTranslator<LogTextAction> { + + private static LogTextTranslator logTextTranslator = new LogTextTranslator(); + + public static LogTextTranslator getInstance() { + return logTextTranslator; + } + + private LogTextTranslator(){} + + public Object translateToHpJson(LogTextAction action) { + return new LogTextTranslation(action); + } + + + class LogTextTranslation extends ProcessorTranslation { + private String logLevel; + private String logName; + private String logText; + + private LogTextTranslation(LogTextAction action) { + clazz = "LogText"; + logLevel = action.getLevel(); + logName = action.getName(); + logText = action.getText(); + } + } + +} diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/MapActionTranslator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/MapActionTranslator.java index 922312e..d493abb 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/MapActionTranslator.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/MapActionTranslator.java @@ -2,14 +2,11 @@ package org.onap.sdc.dcae.rule.editor.translators; import com.google.gson.annotations.SerializedName; -import org.onap.sdc.common.onaplog.Enums.LogLevel; - -import java.util.List; import java.util.Map; import org.onap.sdc.dcae.composition.restmodels.ruleeditor.MapAction; -public class MapActionTranslator extends CopyActionTranslator<MapAction> { +public class MapActionTranslator extends ActionTranslator<MapAction> { private static MapActionTranslator mapActionTranslator = new MapActionTranslator(); @@ -36,15 +33,8 @@ public class MapActionTranslator extends CopyActionTranslator<MapAction> { } } - @Override - public Translation translateToHpJson(MapAction action) { + public Object translateToHpJson(MapAction action) { return new MapActionTranslation(action); } - @Override - public boolean addToHpJsonProcessors(MapAction action, List<Translation> processors, boolean asNewProcessor) { - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Translating map action"); - addToHpJsonProcessors(action, processors); - return true; - } } diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/MappingRulesTranslator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/MappingRulesTranslator.java index 0164446..91a1ab0 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/MappingRulesTranslator.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/MappingRulesTranslator.java @@ -18,19 +18,19 @@ public class MappingRulesTranslator implements IRuleElementTranslator<MappingRul private RuleTranslator ruleTranslator = RuleTranslator.getInstance(); - public Translation translateToHpJson(MappingRules mappingRules) { + public Object translateToHpJson(MappingRules mappingRules) { return new MappingRulesTranslation(mappingRules); } - public Translation translateToHpJson(MappingRules mappingRules, String entryPointPhaseName, String lastPhaseName, String runPhase) { + public Object translateToHpJson(MappingRules mappingRules, String entryPointPhaseName, String lastPhaseName, String runPhase) { // 1806 US349308 assign Vfcmt name as rule phaseName mappingRules.getRules().forEach((k,v) -> v.setPhase(runPhase)); return new MappingRulesTranslation(mappingRules, entryPointPhaseName, lastPhaseName, runPhase); } - private class MappingRulesTranslation extends Translation { + private class MappingRulesTranslation { - private List<Translation> processing; + private List<Object> processing; private MappingRulesTranslation(MappingRules mappingRules) { processing = mappingRules.getRules().values().stream().map(ruleTranslator::translateToHpJson).collect(Collectors.toList()); @@ -49,8 +49,9 @@ public class MappingRulesTranslator implements IRuleElementTranslator<MappingRul private RunPhaseRuleTranslation(String phaseName, String runPhase) { phase = phaseName; - if ("snmp_map".equals(phaseName)) + if("snmp_map".equals(phaseName)) { processors.add(new SnmpConvertor()); + } processors.add(new RunPhaseProcessorsTranslation(runPhase)); } } diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/RegexActionTranslator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/RegexActionTranslator.java index c49a04e..85fdf1d 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/RegexActionTranslator.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/RegexActionTranslator.java @@ -1,11 +1,10 @@ package org.onap.sdc.dcae.rule.editor.translators; import org.onap.sdc.common.onaplog.Enums.LogLevel; -import java.util.List; -import org.onap.sdc.dcae.composition.restmodels.ruleeditor.BaseAction; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.BaseCopyAction; -public class RegexActionTranslator extends CopyActionTranslator<BaseAction> { +public class RegexActionTranslator extends ActionTranslator<BaseCopyAction> { private static RegexActionTranslator regexActionTranslator = new RegexActionTranslator(); @@ -21,7 +20,7 @@ public class RegexActionTranslator extends CopyActionTranslator<BaseAction> { private String field; private String value; - private RegexCopyActionTranslation(BaseAction action) { + private RegexCopyActionTranslation(BaseCopyAction action) { clazz = "ExtractText"; regex = action.getRegexValue(); field = action.getTarget(); @@ -29,15 +28,9 @@ public class RegexActionTranslator extends CopyActionTranslator<BaseAction> { } } - @Override - public boolean addToHpJsonProcessors(BaseAction action, List<Translation> processors, boolean asNewProcessor) { - debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Translating copy action as regex action"); - addToHpJsonProcessors(action, processors); - return true; - } - @Override - public Translation translateToHpJson(BaseAction action) { + public Object translateToHpJson(BaseCopyAction action) { + debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Translating copy action as regex action"); return new RegexCopyActionTranslation(action); } diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/ReplaceActionTranslator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/ReplaceActionTranslator.java new file mode 100644 index 0000000..3069df3 --- /dev/null +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/ReplaceActionTranslator.java @@ -0,0 +1,33 @@ +package org.onap.sdc.dcae.rule.editor.translators; + +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.ReplaceTextAction; + +public class ReplaceActionTranslator extends ActionTranslator<ReplaceTextAction> { + + private static ReplaceActionTranslator replaceActionTranslator = new ReplaceActionTranslator(); + + public static ReplaceActionTranslator getInstance() { + return replaceActionTranslator; + } + + private ReplaceActionTranslator(){} + + public Object translateToHpJson(ReplaceTextAction action) { + return new ReplaceActionTranslation(action); + } + + + private class ReplaceActionTranslation extends ProcessorTranslation { + private String field; + private String find; + private String replace; + + ReplaceActionTranslation(ReplaceTextAction action) { + clazz = "ReplaceText"; + field = action.getFromValue(); + find = action.getFind(); + replace = action.getReplace(); + } + } + +} diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/RuleTranslator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/RuleTranslator.java index f7dea47..b98050d 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/RuleTranslator.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/translators/RuleTranslator.java @@ -30,9 +30,9 @@ public class RuleTranslator implements IRuleElementTranslator<Rule> { } } - public Translation translateToHpJson(Rule rule) { + public Object translateToHpJson(Rule rule) { debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Start translating rule {}", rule.getUid()); - Translation translation = new ActionRuleTranslation(rule); + Object translation = new ActionRuleTranslation(rule); debugLogger.log(LogLevel.DEBUG, this.getClass().getName(), "Finished translation for rule {}. Result: {}", rule.getUid(), new Gson().toJson(translation)); return translation; } @@ -42,10 +42,11 @@ public class RuleTranslator implements IRuleElementTranslator<Rule> { ValidationUtils.validateNotEmpty(OperatorTypeEnum.getTypeByName(((Condition)condition).getOperator()).getModifiedType()) ? FieldConditionTranslator.getInstance() : ConditionTranslator.getInstance(); } - private CopyActionTranslator getActionTranslator(BaseAction action) { + private ActionTranslator getActionTranslator(BaseAction action) { ActionTypeEnum type = ActionTypeEnum.getTypeByName(action.getActionType()); - if(ActionTypeEnum.COPY == type && ValidationUtils.validateNotEmpty(action.getRegexValue())) + if(ActionTypeEnum.COPY == type && ValidationUtils.validateNotEmpty(((BaseCopyAction)action).getRegexValue())) { return RegexActionTranslator.getInstance(); - return (CopyActionTranslator)RuleEditorElementType.getElementTypeByName(type.getType()).getTranslator(); + } + return (ActionTranslator) RuleEditorElementType.getElementTypeByName(type.getType()).getTranslator(); } }
\ No newline at end of file diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/ClearActionValidator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/ClearActionValidator.java new file mode 100644 index 0000000..8be49b5 --- /dev/null +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/ClearActionValidator.java @@ -0,0 +1,27 @@ +package org.onap.sdc.dcae.rule.editor.validators; + +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.UnaryFieldAction; +import org.onap.sdc.dcae.errormng.ActionStatus; +import org.onap.sdc.dcae.errormng.ErrConfMgr; +import org.onap.sdc.dcae.errormng.ResponseFormat; + +import java.util.List; + +public class ClearActionValidator implements IRuleElementValidator<UnaryFieldAction> { + + private static ClearActionValidator clearActionValidator = new ClearActionValidator(); + + public static ClearActionValidator getInstance() { + return clearActionValidator; + } + + private ClearActionValidator(){} + + public boolean validate(UnaryFieldAction action, List<ResponseFormat> errors) { + if(action.getFromValues().isEmpty()) { + errors.add(ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.MISSING_ACTION_FIELD, null, "from", action.getActionType(), action.strippedTarget())); + return false; + } + return true; + } +} diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/ConcatActionValidator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/ConcatActionValidator.java index 965c898..956ac51 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/ConcatActionValidator.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/ConcatActionValidator.java @@ -1,6 +1,6 @@ package org.onap.sdc.dcae.rule.editor.validators; -import org.onap.sdc.dcae.composition.restmodels.ruleeditor.BaseAction; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.BaseCopyAction; import org.onap.sdc.dcae.errormng.ActionStatus; import org.onap.sdc.dcae.errormng.ErrConfMgr; import org.onap.sdc.dcae.errormng.ResponseFormat; @@ -8,7 +8,7 @@ import org.onap.sdc.dcae.rule.editor.utils.ValidationUtils; import java.util.List; -public class ConcatActionValidator extends ActionValidator<BaseAction> { +public class ConcatActionValidator extends CopyActionValidator<BaseCopyAction> { private static ConcatActionValidator concatActionValidator = new ConcatActionValidator(); @@ -19,7 +19,7 @@ public class ConcatActionValidator extends ActionValidator<BaseAction> { private ConcatActionValidator(){} @Override - protected boolean validateFromValue(BaseAction action, List<ResponseFormat> errors) { + protected boolean validateFromValue(BaseCopyAction action, List<ResponseFormat> errors) { if(!ValidationUtils.validateNotEmpty(action.getFromValue()) || 2 > action.getFromValues().size()) { errors.add(ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.MISSING_CONCAT_VALUE, null, action.getTarget())); return false; diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/ActionValidator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/CopyActionValidator.java index 3eb0eb5..74102a6 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/ActionValidator.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/CopyActionValidator.java @@ -1,6 +1,6 @@ package org.onap.sdc.dcae.rule.editor.validators; -import org.onap.sdc.dcae.composition.restmodels.ruleeditor.BaseAction; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.BaseCopyAction; import org.onap.sdc.dcae.errormng.ActionStatus; import org.onap.sdc.dcae.errormng.ErrConfMgr; import org.onap.sdc.dcae.errormng.ResponseFormat; @@ -8,15 +8,15 @@ import org.onap.sdc.dcae.rule.editor.utils.ValidationUtils; import java.util.List; -public class ActionValidator<A extends BaseAction> implements IRuleElementValidator<A> { +public class CopyActionValidator<A extends BaseCopyAction> implements IRuleElementValidator<A> { - private static ActionValidator actionValidator = new ActionValidator(); + private static CopyActionValidator copyActionValidator = new CopyActionValidator(); - public static ActionValidator getInstance() { - return actionValidator; + public static CopyActionValidator getInstance() { + return copyActionValidator; } - ActionValidator(){} + CopyActionValidator(){} public boolean validate(A action, List<ResponseFormat> errors) { diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/DateFormatterValidator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/DateFormatterValidator.java index d5ec0fc..19af40c 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/DateFormatterValidator.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/DateFormatterValidator.java @@ -8,7 +8,7 @@ import org.onap.sdc.dcae.rule.editor.utils.ValidationUtils; import java.util.List; -public class DateFormatterValidator extends ActionValidator<DateFormatterAction> { +public class DateFormatterValidator extends CopyActionValidator<DateFormatterAction> { private static DateFormatterValidator dateFormatterValidator = new DateFormatterValidator(); public static DateFormatterValidator getInstance() { diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/IRuleElementValidator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/IRuleElementValidator.java index dd1eaf4..cdcf5b2 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/IRuleElementValidator.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/IRuleElementValidator.java @@ -1,9 +1,13 @@ package org.onap.sdc.dcae.rule.editor.validators; +import org.onap.sdc.common.onaplog.OnapLoggerError; import org.onap.sdc.dcae.errormng.ResponseFormat; import java.util.List; public interface IRuleElementValidator <T> { + + OnapLoggerError errLogger = OnapLoggerError.getInstance(); + boolean validate(T element, List<ResponseFormat> errors); } diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/LogEventValidator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/LogEventValidator.java new file mode 100644 index 0000000..1bbf07a --- /dev/null +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/LogEventValidator.java @@ -0,0 +1,28 @@ +package org.onap.sdc.dcae.rule.editor.validators; + +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.LogEventAction; +import org.onap.sdc.dcae.errormng.ActionStatus; +import org.onap.sdc.dcae.errormng.ErrConfMgr; +import org.onap.sdc.dcae.errormng.ResponseFormat; +import org.onap.sdc.dcae.rule.editor.utils.ValidationUtils; + +import java.util.List; + +public class LogEventValidator implements IRuleElementValidator<LogEventAction> { + + private static LogEventValidator logEventValidator = new LogEventValidator(); + + public static LogEventValidator getInstance() { + return logEventValidator; + } + + LogEventValidator(){} + + public boolean validate(LogEventAction action, List<ResponseFormat> errors) { + if(!ValidationUtils.validateNotEmpty(action.getTitle())){ + errors.add(ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.MISSING_ACTION_FIELD, null, "title", action.getActionType(), action.strippedTarget())); + return false; + } + return true; + } +} diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/LogTextValidator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/LogTextValidator.java new file mode 100644 index 0000000..711692f --- /dev/null +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/LogTextValidator.java @@ -0,0 +1,28 @@ +package org.onap.sdc.dcae.rule.editor.validators; + +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.LogTextAction; +import org.onap.sdc.dcae.errormng.ActionStatus; +import org.onap.sdc.dcae.errormng.ErrConfMgr; +import org.onap.sdc.dcae.errormng.ResponseFormat; +import org.onap.sdc.dcae.rule.editor.utils.ValidationUtils; + +import java.util.List; + +public class LogTextValidator implements IRuleElementValidator<LogTextAction> { + + private static LogTextValidator logTextValidator = new LogTextValidator(); + + public static LogTextValidator getInstance() { + return logTextValidator; + } + + LogTextValidator(){} + + public boolean validate(LogTextAction action, List<ResponseFormat> errors) { + if(!ValidationUtils.validateNotEmpty(action.getText())){ + errors.add(ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.MISSING_ACTION_FIELD, null, "text", action.getActionType(), action.strippedTarget())); + return false; + } + return true; + } +} diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/MapActionValidator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/MapActionValidator.java index 8cbcaa8..130e428 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/MapActionValidator.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/MapActionValidator.java @@ -1,5 +1,6 @@ package org.onap.sdc.dcae.rule.editor.validators; +import org.onap.sdc.common.onaplog.Enums.LogLevel; import org.onap.sdc.dcae.composition.restmodels.ruleeditor.MapAction; import org.onap.sdc.dcae.errormng.ActionStatus; import org.onap.sdc.dcae.errormng.ErrConfMgr; @@ -9,7 +10,7 @@ import org.springframework.util.CollectionUtils; import java.util.List; -public class MapActionValidator extends ActionValidator<MapAction> { +public class MapActionValidator extends CopyActionValidator<MapAction> { private static MapActionValidator mapActionValidator = new MapActionValidator(); @@ -37,6 +38,7 @@ public class MapActionValidator extends ActionValidator<MapAction> { } } catch (IllegalStateException err) { valid = false; + errLogger.log(LogLevel.ERROR, this.getClass().getName(), "Map validation error: {}", err); errors.add(ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.DUPLICATE_KEY, null)); } } diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/ReplaceActionValidator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/ReplaceActionValidator.java new file mode 100644 index 0000000..d9aea82 --- /dev/null +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/ReplaceActionValidator.java @@ -0,0 +1,37 @@ +package org.onap.sdc.dcae.rule.editor.validators; + +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.ReplaceTextAction; +import org.onap.sdc.dcae.errormng.ActionStatus; +import org.onap.sdc.dcae.errormng.ErrConfMgr; +import org.onap.sdc.dcae.errormng.ResponseFormat; +import org.onap.sdc.dcae.rule.editor.utils.ValidationUtils; + +import java.util.List; + +public class ReplaceActionValidator implements IRuleElementValidator<ReplaceTextAction> { + + private static ReplaceActionValidator replaceActionValidator = new ReplaceActionValidator(); + + public static ReplaceActionValidator getInstance() { + return replaceActionValidator; + } + + private ReplaceActionValidator(){} + + public boolean validate(ReplaceTextAction action, List<ResponseFormat> errors) { + boolean valid = true; + if(!ValidationUtils.validateNotEmpty(action.getFromValue())) { + valid = false; + errors.add(ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.MISSING_ACTION_FIELD, null, "from", action.getActionType(), action.strippedTarget())); + } + if(!ValidationUtils.validateNotEmpty(action.getFind())) { + valid = false; + errors.add(ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.MISSING_ACTION_FIELD, null, "find", action.getActionType(), action.strippedTarget())); + } + if(!ValidationUtils.validateNotEmpty(action.getReplace())) { + valid = false; + errors.add(ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.MISSING_ACTION_FIELD, null, "replace", action.getActionType(), action.strippedTarget())); + } + return valid; + } +} diff --git a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/RuleValidator.java b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/RuleValidator.java index 371d1e9..e03ca8a 100644 --- a/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/RuleValidator.java +++ b/dcaedt_be/src/main/java/org/onap/sdc/dcae/rule/editor/validators/RuleValidator.java @@ -1,13 +1,9 @@ package org.onap.sdc.dcae.rule.editor.validators; -import org.onap.sdc.dcae.composition.restmodels.ruleeditor.ActionTypeEnum; -import org.onap.sdc.dcae.composition.restmodels.ruleeditor.BaseAction; -import org.onap.sdc.dcae.composition.restmodels.ruleeditor.BaseCondition; -import org.onap.sdc.dcae.composition.restmodels.ruleeditor.Rule; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.*; import org.onap.sdc.dcae.errormng.ActionStatus; import org.onap.sdc.dcae.errormng.ErrConfMgr; import org.onap.sdc.dcae.errormng.ResponseFormat; -import org.onap.sdc.dcae.errormng.ServiceException; import org.onap.sdc.dcae.rule.editor.enums.RuleEditorElementType; import org.onap.sdc.dcae.rule.editor.utils.ValidationUtils; import org.springframework.util.CollectionUtils; diff --git a/dcaedt_be/src/main/webapp/WEB-INF/config/dcae-be/application.properties b/dcaedt_be/src/main/webapp/WEB-INF/config/dcae-be/application.properties index d5333c4..b833be9 100644 --- a/dcaedt_be/src/main/webapp/WEB-INF/config/dcae-be/application.properties +++ b/dcaedt_be/src/main/webapp/WEB-INF/config/dcae-be/application.properties @@ -6,6 +6,7 @@ scheduled.timer.value=5000 asdc_catalog_url=asdc #uri=https://dcaeDesigner:Aa123456@zldcrdm2sdc2abe01.3f1a87.rdm2.tci.att.com:8443#demo uri=https://dcaeDesigner:Aa123456@zldcrdm2sdc4cbe01.3f1a87.rdm2.tci.att.com:8443#demo +#uri=https://dcaeDesigner:Aa123456@zldcrdm2sdc2dbe01.3f1a87.rdm2.tci.att.com:8443#demo toscalab_url=http://localhost:8080/ blueprinter.uri=${toscalab_url}translate blueprinter.hcuri=${toscalab_url}healthcheck @@ -19,4 +20,21 @@ compositionConfig.flowTypes={"Syslog":{"entryPointPhaseName":"syslog_map","lastP "Guest OS":{"entryPointPhaseName":"guest_os_map","lastPhaseName":"map_publish"},\ "Status Poller":{"entryPointPhaseName":"status_poller_map","lastPhaseName":"map_publish"},\ "SNMP Polling":{"entryPointPhaseName":"snmp_polling_map","lastPhaseName":"map_publish"},\ - "TCA Hi Lo":{"entryPointPhaseName":"tca_hi_lo_map","lastPhaseName":"map_publish"}} + "TCA Hi Lo":{"entryPointPhaseName":"tca_hi_lo_map","lastPhaseName":"map_publish"},\ + "Syslog Collector":{"entryPointPhaseName":"syslog_map","lastPhaseName":"syslog_publish"},\ + "Syslog MSEA":{"entryPointPhaseName":"syslog_map","lastPhaseName":"syslog_publish"},\ + "Status Poller Collector":{"entryPointPhaseName":"status_poller_map","lastPhaseName":"status_poller_publish"},\ + "Status Poller MSE":{"entryPointPhaseName":"snmp_map","lastPhaseName":"snmp_publish"},\ + "FOI Collector":{"entryPointPhaseName":"pmossFoiPhase","lastPhaseName":"foiEventToDmaapPhase"},\ + "Docker Map":{"entryPointPhaseName":"docker_map","lastPhaseName":"docker_publish"},\ + "SNMP MSE":{"entryPointPhaseName":"snmp_map","lastPhaseName":"snmp_publish"},\ + "SAM Collector":{"entryPointPhaseName":"sam_collector_map","lastPhaseName":"sam_collector_publish"},\ + "Docker MSE":{"entryPointPhaseName":"docker_map","lastPhaseName":"docker_publish"},\ + "SNMP PM Poller":{"entryPointPhaseName":"docker_map","lastPhaseName":"docker_publilsh"},\ + "Discovery and MIB Poller":{"entryPointPhaseName":"snmp_pm_map","lastPhaseName":"snmp_pm_publish"},\ + "Nagios docker MSE":{"entryPointPhaseName":"docker_map","lastPhaseName":"docker_publish"},\ + "VES Fault":{"entryPointPhaseName":"ves_fault_map","lastPhaseName":"ves_fault_publish"},\ + "VES Heartbeat":{"entryPointPhaseName":"ves_heartbeat_map","lastPhaseName":"ves_heartbeat_publish"},\ + "VES Measurement":{"entryPointPhaseName":"ves_measurement_map","lastPhaseName":"ves_measurement_publish"},\ + "VES Syslog":{"entryPointPhaseName":"ves_syslog_map","lastPhaseName":"ves_syslog_publish"}} + diff --git a/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/BlueprintBusinessLogicTest.java b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/BlueprintBusinessLogicTest.java new file mode 100644 index 0000000..a00130f --- /dev/null +++ b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/BlueprintBusinessLogicTest.java @@ -0,0 +1,69 @@ +package org.onap.sdc.dcae.composition.impl; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.sdc.dcae.client.ISdcClient; +import org.onap.sdc.dcae.composition.restmodels.sdc.Artifact; +import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceDetailed; +import org.onap.sdc.dcae.errormng.ErrorConfigurationLoader; +import org.springframework.http.ResponseEntity; + +import java.util.ArrayList; + +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; +import static org.onap.sdc.dcae.composition.util.DcaeBeConstants.Composition.fileNames.COMPOSITION_YML; + +@RunWith(MockitoJUnitRunner.class) +public class BlueprintBusinessLogicTest { + + private static final String USER_ID = "UserId"; + private static final String CONTEXT = "Context"; + private static final String VFCMT_UUID = "VfcmtUuid"; + private static final String SERVICE_UUID = "ServiceUuid"; + private static final String VFI_NAME = "VfiName"; + private static final String FLOW_TYPE = "FlowType"; + private static final String REQUEST_ID = "RequestId"; + + @InjectMocks + BlueprintBusinessLogic classUnderTest; + @Mock + private ISdcClient sdcClientMock; + private ResourceDetailed resourceDetailed; + + @Before + public void setup() { + new ErrorConfigurationLoader(System.getProperty("user.dir")+"/src/main/webapp/WEB-INF"); + + resourceDetailed = new ResourceDetailed(); + resourceDetailed.setUuid(VFCMT_UUID); + classUnderTest.setSdcRestClient(sdcClientMock); + when(sdcClientMock.getResource(eq(VFCMT_UUID), eq(REQUEST_ID))).thenReturn(resourceDetailed); + when(sdcClientMock.getResourceArtifact(eq(VFCMT_UUID), anyString(), anyString())).thenReturn("\"{\\\\\\\"version\\\\\\\":0,\\\\\\\"flowType\\\\\\\":\\\\\\\"templateInfoFlowType\\\\\\\",\\\\\\\"nodes\\\\\\\":[],\\\\\\\"inputs\\\\\\\":[],\\\\\\\"outputs\\\\\\\":[],\\\\\\\"relations\\\\\\\":[]}\\\"\""); + } + + @Test + public void generateAndSaveBlueprint_compositionNotFound() { + ResponseEntity responseEntity = classUnderTest.generateAndSaveBlueprint(USER_ID, CONTEXT, VFCMT_UUID, SERVICE_UUID, VFI_NAME, FLOW_TYPE, REQUEST_ID); + Assert.assertEquals( 404, responseEntity.getStatusCodeValue()); + } + + @Test + public void generateAndSaveBlueprint_toscaFailed() { + Artifact artifact = new Artifact(); + artifact.setArtifactName(COMPOSITION_YML); + artifact.setPayloadData("{\\\"version\\\":0,\\\"flowType\\\":\\\"templateInfoFlowType\\\",\\\"nodes\\\":[],\\\"inputs\\\":[],\\\"outputs\\\":[],\\\"relations\\\":[]}\""); + ArrayList<Artifact> artifacts = new ArrayList<>(); + artifacts.add(artifact); + resourceDetailed.setArtifacts(artifacts); + ResponseEntity responseEntity = classUnderTest.generateAndSaveBlueprint(USER_ID, CONTEXT, VFCMT_UUID, SERVICE_UUID, VFI_NAME, FLOW_TYPE, REQUEST_ID); + Assert.assertEquals( 500, responseEntity.getStatusCodeValue()); + } + +} diff --git a/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/CompositionBusinessLogicTest.java b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/CompositionBusinessLogicTest.java new file mode 100644 index 0000000..d9b65b2 --- /dev/null +++ b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/CompositionBusinessLogicTest.java @@ -0,0 +1,218 @@ +package org.onap.sdc.dcae.composition.impl; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.sdc.dcae.catalog.asdc.ASDCException; +import org.onap.sdc.dcae.client.ISdcClient; +import org.onap.sdc.dcae.composition.restmodels.VfcmtData; +import org.onap.sdc.dcae.composition.restmodels.sdc.*; +import org.onap.sdc.dcae.composition.util.DcaeBeConstants; +import org.onap.sdc.dcae.errormng.ErrorConfigurationLoader; +import org.onap.sdc.dcae.errormng.RequestError; +import org.onap.sdc.dcae.errormng.ServiceException; +import org.onap.sdc.dcae.utils.Normalizers; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.*; + +public class CompositionBusinessLogicTest { + + private ISdcClient sdcClientMock = Mockito.mock(ISdcClient.class); + private ResourceDetailed vfcmt = Mockito.mock(ResourceDetailed.class); + private ServiceDetailed service = Mockito.mock(ServiceDetailed.class); + private CompositionBusinessLogic compositionBusinessLogic = new CompositionBusinessLogic(); + private String justAString = "aStringForAllSeasons"; + + @Before + public void setup(){ + MockitoAnnotations.initMocks(this); + compositionBusinessLogic.setSdcRestClient(sdcClientMock); + new ErrorConfigurationLoader(System.getProperty("user.dir")+"/src/main/webapp/WEB-INF"); + when(vfcmt.getUuid()).thenReturn(justAString); + when(vfcmt.getName()).thenReturn(justAString); + when(vfcmt.getDescription()).thenReturn(justAString); + when(vfcmt.getInvariantUUID()).thenReturn(justAString); + } + + @Test + public void successfulSaveCompositionAndCheckInInitialStateCheckedOut() throws Exception { + emulateListOfArtifactsWithCompositionYml(); + when(sdcClientMock.getResource(anyString(),anyString())).thenReturn(vfcmt); + when(vfcmt.getLifecycleState()).thenReturn("NOT_CERTIFIED_CHECKOUT"); + + compositionBusinessLogic.saveComposition(justAString, justAString, justAString, justAString, false); + + verify(sdcClientMock).getResource(anyString(),anyString()); + verify(sdcClientMock, times(0)).createResourceArtifact(anyString(),anyString(),any(),anyString()); + verify(sdcClientMock).updateResourceArtifact(anyString(), anyString(), any(), anyString()); + verify(sdcClientMock).changeResourceLifecycleState(anyString(),anyString(),anyString(),anyString(),anyString()); + } + + @Test + public void successfulSaveCompositionAndCheckInInitialStateCheckedIn() throws Exception { + emulateListOfArtifactsWithCompositionYml(); + when(sdcClientMock.getResource(anyString(),anyString())).thenReturn(vfcmt); + when(vfcmt.getLifecycleState()).thenReturn("NOT_CERTIFIED_CHECKIN"); + when(sdcClientMock.changeResourceLifecycleState(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(vfcmt); + + compositionBusinessLogic.saveComposition(justAString, justAString, justAString, justAString, false); + + verify(sdcClientMock).getResource(anyString(),anyString()); + verify(sdcClientMock, times(0)).createResourceArtifact(anyString(),anyString(),any(),anyString()); + verify(sdcClientMock).updateResourceArtifact(anyString(), anyString(), any(), anyString()); + verify(sdcClientMock, times(2)).changeResourceLifecycleState(anyString(),anyString(),anyString(),anyString(),anyString()); + } + + @Test + public void saveCompositionCheckInFailureDoRollback() throws Exception { + + emulateListOfArtifactsWithCompositionYml(); + when(sdcClientMock.getResource(anyString(),anyString())).thenReturn(vfcmt); + when(vfcmt.getLifecycleState()).thenReturn("NOT_CERTIFIED_CHECKIN"); + RequestError requestError = new RequestError(); + requestError.setServiceException(new ServiceException("SVC4086", "", null)); + when(sdcClientMock.changeResourceLifecycleState(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(vfcmt).thenThrow(new ASDCException(HttpStatus.FORBIDDEN, requestError)); + + ResponseEntity result = compositionBusinessLogic.saveComposition(justAString, justAString, justAString, justAString, false); + + verify(sdcClientMock).getResource(anyString(),anyString()); + verify(sdcClientMock, times(0)).createResourceArtifact(anyString(),anyString(),any(),anyString()); + verify(sdcClientMock).updateResourceArtifact(anyString(), anyString(), any(), anyString()); + verify(sdcClientMock, times(3)).changeResourceLifecycleState(anyString(),anyString(),anyString(),anyString(),anyString()); + assertEquals(403, result.getStatusCodeValue()); + } + + @Test + public void saveCompositionUpdateArtifactFailureNoRollback() throws Exception { + + emulateListOfArtifactsWithCompositionYml(); + when(sdcClientMock.getResource(anyString(),anyString())).thenReturn(vfcmt); + when(vfcmt.getLifecycleState()).thenReturn("NOT_CERTIFIED_CHECKOUT"); + RequestError requestError = new RequestError(); + requestError.setServiceException(new ServiceException("SVC4127", "", null)); + when(sdcClientMock.updateResourceArtifact(anyString(), anyString(), any(), anyString())).thenThrow(new ASDCException(HttpStatus.BAD_REQUEST, requestError)); + ResponseEntity result = compositionBusinessLogic.saveComposition(justAString, justAString, justAString, justAString, false); + + verify(sdcClientMock).getResource(anyString(),anyString()); + verify(sdcClientMock, times(0)).createResourceArtifact(anyString(),anyString(),any(),anyString()); + verify(sdcClientMock).updateResourceArtifact(anyString(), anyString(), any(), anyString()); + verify(sdcClientMock, times(0)).changeResourceLifecycleState(anyString(),anyString(),anyString(),anyString(),anyString()); + assertEquals(409, result.getStatusCodeValue()); + } + + @Test + public void saveCompositionNoExistingCompositionFailure() throws Exception { + + when(sdcClientMock.getResource(anyString(),anyString())).thenReturn(vfcmt); + + ResponseEntity result = compositionBusinessLogic.saveComposition(justAString, justAString, justAString, justAString, false); + + verify(sdcClientMock).getResource(anyString(),anyString()); + verify(sdcClientMock, times(0)).createResourceArtifact(anyString(),anyString(),any(),anyString()); + verify(sdcClientMock, times(0)).updateResourceArtifact(anyString(), anyString(), any(), anyString()); + verify(sdcClientMock, times(0)).changeResourceLifecycleState(anyString(),anyString(),anyString(),anyString(),anyString()); + assertEquals(404, result.getStatusCodeValue()); + } + + + //backward compatibility - create new composition + @Test + public void successfulSaveNewCompositionAndCheckIn() throws Exception { + + when(sdcClientMock.getResource(anyString(),anyString())).thenReturn(vfcmt); + when(vfcmt.getLifecycleState()).thenReturn("NOT_CERTIFIED_CHECKOUT"); + + compositionBusinessLogic.saveComposition(justAString, justAString, justAString, justAString, true); + + verify(sdcClientMock).getResource(anyString(),anyString()); + verify(sdcClientMock).createResourceArtifact(anyString(),anyString(),any(),anyString()); + verify(sdcClientMock, times(0)).updateResourceArtifact(anyString(), anyString(), any(), anyString()); + verify(sdcClientMock).changeResourceLifecycleState(anyString(),anyString(),anyString(),anyString(),anyString()); + } + + + @Test + public void submitCompositionSuccessNoPreviousBlueprint() throws Exception { + + String vfiName = "vfiName"; + mockVfiList(vfiName); + when(vfcmt.getLifecycleState()).thenReturn("NOT_CERTIFIED_CHECKOUT"); + when(sdcClientMock.getAssetMetadata(anyString(),anyString(), anyString())).thenReturn(service); + VfcmtData vfcmtData = new VfcmtData(vfcmt, vfiName, justAString, justAString); + + compositionBusinessLogic.submitComposition(justAString, justAString, vfcmtData, justAString, justAString); + + verify(sdcClientMock).getAssetMetadata(anyString(), anyString(), anyString()); + verify(sdcClientMock).createInstanceArtifact(anyString(), anyString(), anyString(), anyString(), any(),anyString()); + verify(sdcClientMock, times(0)).updateInstanceArtifact(anyString(), anyString(), anyString(), anyString(), any(), anyString()); + verify(sdcClientMock, times(0)).getMonitoringReferences(anyString(), anyString(), anyString(), anyString()); + verify(sdcClientMock, times(2)).changeResourceLifecycleState(anyString(),anyString(),anyString(),anyString(),anyString()); + } + + @Test + public void submitCompositionSuccessDeletePreviousReference() throws Exception { + + String vfiName = "vfiName"; + String flowType = "flowType"; + mockVfiWithBlueprint(vfiName, flowType); + when(vfcmt.getLifecycleState()).thenReturn("NOT_CERTIFIED_CHECKIN"); + when(sdcClientMock.getAssetMetadata(anyString(),anyString(), anyString())).thenReturn(service); + when(service.getVersion()).thenReturn("0.3"); + when(service.getUuid()).thenReturn(justAString); + ExternalReferencesMap referencesMap = new ExternalReferencesMap(); + ResourceDetailed previousMcVersion = new ResourceDetailed(); + previousMcVersion.setInvariantUUID(vfcmt.getInvariantUUID()); + previousMcVersion.setUuid("previousId"); + referencesMap.put(Normalizers.normalizeComponentInstanceName(vfiName), Arrays.asList(vfcmt.getUuid(), previousMcVersion.getUuid())); + when(sdcClientMock.getMonitoringReferences(anyString(), anyString(), anyString(), anyString())).thenReturn(referencesMap); + when(sdcClientMock.getResource(previousMcVersion.getUuid(), justAString)).thenReturn(previousMcVersion); + VfcmtData vfcmtData = new VfcmtData(vfcmt, vfiName, flowType, justAString); + + compositionBusinessLogic.submitComposition(justAString, justAString, vfcmtData, justAString, justAString); + + verify(sdcClientMock).getAssetMetadata(anyString(), anyString(), anyString()); + verify(sdcClientMock).updateInstanceArtifact(anyString(), anyString(), anyString(), anyString(), any(),anyString()); + verify(sdcClientMock, times(0)).createInstanceArtifact(anyString(), anyString(), anyString(), anyString(), any(), anyString()); + verify(sdcClientMock).getMonitoringReferences(anyString(), anyString(), anyString(), anyString()); + verify(sdcClientMock).getResource(anyString(), anyString()); + verify(sdcClientMock).deleteExternalMonitoringReference(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()); + verify(sdcClientMock).changeResourceLifecycleState(anyString(),anyString(),anyString(),anyString(),anyString()); + } + + private void emulateListOfArtifactsWithCompositionYml() { + List<Artifact> listOfArtifactCompositionYml = new ArrayList<>(); + Artifact compositionArtifact = Mockito.mock(Artifact.class); + when(compositionArtifact.getArtifactName()).thenReturn(DcaeBeConstants.Composition.fileNames.COMPOSITION_YML); + listOfArtifactCompositionYml.add(compositionArtifact); + when(vfcmt.getArtifacts()).thenReturn(listOfArtifactCompositionYml); + } + + private void mockVfiList(String vfiName) { + List<ResourceInstance> vfiList = new ArrayList<>(); + ResourceInstance vfi = Mockito.mock(ResourceInstance.class); + when(vfi.getResourceInstanceName()).thenReturn(vfiName); + vfiList.add(vfi); + when(service.getResources()).thenReturn(vfiList); + } + + private void mockVfiWithBlueprint(String vfiName, String flowType) { + mockVfiList(vfiName); + List<Artifact> instanceArtifacts = new ArrayList<>(); + Artifact blueprint = Mockito.mock(Artifact.class); + String artifactName = compositionBusinessLogic.generateBlueprintFileName(flowType, vfcmt.getName()); + when(blueprint.getArtifactName()).thenReturn(artifactName); + instanceArtifacts.add(blueprint); + when(service.getResources().get(0).getArtifacts()).thenReturn(instanceArtifacts); + } + +}
\ No newline at end of file diff --git a/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/ReferenceBusinessLogicTest.java b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/ReferenceBusinessLogicTest.java index c353701..70c0577 100644 --- a/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/ReferenceBusinessLogicTest.java +++ b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/ReferenceBusinessLogicTest.java @@ -10,6 +10,7 @@ import org.mockito.runners.MockitoJUnitRunner; import org.onap.sdc.dcae.client.ISdcClient; import org.onap.sdc.dcae.composition.restmodels.MonitoringComponent; import org.onap.sdc.dcae.composition.restmodels.sdc.*; +import org.onap.sdc.dcae.composition.util.DcaeBeConstants; import org.onap.sdc.dcae.errormng.ErrorConfigurationLoader; import org.onap.sdc.dcae.errormng.ResponseFormat; import org.springframework.http.HttpStatus; @@ -36,7 +37,7 @@ public class ReferenceBusinessLogicTest { private ResourceDetailed templateMC; @InjectMocks - ReferenceBusinessLogic classUnderTest; + private ReferenceBusinessLogic classUnderTest; @Before public void setup(){ @@ -86,7 +87,7 @@ public class ReferenceBusinessLogicTest { ServiceDetailed serviceDetailed = new ServiceDetailed(); ResourceInstance resourceInstance = new ResourceInstance(); Artifact artifact = new Artifact(); - artifact.setArtifactName(monitoringComponentName); + artifact.setArtifactName("." + monitoringComponentName + "." + DcaeBeConstants.Composition.fileNames.EVENT_PROC_BP_YAML); resourceInstance.setArtifacts(Collections.singletonList(artifact)); resourceInstance.setResourceInstanceName(vfiName); serviceDetailed.setResources(Collections.singletonList(resourceInstance)); @@ -98,7 +99,7 @@ public class ReferenceBusinessLogicTest { mockGetService(); ResponseEntity responseEntity = classUnderTest.deleteVfcmtReferenceBlueprint(userId, "", monitoringComponentName, serviceUuid, vfiName, "", requestId); verify(sdcClientMock).getService(serviceUuid, requestId); - verify(sdcClientMock).deleteInstanceResourceArtifact(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()); + verify(sdcClientMock).deleteInstanceArtifact(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()); Assert.assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); } @@ -114,7 +115,7 @@ public class ReferenceBusinessLogicTest { @Test public void deleteVfcmtReferenceBlueprint_exceptionSdcdeleteInstanceResourceArtifact() throws Exception { mockGetService(); - doThrow(new RuntimeException("")).when(sdcClientMock).deleteInstanceResourceArtifact(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()); + doThrow(new RuntimeException("")).when(sdcClientMock).deleteInstanceArtifact(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()); ResponseEntity<ResponseFormat> responseEntity = classUnderTest.deleteVfcmtReferenceBlueprint(userId, "", monitoringComponentName, serviceUuid, vfiName, "", requestId); diff --git a/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/RuleEditorBusinessLogicTest.java b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/RuleEditorBusinessLogicTest.java new file mode 100644 index 0000000..d421113 --- /dev/null +++ b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/RuleEditorBusinessLogicTest.java @@ -0,0 +1,217 @@ +package org.onap.sdc.dcae.composition.impl; + +import org.onap.sdc.dcae.client.ISdcClient; +import org.onap.sdc.dcae.composition.CompositionConfig; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.*; +import org.onap.sdc.dcae.composition.restmodels.sdc.*; +import org.onap.sdc.dcae.composition.util.DcaeBeConstants; +import org.onap.sdc.dcae.errormng.ErrorConfigurationLoader; +import org.onap.sdc.dcae.errormng.ResponseFormat; +import org.onap.sdc.dcae.rule.editor.impl.RulesBusinessLogic; +import org.springframework.http.ResponseEntity; +import org.testng.Assert; + +import java.util.*; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.mockito.Mockito.*; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; + +public class RuleEditorBusinessLogicTest { + + // DEFAULT PROPERTIES + private String justAString = "aStringForAllSeasons"; + private String userId = "gc786h"; + private String vfcmtUuid = "26e8d4b5-f087-4821-a75a-0b9514b5a7ab"; + private String dcaeCompLabel = "dMp.DockerMap"; + private String nId = "n.1525864440166.30"; + private String resourceUuid = "26e8d4b5-f087-4821-a75a-0b9514b5a7ab"; + private String artifactUuid = "9b00ba74-da02-4706-8db0-ac3c11d1d47b"; + private String configParam = "aaf_username"; + private String requestId = "9a89b5c7-33b2-4f7e-a404-66bf4115f510"; + private String flowTypeName = "SNMP MSE"; + private String ruleUuid = "sadsads"; + private String categoryName = "Template"; + private String resourceType = "VFCMT"; + private String saveRulesJsonRequest = "{\n\"version\":\"4.1\",\n\"eventType\":\"syslogFields\",\n\"uid\":\"\",\n\"description\":\"sfasfsaf\",\n\"actions\":[\n{\n\"id\":\"6e0175a0-581f-11e8-82eb-53bb060b790a\",\n\"actionType\":\"copy\",\n\"from\":{\n\"value\":\"asfsf\",\n\"regex\":\"\",\n\"state\":\"closed\",\n\"values\":[\n{\n" + "\"value\":\"\"\n" + "},\n" + "{\n\"value\":\"\"\n}\n]\n},\n\"target\":\"event.commonEventHeader.eventType\",\n\"map\":{\n\"values\":[\n{\n\"key\":\"\",\n\"value\":\"\"\n}\n],\n\"haveDefault\":false,\n\"default\":\"\"\n},\n\"dateFormatter\":{\n\"fromFormat\":\"\",\n\"toFormat\":\"\",\n\"fromTimezone\":\"\",\n\"toTimezone\":\"\"\n},\n\"replaceText\":{\n\"find\":\"\",\n\"replace\":\"\"\n},\n\"logText\":{\n\"name\":\"\",\n\"level\":\"\",\n\"text\":\"\"\n},\n\"logEvent\":{\n\"title\":\"\"\n}\n}\n],\n\"condition\":null\n}"; + private String artifactJson = "{\n \"artifactName\":\"composition.yml\",\n \"artifactType\":\"DCAE_TOSCA\",\n \"artifactURL\":\"/sdc/v1/catalog/resources/c2877686-616a-48ca-a37b-7e311bf83adc/artifacts/9b00ba74-da02-4706-8db0-ac3c11d1d47b\",\n \"artifactDescription\":\"createReferenceArtifact\",\n \"artifactTimeout\":null,\n \"artifactChecksum\":\"MjhhYTAwOTIxZGZkMGMyMmFjYmEzYjI1NTIwYjA3YzM=\",\n \"artifactUUID\":\"9b00ba74-da02-4706-8db0-ac3c11d1d47b\",\n \"artifactVersion\":\"1\",\n \"generatedFromUUID\":null,\n \"artifactLabel\":\"servicereference\",\n \"artifactGroupType\":\"DEPLOYMENT\",\n \"payloadData\":null,\n \"description\":null\n" + "}"; + private String defaultPayload = "{eventType:syslogFields,version:4.1,rules:{'test':{'version':'4.1'}}}"; + + + // MOCKS + private ISdcClient sdcClientMock = Mockito.mock(ISdcClient.class); + private ResourceDetailed vfcmt = Mockito.mock(ResourceDetailed.class); + private SchemaInfo schemaInfo = Mockito.mock(SchemaInfo.class); + private CompositionConfig compositionConfig = Mockito.mock(CompositionConfig.class); + private RulesBusinessLogic rulesBusinessLogic = Mockito.mock(RulesBusinessLogic.class); + private CompositionConfig.FlowType flowType = Mockito.mock(CompositionConfig.FlowType.class); + + @InjectMocks + private RuleEditorBusinessLogic ruleEditorBusinessLogic = new RuleEditorBusinessLogic(); + + @Before + public void setup() { + + MockitoAnnotations.initMocks(this); + ruleEditorBusinessLogic.setSdcRestClient(sdcClientMock); + + new ErrorConfigurationLoader(System.getProperty("user.dir") + "/src/main/webapp/WEB-INF"); + when(vfcmt.getUuid()).thenReturn(vfcmtUuid); + when(vfcmt.getName()).thenReturn(justAString); + when(vfcmt.getDescription()).thenReturn(justAString); + when(vfcmt.getResourceType()).thenReturn(resourceType); + when(vfcmt.getCategory()).thenReturn(categoryName); + + when(ruleEditorBusinessLogic.getSdcRestClient().getResource(anyString(), anyString())).thenReturn(vfcmt); + when(schemaInfo.getVersion()).thenReturn("0.2"); + + /* PowerMockito.doReturn(vs).when(VesStructureLoader.class); + when(vs.getEventListenerDefinitionByVersion(anyString())).thenReturn(null);*/ + } + + @Test + public void test_saveRules() throws Exception { + + emulateMockListOfArtifacts(dcaeCompLabel, nId, configParam, true); + + when(ruleEditorBusinessLogic.getSdcRestClient().getResourceArtifact(resourceUuid, artifactUuid, requestId)).thenReturn(defaultPayload); + when(rulesBusinessLogic.addOrEditRule(any(MappingRules.class), any(Rule.class))).thenReturn(true); + + ResponseEntity result = ruleEditorBusinessLogic.saveRule(saveRulesJsonRequest, requestId, userId, vfcmtUuid, dcaeCompLabel, nId, configParam); + assertEquals(200,result.getStatusCodeValue()); + Assert.assertTrue(result.getBody().toString().contains("6e0175a0-581f-11e8-82eb-53bb060b790a")); + verify(rulesBusinessLogic,times(1)).addOrEditRule(any(MappingRules.class), any(Rule.class)); + + } + + @Test + public void test_saveRules_artifactNotFound() throws Exception { + + emulateMockListOfArtifacts(dcaeCompLabel, nId, configParam, false); + + when(rulesBusinessLogic.addOrEditRule(any(MappingRules.class), any(Rule.class))).thenReturn(true); + String payload = "{eventType:syslogFields,version:4.1,rules:{'test':{'version':'4.1'}},\"nid\":\"n.1525864440166.30}"; + when(ruleEditorBusinessLogic.getSdcRestClient().getResourceArtifact(anyString(),anyString(), anyString())).thenReturn(payload); + + ResponseEntity result = ruleEditorBusinessLogic.saveRule(saveRulesJsonRequest, requestId, userId, vfcmtUuid, dcaeCompLabel, nId, configParam); + assertEquals(200,result.getStatusCodeValue()); + Assert.assertTrue(result.getBody().toString().contains("6e0175a0-581f-11e8-82eb-53bb060b790a")); + verify(rulesBusinessLogic,times(0)).addOrEditRule(any(MappingRules.class), any(Rule.class)); + + } + + @Test + public void test_saveRules_artifactNotFound_Error() throws Exception { + + emulateMockListOfArtifacts(dcaeCompLabel, nId, configParam, false); + + when(ruleEditorBusinessLogic.getSdcRestClient().getResourceArtifact(anyString(),anyString(), anyString())).thenReturn(defaultPayload); + + ResponseEntity<ResponseFormat> result = ruleEditorBusinessLogic.saveRule(saveRulesJsonRequest, requestId, userId, vfcmtUuid, dcaeCompLabel, nId, configParam); + assertEquals(400,result.getStatusCodeValue()); + assertEquals("SVC6114",result.getBody().getRequestError().getServiceException().getMessageId()); + assertEquals("DCAE component %1 not found in composition",result.getBody().getRequestError().getServiceException().getText()); + verify(rulesBusinessLogic,times(0)).addOrEditRule(any(MappingRules.class), any(Rule.class)); + + } + + @Test + public void test_getRules() throws Exception { + + emulateMockListOfArtifacts(dcaeCompLabel, nId, configParam, true); + + when(ruleEditorBusinessLogic.getSdcRestClient().getResourceArtifact(resourceUuid, artifactUuid, requestId)) + .thenReturn(defaultPayload); + + ResponseEntity result = ruleEditorBusinessLogic.getRules(vfcmtUuid, dcaeCompLabel, nId, configParam, requestId); + assertEquals(200,result.getStatusCodeValue()); + Assert.assertTrue(result.getBody().toString().contains("eventType:syslogFields,version:4.1,rules:{'test':{'version':'4.1'")); + + } + + @Test + public void test_getExistingRuleTargets() throws Exception { + + emulateMockListOfArtifacts(dcaeCompLabel, nId, configParam, true); + + when(ruleEditorBusinessLogic.getSdcRestClient().getResourceArtifact(resourceUuid, artifactUuid, requestId)).thenReturn(defaultPayload); + + ResponseEntity result = ruleEditorBusinessLogic.getExistingRuleTargets(vfcmtUuid, requestId, dcaeCompLabel, nId); + assertEquals(200,result.getStatusCodeValue()); + assertNotEquals(null,result.getBody()); + + } + + @Test + public void test_translate() throws Exception { + + emulateMockListOfArtifacts(dcaeCompLabel, nId, configParam, true); + + when(ruleEditorBusinessLogic.getSdcRestClient().getResourceArtifact(resourceUuid, artifactUuid, requestId)).thenReturn(defaultPayload); + Map<String, CompositionConfig.FlowType> flowTypeMap = new HashMap<>(); + flowTypeMap.put("SNMP MSE", flowType); + when(compositionConfig.getFlowTypesMap()).thenReturn(flowTypeMap); + when(compositionConfig.getFlowTypesMap().get("SNMP MSE").getEntryPointPhaseName()).thenReturn("testName"); + when(compositionConfig.getFlowTypesMap().get("SNMP MSE").getLastPhaseName()).thenReturn("testLastName"); + + when(rulesBusinessLogic.translateRules(any(MappingRules.class), anyString(), anyString(), anyString())).thenReturn("testLastName"); + ResponseEntity result = ruleEditorBusinessLogic.translateRules(vfcmtUuid, requestId, dcaeCompLabel, nId, configParam, flowTypeName); + verify(compositionConfig,times(6)).getFlowTypesMap(); + verify(rulesBusinessLogic,times(1)).translateRules(any(MappingRules.class), anyString(), anyString(), anyString()); + + assertEquals(200,result.getStatusCodeValue()); + + } + + @Test + public void test_deleteRule() throws Exception { + + emulateMockListOfArtifacts(dcaeCompLabel, nId, configParam, true); + + when(ruleEditorBusinessLogic.getSdcRestClient().getResourceArtifact(resourceUuid, artifactUuid, requestId)).thenReturn(defaultPayload); + + when(rulesBusinessLogic.deleteRule(any(MappingRules.class), anyString())).thenReturn(new Rule()); + ResponseEntity result = ruleEditorBusinessLogic.deleteRule(userId, vfcmtUuid, dcaeCompLabel, nId, configParam, ruleUuid, requestId); + assertEquals(200,result.getStatusCodeValue()); + + } + + @Test + public void test_getDefinition(){ + + +/* + PowerMockito.mockStatic(VesStructureLoader.class); + when(VesStructureLoader.getEventListenerDefinitionByVersion(anyString())).thenReturn(null); +*/ + + ResponseEntity res = ruleEditorBusinessLogic.getDefinition("4.1","syslogFields"); + + } + + private void emulateMockListOfArtifacts(String dcaeCompLabel, String nid, String configParam, boolean isApprovedArtifact) { + List<Artifact> listOfArtifactCompositionYml = new ArrayList<>(); + Artifact artifact = Mockito.mock(Artifact.class);//gson.fromJson(artifactJson, Artifact.class); + + if (isApprovedArtifact) { + when(artifact.getArtifactLabel()).thenReturn(dcaeCompLabel + nid + configParam); + when(artifact.getArtifactName()).thenReturn(dcaeCompLabel + "_" + nid + "_" + DcaeBeConstants.Composition.fileNames.MAPPING_RULE_POSTFIX); + }else { + when(artifact.getArtifactLabel()).thenReturn("servicereference"); + when(artifact.getArtifactName()).thenReturn("composition.yml"); + } + when(artifact.getArtifactType()).thenReturn("DCAE_TOSCA"); + when(artifact.getArtifactUUID()).thenReturn(artifactUuid); + when(artifact.getArtifactDescription()).thenReturn("createmapArtifact"); + + listOfArtifactCompositionYml.add(artifact); + when(vfcmt.getArtifacts()).thenReturn(listOfArtifactCompositionYml); + } + + +} diff --git a/dcaedt_be/src/test/java/org/onap/sdc/dcae/services/GetServicesTest.java b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/ServiceBusinessLogicTest.java index 68f055f..3cac355 100644 --- a/dcaedt_be/src/test/java/org/onap/sdc/dcae/services/GetServicesTest.java +++ b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/ServiceBusinessLogicTest.java @@ -1,22 +1,47 @@ -package org.onap.sdc.dcae.services; +package org.onap.sdc.dcae.composition.impl; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.when; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.UUID; +import java.util.*; import java.util.stream.Collectors; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import org.junit.Before; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.sdc.dcae.client.ISdcClient; import org.onap.sdc.dcae.composition.restmodels.DcaeMinimizedService; -import org.onap.sdc.dcae.composition.controller.ServicesController; +import org.onap.sdc.dcae.composition.impl.ServiceBusinessLogic; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.ActionDeserializer; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.BaseAction; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.BaseCondition; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.ConditionDeserializer; +import org.onap.sdc.dcae.composition.restmodels.sdc.Artifact; +import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceInstance; +import org.onap.sdc.dcae.composition.restmodels.sdc.ServiceDetailed; import org.onap.sdc.dcae.composition.util.DcaeBeConstants; import org.onap.sdc.dcae.composition.util.DcaeBeConstants.LifecycleStateEnum; +import org.onap.sdc.dcae.errormng.ErrorConfigurationLoader; import org.testng.annotations.Test; -public class GetServicesTest { - +public class ServiceBusinessLogicTest { + + private String userId = "me"; + private String requestId = "1"; + private String monitoringComponentName = "monitoringComponentName"; + private String serviceUuid = "serviceUuid"; + private String vfiName = "vfiName"; + + private static Gson gson = new GsonBuilder() + .registerTypeAdapter(BaseAction.class, new ActionDeserializer()) + .registerTypeAdapter(BaseCondition.class, new ConditionDeserializer()).create(); + + ServiceBusinessLogic target = new ServiceBusinessLogic(); + @Test public void parseAndFliterServicesByUser_nullServices_TBD() { @@ -27,7 +52,6 @@ public class GetServicesTest { @Test public void parseAndFliterServicesByUser_emptyList_emptyList() { // arrange - ServicesController target = new ServicesController(); String user_id = "test"; String lastUpdaterUserId = "test"; List<LinkedHashMap<String, String>> services = new ArrayList<LinkedHashMap<String, String>>(); @@ -49,7 +73,6 @@ public class GetServicesTest { String version = "0.1"; String serviceName = "TestService"; - ServicesController target = new ServicesController(); LinkedHashMap<String, String> service = createServiceAsMap(lastUpdaterUserId, uuid, invariantUUID, lifecycleState, version, serviceName); List<LinkedHashMap<String, String>> services = new ArrayList<LinkedHashMap<String, String>>( @@ -77,7 +100,6 @@ public class GetServicesTest { .map(x -> createServiceAsMap(lastUpdaterUserId, uuid, UUID.randomUUID().toString(), lifecycleState, version, x)) .collect(Collectors.toList()); - ServicesController target = new ServicesController(); // act List<DcaeMinimizedService> result = target.parseAndFilterServicesByUser(lastUpdaterUserId, unsortedServices, @@ -112,8 +134,6 @@ public class GetServicesTest { List<LinkedHashMap<String, String>> singleServiceWithMultiVersions = Arrays.asList("1.0", "0.3", "11.0", "2.0", "1.8").stream() .map(x -> createServiceAsMap(lastUpdaterUserId, uuid, invariantUUID, lifecycleState, x, serviceName)) .collect(Collectors.toList()); - - ServicesController target = new ServicesController(); // act List<DcaeMinimizedService> result = target.parseAndFilterServicesByUser(lastUpdaterUserId, singleServiceWithMultiVersions, user_id); @@ -139,5 +159,15 @@ public class GetServicesTest { return service; } - + private void mockGetService() + { + ServiceDetailed serviceDetailed = new ServiceDetailed(); + ResourceInstance resourceInstance = new ResourceInstance(); + Artifact artifact = new Artifact(); + artifact.setArtifactName("." + monitoringComponentName + "." + DcaeBeConstants.Composition.fileNames.EVENT_PROC_BP_YAML); + resourceInstance.setArtifacts(Collections.singletonList(artifact)); + resourceInstance.setResourceInstanceName(vfiName); + serviceDetailed.setResources(Collections.singletonList(resourceInstance)); + when(target.getSdcRestClient().getService(serviceUuid, requestId)).thenReturn(serviceDetailed); + } } diff --git a/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/VfcmtBusinessLogicTest.java b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/VfcmtBusinessLogicTest.java index 12ed040..5f1ba41 100644 --- a/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/VfcmtBusinessLogicTest.java +++ b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/VfcmtBusinessLogicTest.java @@ -7,10 +7,8 @@ import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.onap.sdc.dcae.catalog.asdc.ASDCException; import org.onap.sdc.dcae.client.ISdcClient; -import org.onap.sdc.dcae.client.SdcRestClient; import org.onap.sdc.dcae.composition.restmodels.CreateVFCMTRequest; import org.onap.sdc.dcae.composition.restmodels.ImportVFCMTRequest; -import org.onap.sdc.dcae.composition.restmodels.MonitoringComponent; import org.onap.sdc.dcae.composition.restmodels.VfcmtData; import org.onap.sdc.dcae.composition.restmodels.sdc.Artifact; import org.onap.sdc.dcae.composition.restmodels.sdc.ExternalReferencesMap; @@ -23,20 +21,20 @@ import org.onap.sdc.dcae.errormng.RequestError; import org.onap.sdc.dcae.errormng.ResponseFormat; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.web.client.HttpClientErrorException; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; import static org.onap.sdc.dcae.composition.util.DcaeBeConstants.LifecycleStateEnum.CERTIFIED; import static org.onap.sdc.dcae.composition.util.DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT; public class VfcmtBusinessLogicTest { - private ISdcClient sdcClientMock = Mockito.mock(SdcRestClient.class); + private ISdcClient sdcClientMock = Mockito.mock(ISdcClient.class); private ResourceDetailed templateMC = Mockito.mock(ResourceDetailed.class); private VfcmtBusinessLogic vfcmtBusinessLogic = new VfcmtBusinessLogic(); @@ -60,7 +58,7 @@ public class VfcmtBusinessLogicTest { } @Test - public void sdcIsDown_creatingVfcmt_gotResponseWithError500() throws Exception{ + public void sdcIsDown_creatingVfcmt_gotResponseWithError500() { RequestError requestError = new RequestError(); requestError.setPolicyException(new PolicyException("POL5000", "Error: Internal Server Error. Please try again later.", null)); when(sdcClientMock.createResource(userId,request,requestId)).thenThrow(new ASDCException(HttpStatus.INTERNAL_SERVER_ERROR, requestError)); @@ -77,7 +75,6 @@ public class VfcmtBusinessLogicTest { requestError.setPolicyException(new PolicyException("POL5000", "Error: Internal Server Error. Please try again later.", null)); when(sdcClientMock.createResourceArtifact(anyString(),anyString(),any(),anyString())).thenThrow(new ASDCException(HttpStatus.INTERNAL_SERVER_ERROR, requestError)); when(sdcClientMock.createResource(userId,request,requestId)).thenReturn(templateMC); - when(sdcClientMock.getResourceArtifact(anyString(), anyString(), anyString())).thenReturn("{\"flowType\":\"don't override\""); when(templateMC.getUuid()).thenReturn("3"); when(sdcClientMock.getResource(anyString(),anyString())).thenReturn(templateMC); emulateListOfArtifactsWithCompositionYml(); @@ -113,7 +110,6 @@ public class VfcmtBusinessLogicTest { @Test public void successfulImportAndAttachmentOfVfcmtAlreadyConnectedWithoutEditDoCheckin() throws Exception { when(sdcClientMock.getResource(anyString(),anyString())).thenReturn(templateMC); - when(sdcClientMock.getResourceArtifact(anyString(),anyString(),anyString())).thenReturn("{\"flowType\":\"don't override\"}"); when(templateMC.getLifecycleState()).thenReturn("NOT_CERTIFIED_CHECKOUT"); emulateListOfArtifactsWithCompositionYmlAndSvcRef(); request.setCloneVFCMT(false); @@ -136,7 +132,6 @@ public class VfcmtBusinessLogicTest { when(templateMC.getUuid()).thenReturn("3"); when(sdcClientMock.changeResourceLifecycleState(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(templateMC); when(sdcClientMock.updateResourceArtifact(anyString(), anyString(), any(), anyString())).thenReturn(new Artifact()); - when(sdcClientMock.getResourceArtifact(anyString(),anyString(),anyString())).thenReturn("{\"cid\":\"xsssdaerrwr\"}"); when(templateMC.getLifecycleState()).thenReturn("NOT_CERTIFIED_CHECKIN").thenReturn("NOT_CERTIFIED_CHECKOUT"); emulateListOfArtifactsWithCompositionYmlAndSvcRef(); request.setCloneVFCMT(false); @@ -154,46 +149,69 @@ public class VfcmtBusinessLogicTest { @Test - public void successfulFetchVfcmtDataFull() throws Exception { + public void invalidateMCRequestFields_returnError() { + ResponseEntity response = vfcmtBusinessLogic.importMC(userId, new ImportVFCMTRequest(), requestId); + Assert.assertEquals(response.getStatusCodeValue(), 400); + } + + @Test + public void cloneVfcmt_missingToscaFile_returnError() { + when(sdcClientMock.getResource(anyString(),anyString())).thenReturn(templateMC); + request.setCloneVFCMT(true); + ResponseEntity response = vfcmtBusinessLogic.importMC(userId, request, requestId); + Assert.assertEquals(response.getStatusCodeValue(), 404); + } + + @Test + public void checkCatchingSdcExceptions_returnError() { + RequestError requestError = new RequestError(); + requestError.setPolicyException(new PolicyException("POL5000", "Error: Internal Server Error. Please try again later.", null)); + when(sdcClientMock.getResource(request.getTemplateUuid(), requestId)).thenThrow(new ASDCException(HttpStatus.INTERNAL_SERVER_ERROR, requestError)); + request.setCloneVFCMT(false); + request.setUpdateFlowType(true); + ResponseEntity response = vfcmtBusinessLogic.importMC(userId, request, requestId); + Assert.assertEquals(response.getStatusCodeValue(), 500); + } + + + @Test + public void successfulFetchVfcmtDataFull() { String templateUuid = "3"; when(templateMC.getUuid()).thenReturn(templateUuid); when(sdcClientMock.getResource(anyString(),anyString())).thenReturn(templateMC); emulateListOfArtifactsWithCompositionYmlAndSvcRef(); when(sdcClientMock.getResourceArtifact(templateUuid, "svcRefArtifactUuid", requestId)).thenReturn("thisIsTheServiceId/resources/thisIsTheVfiName"); - when(sdcClientMock.getResourceArtifact(templateUuid, "compositionArtifactUuid", requestId)).thenReturn("\"flowType\":\"Syslog\""); ResponseEntity<VfcmtData> result = vfcmtBusinessLogic.getVfcmtReferenceData(templateUuid, requestId); verify(sdcClientMock).getResource(anyString(),anyString()); verify(sdcClientMock,times(2)).getResourceArtifact(anyString(),anyString(),anyString()); Assert.assertEquals(200, result.getStatusCodeValue()); - Assert.assertEquals("Syslog", result.getBody().getFlowType()); + Assert.assertEquals("don't override", result.getBody().getFlowType()); Assert.assertEquals("thisIsTheServiceId", result.getBody().getServiceUuid()); Assert.assertEquals("thisIsTheVfiName", result.getBody().getVfiName()); } @Test - public void successfulFetchVfcmtDataPartial() throws Exception { + public void successfulFetchVfcmtDataPartial() { String templateUuid = "3"; when(templateMC.getUuid()).thenReturn(templateUuid); when(sdcClientMock.getResource(anyString(),anyString())).thenReturn(templateMC); emulateListOfArtifactsWithCompositionYml(); - when(sdcClientMock.getResourceArtifact(templateUuid, "compositionArtifactUuid", requestId)).thenReturn("\"flowType\":\"Syslog\""); ResponseEntity<VfcmtData> result = vfcmtBusinessLogic.getVfcmtReferenceData(templateUuid, requestId); verify(sdcClientMock).getResource(anyString(),anyString()); verify(sdcClientMock,times(1)).getResourceArtifact(anyString(),anyString(),anyString()); Assert.assertEquals(200, result.getStatusCodeValue()); - Assert.assertEquals("Syslog", result.getBody().getFlowType()); + Assert.assertEquals("don't override", result.getBody().getFlowType()); Assert.assertEquals(null, result.getBody().getServiceUuid()); Assert.assertEquals(null, result.getBody().getVfiName()); } @Test - public void successfulFetchVfcmtDataEmpty() throws Exception { + public void successfulFetchVfcmtDataEmpty() { String templateUuid = "3"; when(templateMC.getUuid()).thenReturn(templateUuid); when(sdcClientMock.getResource(anyString(),anyString())).thenReturn(templateMC); - emulateListOfArtifactsWithCompositionYml(); - when(sdcClientMock.getResourceArtifact(templateUuid, "compositionArtifactUuid", requestId)).thenReturn(""); + emulateCdumpArtifactWithoutFlowtype(); ResponseEntity<VfcmtData> result = vfcmtBusinessLogic.getVfcmtReferenceData(templateUuid, requestId); verify(sdcClientMock).getResource(anyString(),anyString()); verify(sdcClientMock,times(1)).getResourceArtifact(anyString(),anyString(),anyString()); @@ -204,7 +222,7 @@ public class VfcmtBusinessLogicTest { } @Test - public void fetchVfcmtDataNoCompositionFound() throws Exception { + public void fetchVfcmtDataNoCompositionFound() { String templateUuid = "3"; when(templateMC.getUuid()).thenReturn(templateUuid); @@ -219,7 +237,7 @@ public class VfcmtBusinessLogicTest { } @Test - public void getVfcmtsForMigration() throws Exception { + public void getVfcmtsForMigration() { ExternalReferencesMap connectedVfcmts = new ExternalReferencesMap(); connectedVfcmts.put("11",Arrays.asList("Red", "Blue", "Yellow")); connectedVfcmts.put("22",Arrays.asList("Ibiza", "Bora Bora", "Mykonos")); @@ -281,6 +299,17 @@ public class VfcmtBusinessLogicTest { when(templateMC.getArtifacts()).thenReturn(listOfArtifactCompositionYml); } + + private void emulateCdumpArtifactWithoutFlowtype() { + List<Artifact> listOfArtifactCompositionYml = new ArrayList<>(); + Artifact compositionArtifact = Mockito.mock(Artifact.class); + when(compositionArtifact.getArtifactName()).thenReturn(DcaeBeConstants.Composition.fileNames.COMPOSITION_YML); + when(compositionArtifact.getArtifactUUID()).thenReturn("compositionArtifactUuid"); + when(compositionArtifact.getPayloadData()).thenReturn("{\"cid\":\"xsssdaerrwr\"}\""); + listOfArtifactCompositionYml.add(compositionArtifact); + when(templateMC.getArtifacts()).thenReturn(listOfArtifactCompositionYml); + } + private void emulateListOfArtifactsWithCompositionYmlAndSvcRef() { List<Artifact> listOfArtifactCompositionYml = new ArrayList<>(); Artifact compositionArtifact = Mockito.mock(Artifact.class); @@ -296,7 +325,7 @@ public class VfcmtBusinessLogicTest { } @Test - public void uiHasABug_creatingVfcmtWithBadRequestNoServiceUuid_gotResponseWithError400() throws Exception{ + public void uiHasABug_creatingVfcmtWithBadRequestNoServiceUuid_gotResponseWithError400() { RequestError requestError = new RequestError(); requestError.setPolicyException(new PolicyException("POL5000", "Error: Internal Server Error. Please try again later.", null)); when(sdcClientMock.createResource(userId,request,requestId)).thenThrow(new ASDCException(HttpStatus.INTERNAL_SERVER_ERROR, requestError)); diff --git a/dcaedt_be/src/test/java/org/onap/sdc/dcae/filter/LoggingFilterTest.java b/dcaedt_be/src/test/java/org/onap/sdc/dcae/filter/LoggingFilterTest.java new file mode 100644 index 0000000..cfe9f56 --- /dev/null +++ b/dcaedt_be/src/test/java/org/onap/sdc/dcae/filter/LoggingFilterTest.java @@ -0,0 +1,119 @@ +package org.onap.sdc.dcae.filter; + +import org.apache.http.impl.EnglishReasonPhraseCatalog; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.sdc.common.onaplog.Enums.LogLevel; +import org.onap.sdc.common.onaplog.Enums.OnapLoggerErrorCode; +import org.onap.sdc.common.onaplog.OnapMDCWrapper; + + +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import javax.servlet.http.HttpServletResponse; +import java.util.Enumeration; +import java.util.Locale; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class LoggingFilterTest { + @Mock private HttpServletRequest request; + @Mock private HttpServletResponse httpResponse; + @Mock private ServletResponse response; + @Mock private FilterChain filterChain; + + private FilterConfig filterConfig = new FilterConfig() { + @Override + public String getFilterName() { + return null; + } + + @Override + public ServletContext getServletContext() { + return null; + } + + @Override + public String getInitParameter(String name) { + return null; + } + + @Override + public Enumeration<String> getInitParameterNames() { + return null; + } + }; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void loggingFilterInstanciationLifeCycle() { + LoggingFilter loggingFilter = new LoggingFilter(); + + loggingFilter.init(filterConfig); + + loggingFilter.destroy(); + } + + @Test + public void doFilter_healthCheck_noReadingHeader(){ + LoggingFilter loggingFilter = new LoggingFilter(); + boolean exceptionThrown = false; + + when(request.getServletPath()).thenReturn("/healthCheck"); + try { + loggingFilter.doFilter(request, response, filterChain); + } + catch (Exception e){ + exceptionThrown = true; + } + verify(request,never()).getHeader("X-ECOMP-RequestID"); + assertEquals(exceptionThrown, false); + } + + @Test + public void doFilter_notHealthCheck_noReadingHeader(){ + LoggingFilter loggingFilter = new LoggingFilter(); + boolean exceptionThrown = false; + + when(request.getServletPath()).thenReturn("/notHealthCheck"); + try { + loggingFilter.doFilter(request, response, filterChain); + } + catch (Exception e){ + exceptionThrown = true; + } + verify(request).getHeader("X-ECOMP-RequestID"); + assertEquals(exceptionThrown, false); + } + @Test + public void doFilter_InternalServerError(){ + LoggingFilter loggingFilter = new LoggingFilter(); + boolean exceptionThrown = false; + + when(request.getServletPath()).thenReturn("/notHealthCheck"); + try { + + when(httpResponse.getStatus()).thenReturn(500); + when(request.getHeader("user-agent")).thenReturn("test"); + + loggingFilter.doFilter(request, httpResponse, filterChain); + } + catch (Exception e){ + exceptionThrown = true; + } + verify(request).getHeader("X-ECOMP-RequestID"); + assertEquals(exceptionThrown, false); + } + + +} diff --git a/dcaedt_be/src/test/java/org/onap/sdc/dcae/rule/editor/impl/RulesBusinessLogicTest.java b/dcaedt_be/src/test/java/org/onap/sdc/dcae/rule/editor/impl/RulesBusinessLogicTest.java index d3ae600..bc03632 100644 --- a/dcaedt_be/src/test/java/org/onap/sdc/dcae/rule/editor/impl/RulesBusinessLogicTest.java +++ b/dcaedt_be/src/test/java/org/onap/sdc/dcae/rule/editor/impl/RulesBusinessLogicTest.java @@ -201,6 +201,17 @@ public class RulesBusinessLogicTest { } @Test + public void missingLogTextFailureTest() { + Rule rule = new Rule(); + rule.setDescription("description"); + rule.setActions(new ArrayList<>()); + rule.getActions().add(buildLogTextMissingTextAction()); + List<ServiceException> errors = rulesBusinessLogic.validateRule(rule); + String expectedError = "Please fill the text field of Log Text action to "; + assertEquals(expectedError, errors.get(0).getFormattedErrorMessage()); + } + + @Test public void reorderMappingRulesCircularDependencyFailureTest() { MappingRules mr = new MappingRules(buildRuleWithMultipleCopyActions()); @@ -266,24 +277,31 @@ public class RulesBusinessLogicTest { return rule; } - private BaseAction buildCopyAction(String from, String to) { - BaseAction action = new BaseAction(); + private BaseCopyAction buildCopyAction(String from, String to) { + BaseCopyAction action = new BaseCopyAction(); action.setActionType("copy"); action.setFrom(from); action.setTarget(to); return action; } - private BaseAction buildConcatAction(List<String> from, String to) { - BaseAction action = new BaseAction(); + private LogTextAction buildLogTextMissingTextAction(){ + LogTextAction logTextAction = new LogTextAction(); + logTextAction.setActionType("Log Text"); + logTextAction.setLogText("a name", "a level", ""); + return logTextAction; + } + + private BaseCopyAction buildConcatAction(List<String> from, String to) { + BaseCopyAction action = new BaseCopyAction(); action.setActionType("concat"); action.setFrom(from); action.setTarget(to); return action; } - private BaseAction buildRegexAction(String from, String to, String regex) { - BaseAction action = new BaseAction(); + private BaseCopyAction buildRegexAction(String from, String to, String regex) { + BaseCopyAction action = new BaseCopyAction(); action.setActionType("copy"); action.setFrom(from, regex); action.setTarget(to); |