diff options
Diffstat (limited to 'openecomp-be')
39 files changed, 721 insertions, 588 deletions
diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-services/src/main/java/org/openecomp/sdcrests/action/rest/services/ActionsImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-services/src/main/java/org/openecomp/sdcrests/action/rest/services/ActionsImpl.java index 53ebf0baab..875b51548e 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-services/src/main/java/org/openecomp/sdcrests/action/rest/services/ActionsImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-services/src/main/java/org/openecomp/sdcrests/action/rest/services/ActionsImpl.java @@ -557,15 +557,13 @@ public class ActionsImpl implements Actions { ACTION_REQUEST_MISSING_MANDATORY_PARAM + ARTIFACT_FILE); } - InputStream artifactInputStream = null; - try { - artifactInputStream = artifactToUpload.getDataHandler().getInputStream(); + try (InputStream artifactInputStream = artifactToUpload.getDataHandler().getInputStream()) { + payload = FileUtils.toByteArray(artifactInputStream); } catch (IOException exception) { LOGGER.error(ACTION_ARTIFACT_READ_FILE_ERROR, exception); throw new ActionException(ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ARTIFACT_READ_FILE_ERROR); } - payload = FileUtils.toByteArray(artifactInputStream); //Validate Artifact size if (payload != null && payload.length > MAX_ACTION_ARTIFACT_SIZE) { throw new ActionException(ACTION_ARTIFACT_TOO_BIG_ERROR_CODE, ACTION_ARTIFACT_TOO_BIG_ERROR); @@ -761,15 +759,14 @@ public class ActionsImpl implements Actions { } if (artifactToUpdate != null) { - InputStream artifactInputStream = null; - try { - artifactInputStream = artifactToUpdate.getDataHandler().getInputStream(); + + try (InputStream artifactInputStream = artifactToUpdate.getDataHandler().getInputStream()) { + payload = FileUtils.toByteArray(artifactInputStream); } catch (IOException exception) { LOGGER.error(ACTION_ARTIFACT_READ_FILE_ERROR, exception); throw new ActionException(ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ARTIFACT_READ_FILE_ERROR); } - payload = FileUtils.toByteArray(artifactInputStream); //Validate Artifact size if (payload != null && payload.length > MAX_ACTION_ARTIFACT_SIZE) { throw new ActionException(ACTION_ARTIFACT_TOO_BIG_ERROR_CODE, diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/VendorSoftwareProductsImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/VendorSoftwareProductsImpl.java index 9e4d3bf51b..0450244355 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/VendorSoftwareProductsImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/VendorSoftwareProductsImpl.java @@ -78,6 +78,7 @@ import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Objects; +import java.util.stream.Collectors; import static org.openecomp.sdc.logging.messages.AuditMessages.SUBMIT_VSP_ERROR; @@ -403,59 +404,30 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { MDC.put(LoggerConstants.SERVICE_NAME, LoggerServiceName.Re_Submit_ALL_Final_VSPs.toString()); logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.RESUBMIT_ALL_FINAL_VSPS); - List<VersionedVendorSoftwareProductInfo> vspList = Objects.requireNonNull( - vendorSoftwareProductManager.listVsps(VersionStatus.Final.name(), user)); - int skippedCounter = 0; - final int vspListSizeBefore = vspList.size(); - - for (VersionedVendorSoftwareProductInfo versionVspInfo : vspList) { - final VspDetails vspDetails = versionVspInfo.getVspDetails(); - final String vspId = vspDetails.getId(); - final Version latestFinalVersion = - getVersionInfo(vspId, VersionableEntityAction.Read, user).getLatestFinalVersion(); - - if (latestFinalVersion.getStatus().equals(VersionStatus.Locked)) { - logger.info("Skipping processing VSP name [{}]/id [{}] due to status LOCKED", vspDetails - .getName(), - vspId); - skippedCounter++; - vspList.remove(versionVspInfo); - } - } + List<VersionedVendorSoftwareProductInfo> latestFinalVsps = Objects + .requireNonNull(vendorSoftwareProductManager.listVsps(VersionStatus.Final.name(), user)); - logger.info("Removed {} VSPs out of {} from processing due to status LOCKED", skippedCounter, - vspListSizeBefore); + List<VersionedVendorSoftwareProductInfo> nonLockedLatestFinalVsps = latestFinalVsps.stream() + .filter(vsp -> + !isVspLocked(vsp.getVspDetails().getId(), vsp.getVspDetails().getName(), user)) + .collect(Collectors.toList()); + + logger.info("Removed {} VSPs out of {} from processing due to status LOCKED.\n" + + "Total number of VSPs: {}. Performing healing and resubmit for all non-Manual VSPs " + + "in submitted status.\n No need to pre-set oldVersion field", + latestFinalVsps.size() - nonLockedLatestFinalVsps.size(), latestFinalVsps.size(), + nonLockedLatestFinalVsps.size()); int healingCounter = 0; int failedCounter = 0; - int totalCounter = 0; - - - final int vspListSize = vspList.size(); - logger.info("Total number of VSPs: {}. Performing healing and " + - "resubmit for all non-Manual VSPs in submitted status.\n No need to pre-set oldVersion " + - "field", vspListSize); - - for (VersionedVendorSoftwareProductInfo versionVspInfo : vspList) { + for (int counter = 0; counter < nonLockedLatestFinalVsps.size(); counter++) { + VersionedVendorSoftwareProductInfo versionVspInfo = nonLockedLatestFinalVsps.get(counter); try { - totalCounter++; - final Version activeVersion = versionVspInfo.getVersionInfo().getActiveVersion(); final VspDetails vspDetails = versionVspInfo.getVspDetails(); - final String vspId = vspDetails.getId(); - final Version latestFinalVersion = - getVersionInfo(vspId, VersionableEntityAction.Read, user).getLatestFinalVersion(); - - final String vspName = vspDetails.getName(); - logger.info("VSP Name {}, VSP id [{}], Active Version {} , Active Version Status {}," + - "Latest Final Version {} , " + - "Latest Final Version Status {}", vspName, vspId, activeVersion - .toString(), - activeVersion.getStatus(), latestFinalVersion.toString(), - latestFinalVersion.getStatus()); - - if (Objects.nonNull(latestFinalVersion) && - (!OnboardingMethod.Manual.name().equals(vspDetails.getOnboardingMethod()))) { - reSubmit(vspDetails, user, totalCounter, vspListSize); + if (!OnboardingMethod.Manual.name().equals(vspDetails.getOnboardingMethod())) { + logger.info("Starting on healing and resubmit for VSP [{}], #{} out of total {}", + vspDetails.getName(), counter + 1, nonLockedLatestFinalVsps.size()); + reSubmit(vspDetails, user); healingCounter++; } } catch (Exception e) { @@ -464,42 +436,46 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { } logger.info("Total VSPs processed {}. Completed running healing and resubmit for {} VSPs out" + - " " + - "of total # of {} submitted VSPs. Failures count during resubmitAll: {}", - totalCounter, healingCounter, vspListSize, failedCounter); - + " of total # of {} submitted VSPs. Failures count during resubmitAll: {}", + nonLockedLatestFinalVsps.size(), healingCounter, latestFinalVsps.size(), failedCounter); return Response.ok().build(); } + private boolean isVspLocked(String vspId, String vspName, String user) { + final VersionInfo versionInfo = getVersionInfo(vspId, VersionableEntityAction.Read, user); - private void reSubmit(VspDetails vspDetails, String user, int currentCount, int total) throws - Exception { + if (versionInfo.getStatus().equals(VersionStatus.Locked)) { + logger.info("VSP name [{}]/id [{}] status is LOCKED", vspName, vspId); + return true; + } + logger.info("VSP Name {}, VSP id [{}], Active Version {} , Status {}, Latest Final Version {}", + vspName, vspId, versionInfo.getActiveVersion().toString(), versionInfo.getStatus(), + versionInfo.getLatestFinalVersion().toString()); + return false; + } - final String vspId = vspDetails.getId(); - final String vspName = vspDetails.getName(); - final Version versionBefore = vspDetails.getVersion(); - Version finalVersion; - logger.info("Starting on healing and resubmit for VSP [{}], #{} out of total {}", vspName, - currentCount, total); + private void reSubmit(VspDetails vspDetails, String user) throws Exception { + final Version versionBefore = vspDetails.getVersion(); vspDetails.setOldVersion("true"); + Version finalVersion; try { finalVersion = - vendorSoftwareProductManager.healAndAdvanceFinalVersion(vspId, vspDetails, user); - + vendorSoftwareProductManager + .healAndAdvanceFinalVersion(vspDetails.getId(), vspDetails, user); } catch (Exception e) { - logger.error("Failed during resubmit, VSP [{}] , version before:{}, version after:{}, " + "status after:{}, with exception:{}", - vspName, versionBefore.toString(), vspDetails.getVersion().toString(), vspDetails + vspDetails.getName(), versionBefore.toString(), vspDetails.getVersion().toString(), + vspDetails .getVersion().getStatus().name(), e.getMessage()); throw e; } logger.info("Completed healing and resubmit for VSP [{}], version before:{}, version after:" + - " {}", vspName, versionBefore.toString(), finalVersion); + " {}", vspDetails.getName(), versionBefore.toString(), finalVersion); } private static void printAuditForErrors(List<ErrorMessage> errorList, String vspId, diff --git a/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/impl/UploadValidationManagerImpl.java b/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/impl/UploadValidationManagerImpl.java index ddb56ddbfc..1d1ce4f03c 100644 --- a/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/impl/UploadValidationManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/impl/UploadValidationManagerImpl.java @@ -62,20 +62,19 @@ import java.util.zip.ZipInputStream; */ public class UploadValidationManagerImpl implements UploadValidationManager { - private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + private static final MdcDataDebugMessage MDC_DATA_DEBUG_MESSAGE = new MdcDataDebugMessage(); private static FileContentHandler getFileContentMapFromZip(byte[] uploadFileData) throws IOException, CoreException { + ZipEntry zipEntry; List<String> folderList = new ArrayList<>(); FileContentHandler mapFileContent = new FileContentHandler(); - try { - ZipInputStream inputZipStream; + try (ZipInputStream inputZipStream = new ZipInputStream(new ByteArrayInputStream(uploadFileData))) { byte[] fileByteContent; String currentEntryName; - inputZipStream = new ZipInputStream(new ByteArrayInputStream(uploadFileData)); while ((zipEntry = inputZipStream.getNextEntry()) != null) { currentEntryName = zipEntry.getName(); @@ -130,7 +129,7 @@ public class UploadValidationManagerImpl implements UploadValidationManager { throws IOException { - mdcDataDebugMessage.debugEntryMessage(null, null); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage(null, (String[]) null); ValidationFileResponse validationFileResponse = new ValidationFileResponse(); @@ -150,15 +149,12 @@ public class UploadValidationManagerImpl implements UploadValidationManager { Map<String, List<ErrorMessage>> errors = validateHeatUploadData(content); tree = HeatTreeManagerUtil.initHeatTreeManager(content); tree.createTree(); - if (MapUtils.isNotEmpty(errors)) { - + if (MapUtils.isNotEmpty(errors)) { tree.addErrors(errors); validationStructureList.setImportStructure(tree.getTree()); - //validationFileResponse.setStatus(ValidationFileStatus.Failure); - } else { - //validationFileResponse.setStatus(ValidationFileStatus.Success); } + } else { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, LoggerTragetServiceName.VALIDATE_FILE_TYPE, ErrorLevel.ERROR.name(), @@ -167,12 +163,11 @@ public class UploadValidationManagerImpl implements UploadValidationManager { } validationFileResponse.setValidationData(validationStructureList); - mdcDataDebugMessage.debugExitMessage(null, null); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage(null, (String[]) null); return validationFileResponse; } - private Map<String, List<ErrorMessage>> validateHeatUploadData(FileContentHandler fileContentMap) - throws IOException { + private Map<String, List<ErrorMessage>> validateHeatUploadData(FileContentHandler fileContentMap) { ValidationManager validationManager = ValidationManagerUtil.initValidationManager(fileContentMap); return validationManager.validate(); diff --git a/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/util/ValidationManagerUtil.java b/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/util/ValidationManagerUtil.java index 924a956628..53b05eb953 100644 --- a/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/util/ValidationManagerUtil.java +++ b/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/util/ValidationManagerUtil.java @@ -29,6 +29,7 @@ import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.datatypes.error.ErrorMessage; +import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; @@ -43,11 +44,12 @@ public class ValidationManagerUtil { * @param errors the errors */ public static void handleMissingManifest(FileContentHandler fileContentMap, - Map<String, List<ErrorMessage>> errors) { - InputStream manifest = fileContentMap.getFileContent(SdcCommon.MANIFEST_NAME); - if (manifest == null) { - ErrorMessage.ErrorMessageUtil.addMessage(SdcCommon.MANIFEST_NAME, errors) - .add(new ErrorMessage(ErrorLevel.ERROR, Messages.MANIFEST_NOT_EXIST.getErrorMessage())); + Map<String, List<ErrorMessage>> errors) throws IOException { + try (InputStream manifest = fileContentMap.getFileContent(SdcCommon.MANIFEST_NAME)) { + if (manifest == null) { + ErrorMessage.ErrorMessageUtil.addMessage(SdcCommon.MANIFEST_NAME, errors) + .add(new ErrorMessage(ErrorLevel.ERROR, Messages.MANIFEST_NOT_EXIST.getErrorMessage())); + } } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerImpl.java index 3f6ffcc622..07a3fa7f2c 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerImpl.java @@ -30,6 +30,7 @@ import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; import org.openecomp.sdc.activityLog.ActivityLogManager; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.common.utils.CommonUtil; import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.datatypes.error.ErrorMessage; @@ -258,20 +259,20 @@ public class OrchestrationTemplateCandidateManagerImpl OnboardingTypesEnum type = OnboardingTypesEnum.getOnboardingTypesEnum(vspDetails.getOnboardingOrigin()); - if(vspDetails.getOnboardingOrigin().equals(OnboardingTypesEnum.ZIP.toString())) { + if(CommonUtil.isFileOriginFromZip(vspDetails.getOnboardingOrigin())) { FilesDataStructure structure = JsonUtil .json2Object(candidateDataEntity.get().getFilesDataStructure(), FilesDataStructure.class); String manifest = candidateService.createManifest(vspDetails, structure); mdcDataDebugMessage .debugExitMessage("VSP id", vspId); - return Optional.ofNullable( + return Optional.of( new ImmutablePair<>(OnboardingTypesEnum.ZIP.toString(),candidateService .replaceManifestInZip(candidateDataEntity.get().getContentData(), manifest, vspId, type))); } - return Optional.ofNullable( + return Optional.of( new ImmutablePair<>(vspDetails.getOnboardingOrigin(),candidateDataEntity.get() .getContentData().array())); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ProcessManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ProcessManagerImpl.java index 4df00fd74a..a3d0286019 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ProcessManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ProcessManagerImpl.java @@ -50,10 +50,10 @@ import java.io.InputStream; import java.util.Collection; public class ProcessManagerImpl implements ProcessManager { - private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); - private ActivityLogManager activityLogManager; + private static final MdcDataDebugMessage MDC_DATA_DEBUG_MESSAGE = new MdcDataDebugMessage(); + private final ActivityLogManager activityLogManager; - private VendorSoftwareProductDao vendorSoftwareProductDao; + private final VendorSoftwareProductDao vendorSoftwareProductDao; private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); @@ -66,15 +66,15 @@ public class ProcessManagerImpl implements ProcessManager { public Collection<ProcessEntity> listProcesses(String vspId, Version version, String componentId, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); - mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id, component id", vspId, componentId); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id, component id", vspId, componentId); return vendorSoftwareProductDao.listProcesses(vspId, version, componentId); } @Override public void deleteProcesses(String vspId, Version version, String componentId, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id, component id", vspId, componentId); Collection<ProcessEntity> processes = vendorSoftwareProductDao.listProcesses(vspId, version, componentId); @@ -87,12 +87,12 @@ public class ProcessManagerImpl implements ProcessManager { vendorSoftwareProductDao.deleteProcesses(vspId, version, componentId); } - mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id, component id", vspId, componentId); } @Override public ProcessEntity createProcess(ProcessEntity process, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id, component id", process.getId(), + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id, component id", process.getId(), process.getComponentId()); validateUniqueName(process.getVspId(), process.getVersion(), process.getComponentId(), process.getName()); @@ -102,7 +102,7 @@ public class ProcessManagerImpl implements ProcessManager { createUniqueName(process.getVspId(), process.getVersion(), process.getComponentId(), process.getName()); - mdcDataDebugMessage.debugExitMessage("VSP id, component id", process.getId(), + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id, component id", process.getId(), process.getComponentId()); return process; @@ -112,20 +112,20 @@ public class ProcessManagerImpl implements ProcessManager { @Override public ProcessEntity getProcess(String vspId, Version version, String componentId, String processId, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id, component id", vspId, componentId); ProcessEntity retrieved = vendorSoftwareProductDao.getProcess(vspId, version, componentId, processId); validateProcessExistence(vspId, version, componentId, processId, retrieved); - mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id, component id", vspId, componentId); return retrieved; } @Override public void updateProcess(ProcessEntity process, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id, component id", process.getId(), + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id, component id", process.getId(), process.getComponentId()); ProcessEntity retrieved = vendorSoftwareProductDao @@ -138,14 +138,14 @@ public class ProcessManagerImpl implements ProcessManager { retrieved.getName(), process.getName()); vendorSoftwareProductDao.updateProcess(process); - mdcDataDebugMessage.debugExitMessage("VSP id, component id", process.getId(), + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id, component id", process.getId(), process.getComponentId()); } @Override public void deleteProcess(String vspId, Version version, String componentId, String processId, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id, component id", vspId, componentId); ProcessEntity retrieved = vendorSoftwareProductDao.getProcess(vspId, version, componentId, processId); @@ -155,33 +155,30 @@ public class ProcessManagerImpl implements ProcessManager { deleteUniqueValue(retrieved.getVspId(), retrieved.getVersion(), retrieved.getComponentId(), retrieved.getName()); - mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id, component id", vspId, componentId); } @Override public File getProcessArtifact(String vspId, Version version, String componentId, String processId, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id, component id", vspId, componentId); ProcessEntity retrieved = vendorSoftwareProductDao.getProcessArtifact(vspId, version, componentId, processId); validateProcessArtifactExistence(vspId, version, componentId, processId, retrieved); File file = new File(String.format("%s_%s_%s", vspId, componentId, processId)); - try { - FileOutputStream fos = new FileOutputStream(file); + try (FileOutputStream fos = new FileOutputStream(file)) { fos.write(retrieved.getArtifact().array()); - fos.close(); } catch (IOException exception) { - log.debug("", exception); MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.GET_PROCESS_ARTIFACT, ErrorLevel.ERROR.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), "Can't get process artifact"); - throw new CoreException(new UploadInvalidErrorBuilder().build()); + throw new CoreException(new UploadInvalidErrorBuilder().build(), exception); } - mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id, component id", vspId, componentId); return file; } @@ -189,7 +186,7 @@ public class ProcessManagerImpl implements ProcessManager { @Override public void deleteProcessArtifact(String vspId, Version version, String componentId, String processId, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id, component id", vspId, componentId); ProcessEntity retrieved = vendorSoftwareProductDao.getProcessArtifact(vspId, version, componentId, processId); @@ -197,14 +194,14 @@ public class ProcessManagerImpl implements ProcessManager { vendorSoftwareProductDao.deleteProcessArtifact(vspId, version, componentId, processId); - mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id, component id", vspId, componentId); } @Override public void uploadProcessArtifact(InputStream artifactFile, String artifactFileName, String vspId, Version version, String componentId, String processId, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id, component id", vspId, componentId); ProcessEntity retrieved = vendorSoftwareProductDao.getProcess(vspId, version, componentId, processId); @@ -221,11 +218,10 @@ public class ProcessManagerImpl implements ProcessManager { try { artifact = FileUtils.toByteArray(artifactFile); } catch (RuntimeException exception) { - log.debug("", exception); MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.UPLOAD_PROCESS_ARTIFACT, ErrorLevel.ERROR.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), "Can't upload process artifact"); - throw new CoreException(new UploadInvalidErrorBuilder().build()); + throw new CoreException(new UploadInvalidErrorBuilder().build(), exception); } vendorSoftwareProductDao.uploadProcessArtifact(vspId, version, componentId, processId, artifact, @@ -234,13 +230,13 @@ public class ProcessManagerImpl implements ProcessManager { ActivityType.UPLOAD_MONITORING_FILE.toString(), user, true, "", ""); activityLogManager.addActionLog(activityLogEntity, user); - mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id, component id", vspId, componentId); } private void validateProcessExistence(String vspId, Version version, String componentId, String processId, ProcessEntity retrieved) { - mdcDataDebugMessage.debugEntryMessage("VSP id, component id, process id", vspId, componentId, + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id, component id, process id", vspId, componentId, processId); if (retrieved != null) { @@ -250,13 +246,13 @@ public class ProcessManagerImpl implements ProcessManager { new ProcessEntity(vspId, version, componentId, processId), VspDetails.ENTITY_TYPE);//todo retrieved is always null ?? - mdcDataDebugMessage.debugExitMessage("VSP id, component id, process id", vspId, componentId, + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id, component id, process id", vspId, componentId, processId); } private void validateProcessArtifactExistence(String vspId, Version version, String componentId, String processId, ProcessEntity retrieved) { - mdcDataDebugMessage.debugEntryMessage("VSP id, component id, process id", vspId, componentId, + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id, component id, process id", vspId, componentId, processId); if (retrieved != null) { @@ -269,7 +265,7 @@ public class ProcessManagerImpl implements ProcessManager { VspDetails.ENTITY_TYPE); //todo retrieved is always null ?? } - mdcDataDebugMessage.debugExitMessage("VSP id, component id, process id", vspId, componentId, + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id, component id, process id", vspId, componentId, processId); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VendorSoftwareProductManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VendorSoftwareProductManagerImpl.java index be1aaf08e5..d4879da8d7 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VendorSoftwareProductManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VendorSoftwareProductManagerImpl.java @@ -146,25 +146,25 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa private static final String VALIDATION_VSP_NAME = "validationOnlyVspName"; //private static final String VALIDATION_VSP_USER = "validationOnlyVspUser"; - private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); - private static final Logger logger = + private static final MdcDataDebugMessage MDC_DATA_DEBUG_MESSAGE = new MdcDataDebugMessage(); + private static final Logger LOGGER = LoggerFactory.getLogger(VendorSoftwareProductManagerImpl.class); - private OrchestrationTemplateDao orchestrationTemplateDao; - private VendorSoftwareProductInfoDao vspInfoDao; - private VersioningManager versioningManager; - private VendorSoftwareProductDao vendorSoftwareProductDao; - private VendorLicenseFacade vendorLicenseFacade; - private ServiceModelDao<ToscaServiceModel, ServiceElement> serviceModelDao; - private EnrichedServiceModelDao<ToscaServiceModel, ServiceElement> enrichedServiceModelDao; - private HealingManager healingManager; - private VendorLicenseArtifactsService licenseArtifactsService; - private InformationArtifactGenerator informationArtifactGenerator; - private PackageInfoDao packageInfoDao; - private ActivityLogManager activityLogManager; - private DeploymentFlavorDao deploymentFlavorDao; - private NicDao nicDao; - private ManualVspToscaManager manualVspToscaManager; + private final OrchestrationTemplateDao orchestrationTemplateDao; + private final VendorSoftwareProductInfoDao vspInfoDao; + private final VersioningManager versioningManager; + private final VendorSoftwareProductDao vendorSoftwareProductDao; + private final VendorLicenseFacade vendorLicenseFacade; + private final ServiceModelDao<ToscaServiceModel, ServiceElement> serviceModelDao; + private final EnrichedServiceModelDao<ToscaServiceModel, ServiceElement> enrichedServiceModelDao; + private final HealingManager healingManager; + private final VendorLicenseArtifactsService licenseArtifactsService; + private final InformationArtifactGenerator informationArtifactGenerator; + private final PackageInfoDao packageInfoDao; + private final ActivityLogManager activityLogManager; + private final DeploymentFlavorDao deploymentFlavorDao; + private final NicDao nicDao; + private final ManualVspToscaManager manualVspToscaManager; /** * Instantiates a new Vendor software product manager. @@ -230,7 +230,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa @Override public Version checkout(String vendorSoftwareProductId, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id", vendorSoftwareProductId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vendorSoftwareProductId); MDC.put(LoggerConstants.SERVICE_NAME, LoggerServiceName.Checkout_Entity.toString()); Version newVersion = versioningManager @@ -244,14 +244,14 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa activityLogManager.addActionLog(activityLogEntity, user); } - mdcDataDebugMessage.debugExitMessage("VSP id", vendorSoftwareProductId); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vendorSoftwareProductId); return newVersion; } @Override public Version undoCheckout(String vendorSoftwareProductId, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id", vendorSoftwareProductId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vendorSoftwareProductId); Version version = getVersionInfo(vendorSoftwareProductId, VersionableEntityAction.Read, user) @@ -275,14 +275,14 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa updateUniqueName(preVspName, postVspName); - mdcDataDebugMessage.debugExitMessage("VSP id", vendorSoftwareProductId); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vendorSoftwareProductId); return newVersion; } @Override public Version checkin(String vendorSoftwareProductId, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id", vendorSoftwareProductId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vendorSoftwareProductId); Version newVersion = versioningManager.checkin( VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, @@ -295,14 +295,14 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa activityLogManager.addActionLog(activityLogEntity, user); } - mdcDataDebugMessage.debugExitMessage("VSP id", vendorSoftwareProductId); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vendorSoftwareProductId); return newVersion; } @Override public ValidationResponse submit(String vspId, String user) throws IOException { - mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); Version version = getVersionInfo(vspId, VersionableEntityAction.Read, user).getActiveVersion(); VspDetails vspDetails = getVsp(vspId, version, user); @@ -379,7 +379,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa activityLogManager.addActionLog(activityLogEntity, user); } - mdcDataDebugMessage.debugExitMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspId); return validationResponse; } @@ -397,7 +397,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa private Collection<ErrorCode> deploymentFlavorValidation(String vspId, Version version) { - mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); Set<CompositionEntityValidationData> validationData = new HashSet<>(); Collection<ErrorCode> errorCodeList = new ArrayList<>(); Collection<DeploymentFlavorEntity> deploymentFlavors = @@ -451,7 +451,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa } private Set<CompositionEntityValidationData> componentValidation(String vspId, Version version) { - mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); Set<CompositionEntityValidationData> validationData = new HashSet<>(); Collection<ComponentEntity> components = @@ -578,8 +578,8 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa } String getVspQuestionnaireSchema(SchemaTemplateInput schemaInput) { - mdcDataDebugMessage.debugEntryMessage(null); - mdcDataDebugMessage.debugExitMessage(null); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage(null); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage(null); return SchemaGenerator .generate(SchemaTemplateContext.questionnaire, CompositionEntityType.vsp, schemaInput); } @@ -606,7 +606,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa Map<String, List<ErrorMessage>> enrichErrors = enrichmentManager.enrich(); if (MapUtils.isEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, enrichErrors))) { - logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.ENRICHMENT_COMPLETED + LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.ENRICHMENT_COMPLETED + vendorSoftwareProductId); } else { enrichErrors.values().forEach(errorList -> @@ -621,7 +621,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa } private Collection<ErrorCode> validateLicensingData(VspDetails vspDetails) { - mdcDataDebugMessage.debugEntryMessage("VSP id", vspDetails.getId()); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspDetails.getId()); if (vspDetails.getVendorId() == null || vspDetails.getVlmVersion() == null || vspDetails.getLicenseAgreement() == null @@ -629,7 +629,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa return null; } - mdcDataDebugMessage.debugExitMessage("VSP id", vspDetails.getId()); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspDetails.getId()); return vendorLicenseFacade .validateLicensingData(vspDetails.getVendorId(), vspDetails.getVlmVersion(), vspDetails.getLicenseAgreement(), vspDetails.getFeatureGroups()); @@ -640,7 +640,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa try { validateUniqueName(VALIDATION_VSP_NAME); } catch (Exception ignored) { - logger.debug("", ignored); + LOGGER.debug("Ignored exception when validating unique VSP name", ignored); return VALIDATION_VSP_ID; } VspDetails validationVsp = new VspDetails(); @@ -659,7 +659,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa @Override public VspDetails createVsp(VspDetails vspDetails, String user) { - mdcDataDebugMessage.debugEntryMessage(null); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage(null); validateUniqueName(vspDetails.getName()); @@ -679,13 +679,13 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa activityLogManager.addActionLog(activityLogEntity, user); String vspName = vspDetails.getName(); createUniqueName(vspName); - mdcDataDebugMessage.debugExitMessage(null); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage(null); return vspDetails; } @Override public List<VersionedVendorSoftwareProductInfo> listVsps(String versionFilter, String user) { - mdcDataDebugMessage.debugEntryMessage(null); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage(null); Map<String, VersionInfo> idToVersionsInfo = versioningManager.listEntitiesVersionInfo( VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, user, @@ -714,25 +714,23 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa vsps.add(new VersionedVendorSoftwareProductInfo(vsp, versionInfo)); } } catch (RuntimeException rte) { - logger.debug("", rte); - logger.error( + LOGGER.error( "Error trying to retrieve vsp[" + entry.getKey() + "] version[" + version.toString () + "] " + - "message:" + rte - .getMessage()); + "message:" + rte.getMessage(), rte); } } sortVspListByModificationTimeDescOrder(vsps); - mdcDataDebugMessage.debugExitMessage(null); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage(null); return vsps; } @Override public void updateVsp(VspDetails vspDetails, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id", vspDetails.getId()); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspDetails.getId()); VspDetails retrieved = vspInfoDao.get(vspDetails); if (!Objects.equals(retrieved.getOnboardingMethod(), vspDetails.getOnboardingMethod())) { @@ -756,7 +754,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa vspInfoDao.update(vspDetails); //vendorSoftwareProductDao.updateVspLatestModificationTime(vspDetails.getId(), activeVersion); - mdcDataDebugMessage.debugExitMessage("VSP id", vspDetails.getId()); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspDetails.getId()); } private void updateDeploymentFlavor(VspDetails vspDetails, String user) { @@ -785,7 +783,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa @Override public VspDetails getVsp(String vspId, Version version, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); VspDetails vsp = vspInfoDao.get(new VspDetails(vspId, version)); if (vsp == null) { @@ -803,7 +801,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa vsp.setNetworkPackageName("Upload File"); } - mdcDataDebugMessage.debugExitMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspId); return vsp; } @@ -834,31 +832,30 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa public Version healAndAdvanceFinalVersion(String vspId, VspDetails vendorSoftwareProductInfo, String user) throws IOException { - Version checkoutFinalVersion = checkout(vspId, user); - autoHeal(vspId, checkoutFinalVersion, vendorSoftwareProductInfo, user); - Version checkinFinalVersion = checkin(vspId, user); + Version checkoutVersion = checkout(vspId, user); + autoHeal(vspId, checkoutVersion, vendorSoftwareProductInfo, user); + Version checkinVersion = checkin(vspId, user); ValidationResponse response = Objects.requireNonNull(submit(vspId, user), "Null response not expected"); if (!response.isValid()) { - return checkout(vspId, user); + return checkinVersion; } - Version finalVersion = checkinFinalVersion.calculateNextFinal(); + Version finalVersion = checkinVersion.calculateNextFinal(); createPackage(vspId, finalVersion, user); return finalVersion; - } @Override public void deleteVsp(String vspId, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.DELETE_VSP, ErrorLevel.ERROR.name(), LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), "Unsupported operation"); - mdcDataDebugMessage.debugExitMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspId); throw new UnsupportedOperationException( VendorSoftwareProductConstants.UNSUPPORTED_OPERATION_ERROR); @@ -866,7 +863,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa @Override public void heal(String vspId, Version version, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); VersionInfo versionInfo = getVersionInfo(vspId, VersionableEntityAction.Read, user); @@ -882,17 +879,17 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa vspDetails.setOldVersion(null); vspInfoDao.updateOldVersionIndication(vspDetails); - logger.audit("Healed VSP " + vspDetails.getId()); - mdcDataDebugMessage.debugExitMessage("VSP id", vspId); + LOGGER.audit("Healed VSP " + vspDetails.getId()); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspId); - if (errorMessages.isPresent()) { + errorMessages.ifPresent(s -> { throw new CoreException(new ErrorCode.ErrorCodeBuilder().withId("HEALING_ERROR") - .withCategory(ErrorCategory.APPLICATION).withMessage(errorMessages.get()).build()); - } + .withCategory(ErrorCategory.APPLICATION).withMessage(s).build()); + }); } private void autoHeal(String vspId, Version checkoutVersion, VspDetails vspDetails, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); checkoutVersion.setStatus(VersionStatus.Locked); Map<String, Object> healingParams = getHealingParamsAsMap(vspId, checkoutVersion, user); @@ -903,13 +900,13 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa vspDetails.setOldVersion(null); vspInfoDao.updateOldVersionIndication(vspDetails); - logger.audit("Healed VSP " + vspDetails.getName()); - mdcDataDebugMessage.debugExitMessage("VSP id", vspId); + LOGGER.audit("Healed VSP " + vspDetails.getName()); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspId); - if (errorMessages.isPresent()) { + errorMessages.ifPresent(s -> { throw new CoreException(new ErrorCode.ErrorCodeBuilder().withId("HEALING_ERROR") - .withCategory(ErrorCategory.APPLICATION).withMessage(errorMessages.get()).build()); - } + .withCategory(ErrorCategory.APPLICATION).withMessage(s).build()); + }); } private Map<String, Object> getHealingParamsAsMap(String vspId, Version version, String user) { @@ -929,7 +926,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa @Override public File getTranslatedFile(String vspId, Version version, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); String errorMessage; if (version == null) { errorMessage = "Package not found"; @@ -966,10 +963,8 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa File translatedFile = new File(VendorSoftwareProductConstants.VSP_PACKAGE_ZIP); - try { - FileOutputStream fos = new FileOutputStream(translatedFile); + try (FileOutputStream fos = new FileOutputStream(translatedFile)) { fos.write(translatedFileBuffer.array()); - fos.close(); } catch (IOException exception) { errorMessage = "Can't create package"; MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, @@ -979,7 +974,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa exception); } - mdcDataDebugMessage.debugExitMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspId); return translatedFile; } @@ -987,7 +982,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa @Override public byte[] getOrchestrationTemplateFile(String vspId, Version version, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); UploadDataEntity uploadData = orchestrationTemplateDao.getOrchestrationTemplate(vspId, version); ByteBuffer contentData = uploadData.getContentData(); @@ -1008,13 +1003,13 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa throw new CoreException(new FileCreationErrorBuilder(vspId).build(), exception); } - mdcDataDebugMessage.debugExitMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspId); return baos.toByteArray(); } @Override public PackageInfo createPackage(String vspId, Version version, String user) throws IOException { - mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); if (!version.isFinal()) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, @@ -1042,9 +1037,9 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa packageInfoDao.create(packageInfo); - logger.audit(AuditMessages.AUDIT_MSG + AuditMessages.CREATE_PACKAGE + vspId); + LOGGER.audit(AuditMessages.AUDIT_MSG + AuditMessages.CREATE_PACKAGE + vspId); - mdcDataDebugMessage.debugExitMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspId); return packageInfo; } @@ -1065,7 +1060,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa @Override public QuestionnaireResponse getVspQuestionnaire(String vspId, Version version, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); VspQuestionnaireEntity retrieved = vspInfoDao.getQuestionnaire(vspId, version); VersioningUtil.validateEntityExistence(retrieved, new VspQuestionnaireEntity(vspId, version), @@ -1077,7 +1072,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa questionnaireResponse.setData(questionnaireData); questionnaireResponse.setSchema(getVspQuestionnaireSchema(null)); - mdcDataDebugMessage.debugExitMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspId); return questionnaireResponse; } @@ -1085,11 +1080,11 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa @Override public void updateVspQuestionnaire(String vspId, Version version, String questionnaireData, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); vspInfoDao.updateQuestionnaireData(vspId, version, questionnaireData); - mdcDataDebugMessage.debugExitMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspId); } @@ -1107,7 +1102,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa (vspDetails.getOnboardingOrigin()), uploadData.getContentData().array()); - if (vspDetails.getOnboardingOrigin().equals(OnboardingTypesEnum.ZIP.name().toLowerCase())) { + if (CommonUtil.isFileOriginFromZip(vspDetails.getOnboardingOrigin())) { ValidationManager validationManager = ValidationManagerUtil.initValidationManager(fileContentMap); validationErrors.putAll(validationManager.validate()); @@ -1128,7 +1123,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa private QuestionnaireValidationResult validateQuestionnaire(String vspId, Version version, String onboardingMethod) { - mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); // The apis of CompositionEntityDataManager used here are stateful! // so, it must be re-created from scratch when it is used! @@ -1174,18 +1169,18 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa compositionEntityDataManager.getEntityListWithErrors();*/ //Collection<CompositionEntityValidationData> roots = compositionEntityDataManager.getTrees(); - mdcDataDebugMessage.debugExitMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspId); return new QuestionnaireValidationResult( compositionEntityDataManager.getAllErrorsByVsp(vspId)); } - mdcDataDebugMessage.debugExitMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspId); return null; } @Override public File getInformationArtifact(String vspId, Version version, String user) { - mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP id", vspId); VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version)); if (vspDetails == null) { @@ -1202,14 +1197,15 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa infoArtifactFile = new File( String.format(VendorSoftwareProductConstants.INFORMATION_ARTIFACT_NAME, vspName)); - OutputStream out = new BufferedOutputStream(new FileOutputStream(infoArtifactFile)); - out.write(infoArtifactAsByteBuffer.array()); - out.close(); + try (OutputStream out = new BufferedOutputStream(new FileOutputStream(infoArtifactFile))) { + out.write(infoArtifactAsByteBuffer.array()); + } + } catch (IOException ex) { throw new CoreException(new InformationArtifactCreationErrorBuilder(vspId).build(), ex); } - mdcDataDebugMessage.debugExitMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspId); return infoArtifactFile; } @@ -1239,7 +1235,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa errorList.forEach(errorMessage -> { if (errorMessage.getLevel().equals(ErrorLevel.ERROR)) { - logger.audit(AuditMessages.AUDIT_MSG + String.format(auditType, errorMessage.getMessage(), + LOGGER.audit(AuditMessages.AUDIT_MSG + String.format(auditType, errorMessage.getMessage(), vspId)); } }); diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationTemplateCSARHandler.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationTemplateCSARHandler.java index 53d34749e7..db0851cd5f 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationTemplateCSARHandler.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationTemplateCSARHandler.java @@ -22,10 +22,13 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; -import java.util.stream.Stream; import static org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder.getErrorWithParameters; -import static org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.CSARConstants.*; +import static org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.CSARConstants.ELIGBLE_FOLDERS; +import static org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.CSARConstants.ELIGIBLE_FILES; +import static org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.CSARConstants.MAIN_SERVICE_TEMPLATE_MF_FILE_NAME; +import static org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.CSARConstants.MAIN_SERVICE_TEMPLATE_YAML_FILE_NAME; + public class OrchestrationTemplateCSARHandler extends BaseOrchestrationTemplateHandler implements OrchestrationTemplateFileHandler { @@ -59,14 +62,22 @@ public class OrchestrationTemplateCSARHandler extends BaseOrchestrationTemplateH } private void validateManifest(UploadFileResponse uploadFileResponse, FileContentHandler contentMap) { + if (!validateFileExist(uploadFileResponse, contentMap, MAIN_SERVICE_TEMPLATE_MF_FILE_NAME)){ return; } - InputStream fileContent = contentMap.getFileContent(MAIN_SERVICE_TEMPLATE_MF_FILE_NAME); - OnboardingManifest onboardingManifest = new OnboardingManifest(fileContent); - if (!onboardingManifest.isValid()){ - onboardingManifest.getErrors().forEach(error -> uploadFileResponse.addStructureError( - SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, error))); + + try (InputStream fileContent = contentMap.getFileContent(MAIN_SERVICE_TEMPLATE_MF_FILE_NAME)) { + + OnboardingManifest onboardingManifest = new OnboardingManifest(fileContent); + if (!onboardingManifest.isValid()) { + onboardingManifest.getErrors().forEach(error -> uploadFileResponse.addStructureError( + SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, error))); + } + + } catch (IOException e) { + // convert to runtime to keep the throws unchanged + throw new RuntimeException("Failed to validate manifest", e); } } @@ -79,8 +90,6 @@ public class OrchestrationTemplateCSARHandler extends BaseOrchestrationTemplateH SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, getErrorWithParameters(Messages.CSAR_FILES_NOT_ALLOWED.getErrorMessage(), unwantedFile)))); - - ; } } @@ -97,14 +106,11 @@ public class OrchestrationTemplateCSARHandler extends BaseOrchestrationTemplateH } private boolean filterFiles(String inFileName) { boolean valid = ELIGIBLE_FILES.stream().anyMatch(fileName -> fileName.equals(inFileName)); - if (valid){ - return !valid; - } - return filterFolders(inFileName); + return !valid && filterFolders(inFileName); } private boolean filterFolders(String fileName) { - return !ELIGBLE_FOLDERS.stream().anyMatch(dirName -> fileName.startsWith(dirName)); + return ELIGBLE_FOLDERS.stream().noneMatch(fileName::startsWith); } private boolean validateFileExist(UploadFileResponse uploadFileResponse, FileContentHandler contentMap, String fileName) { diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationUploadFactory.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationUploadFactory.java index 85f92662ea..99b311e473 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationUploadFactory.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationUploadFactory.java @@ -3,9 +3,12 @@ package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration; import org.openecomp.config.api.Configuration; import org.openecomp.config.api.ConfigurationManager; import org.openecomp.core.utilities.CommonMethods; +import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration; +import org.openecomp.sdc.vendorsoftwareproduct.dao.errors.OrchestrationTemplateFileExtensionErrorBuilder; import java.util.Map; +import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import static org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.OrchestrationUtil.ORCHESTRATION_CONFIG_NAMESPACE; @@ -22,7 +25,14 @@ public class OrchestrationUploadFactory { } public static final OrchestrationTemplateFileHandler createOrchestrationTemplateFileHandler(String filePrefix) { - ImplementationConfiguration orchestrationTemplateFileHandler = fileHanlders.get(filePrefix); + String fileExtension = filePrefix.toLowerCase(); + ImplementationConfiguration orchestrationTemplateFileHandler = fileHanlders.get(fileExtension); + + if(Objects.isNull(orchestrationTemplateFileHandler)){ + throw new CoreException(new OrchestrationTemplateFileExtensionErrorBuilder + ().build()); + } + return CommonMethods.newInstance(orchestrationTemplateFileHandler.getImplementationClass(), OrchestrationTemplateFileHandler.class); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/process/OrchestrationProcessFactory.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/process/OrchestrationProcessFactory.java index db43e0084e..516d85c2a7 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/process/OrchestrationProcessFactory.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/process/OrchestrationProcessFactory.java @@ -28,11 +28,11 @@ public class OrchestrationProcessFactory { } public static Optional<OrchestrationTemplateProcessHandler> getInstance(String filePrefix) { - filePrefix = filePrefix == null ? null : filePrefix.toLowerCase().trim(); if (filePrefix == null) { return Optional.empty(); } + filePrefix = filePrefix.toLowerCase().trim(); OnboardingTypesEnum onboardingTypesEnum = OnboardingTypesEnum.getOnboardingTypesEnum(filePrefix); if (onboardingTypesEnum == null) { return Optional.empty(); diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/QuestionnaireDataServiceTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/QuestionnaireDataServiceTest.java index 3e42a23c6a..b544d13ec7 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/QuestionnaireDataServiceTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/QuestionnaireDataServiceTest.java @@ -49,6 +49,7 @@ import org.openecomp.sdc.versioning.dao.types.Version; import org.testng.Assert; import org.testng.annotations.BeforeMethod; +import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Objects; @@ -81,7 +82,7 @@ public class QuestionnaireDataServiceTest { @InjectMocks private OrchestrationTemplateCandidateManagerImpl candidateManager; - private UploadFileTest uploadFileTest = new UploadFileTest(); + private final UploadFileTest uploadFileTest = new UploadFileTest(); private static String vspId; private static Version vspActiveVersion; @@ -93,7 +94,7 @@ public class QuestionnaireDataServiceTest { } // TODO: 3/15/2017 fix and enable //@Test - public void testQuestionnaireDataAfterLegalUploadWithComposition() { + public void testQuestionnaireDataAfterLegalUploadWithComposition() throws IOException { InformationArtifactData informationArtifactData = uploadFileAndValidateInformationArtifactData("/fullComposition", 5); @@ -102,16 +103,18 @@ public class QuestionnaireDataServiceTest { // TODO: 3/15/2017 fix and enable //@Test - public void testQuestionnaireDataAfterLegalUploadEmptyComposition() { + public void testQuestionnaireDataAfterLegalUploadEmptyComposition() throws IOException { uploadFileAndValidateInformationArtifactData("/emptyComposition", 0); } // TODO: 3/15/2017 fix and enable //@Test - public void testQuestionnaireDataAfterIllegalUpload() { - InputStream zipInputStream = uploadFileTest.getZipInputStream("/missingYml"); - UploadFileResponse uploadFileResponse = candidateManager - .upload(vspId, VERSION, zipInputStream, USER1, "zip", "missingYml"); + public void testQuestionnaireDataAfterIllegalUpload() throws IOException { + + try (InputStream zipInputStream = uploadFileTest.getZipInputStream("/missingYml")) { + UploadFileResponse uploadFileResponse = candidateManager + .upload(vspId, VERSION, zipInputStream, USER1, "zip", "missingYml"); + } InformationArtifactData informationArtifactData = questionnaireDataService .generateQuestionnaireDataForInformationArtifact(vspId, vspActiveVersion); @@ -119,15 +122,18 @@ public class QuestionnaireDataServiceTest { } private InformationArtifactData uploadFileAndValidateInformationArtifactData(String filePath, - int listSizeToCheck) { - InputStream zipInputStream = uploadFileTest.getZipInputStream(filePath); - UploadFileResponse uploadFileResponse = candidateManager - .upload(vspId, VERSION, - zipInputStream, USER1,"zip", "file"); - candidateManager.process(vspId, VERSION, USER1); - - Assert.assertTrue(MapUtils.isEmpty( - MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, uploadFileResponse.getErrors()))); + int listSizeToCheck) throws IOException { + + try (InputStream zipInputStream = uploadFileTest.getZipInputStream(filePath)) { + UploadFileResponse uploadFileResponse = candidateManager + .upload(vspId, VERSION, + zipInputStream, USER1, "zip", "file"); + + candidateManager.process(vspId, VERSION, USER1); + + Assert.assertTrue(MapUtils.isEmpty( + MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, uploadFileResponse.getErrors()))); + } InformationArtifactData informationArtifactData = questionnaireDataService .generateQuestionnaireDataForInformationArtifact(vspId, vspActiveVersion); diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/MonitoringUploadsManagerImplTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/MonitoringUploadsManagerImplTest.java index e4dd39cfda..966e1f20bf 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/MonitoringUploadsManagerImplTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/MonitoringUploadsManagerImplTest.java @@ -5,8 +5,6 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.openecomp.core.enrichment.types.MonitoringUploadType; import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentArtifactDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentMonitoringUploadEntity; import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.MonitoringUploadStatus; @@ -20,6 +18,7 @@ import java.io.InputStream; import java.net.URL; import java.util.Arrays; import java.util.Optional; +import java.util.function.Consumer; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyObject; @@ -29,25 +28,23 @@ import static org.mockito.Mockito.verify; public class MonitoringUploadsManagerImplTest { - private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); - private static final String USER1 = "ComponentsUploadTestUser"; private static final String COMPONENT_ID = "COMPONENT_ID"; private static final String VSP_ID = "vspId"; private static final Version VERSION = new Version(0, 1); - private static final String trapFileName = "MMSC.zip"; - private static final String pollFileName = "MNS OAM FW.zip"; - private static final String vesFileName = "vesTest-yml_only.zip"; - private static final String invalidVesFileName = "invalid_ves_file.zip"; - private static final String notZipFileName = "notZipFile"; - private static final String zipWithFoldersFileName = "zipFileWithFolder.zip"; - private static final String emptyZipFileName = "emptyZip.zip"; + private static final String TRAP_FILE_NAME = "MMSC.zip"; + private static final String POLL_FILE_NAME = "MNS OAM FW.zip"; + private static final String VES_FILE_NAME = "vesTest-yml_only.zip"; + private static final String INVALID_VES_FILE_NAME = "invalid_ves_file.zip"; + private static final String NOT_ZIP_FILE_NAME = "notZipFile"; + private static final String ZIP_WITH_FOLDERS_FILE_NAME = "zipFileWithFolder.zip"; + private static final String EMPTY_ZIP_FILE_NAME = "emptyZip.zip"; private static final String ZIP_DIR = "/vspmanager/zips/"; @Mock private ComponentArtifactDao componentArtifactDaoMock; @InjectMocks - private MonitoringUploadsManagerImpl moitoringUploadsManager; + private MonitoringUploadsManagerImpl monitoringUploadsManager; @BeforeMethod public void setUp() throws Exception { @@ -56,51 +53,47 @@ public class MonitoringUploadsManagerImplTest { @Test(expectedExceptions = CoreException.class) public void testUploadEmptyZip() { - InputStream zis = getFileInputStream(ZIP_DIR + emptyZipFileName); - moitoringUploadsManager.upload(zis, emptyZipFileName, VSP_ID, VERSION, COMPONENT_ID, - MonitoringUploadType.SNMP_TRAP, USER1); + processFile(ZIP_DIR + EMPTY_ZIP_FILE_NAME, inputStream -> + monitoringUploadsManager.upload(inputStream, EMPTY_ZIP_FILE_NAME, VSP_ID, VERSION, COMPONENT_ID, + MonitoringUploadType.SNMP_TRAP, USER1)); } @Test public void testUploadInvalidZip() { - URL url = this.getClass().getResource("/notZipFile"); + try { - moitoringUploadsManager - .upload(url.openStream(), notZipFileName, VSP_ID, VERSION, COMPONENT_ID, - MonitoringUploadType.VES_EVENTS, USER1); + processFile("/notZipFile", inputStream -> + monitoringUploadsManager + .upload(inputStream, NOT_ZIP_FILE_NAME, VSP_ID, VERSION, COMPONENT_ID, + MonitoringUploadType.VES_EVENTS, USER1)); Assert.fail(); } catch (Exception exception) { - log.debug("",exception); Assert.assertEquals(exception.getMessage(), "Invalid zip file"); } } @Test public void testUploadZipWithFolders() { - InputStream zis = getFileInputStream(ZIP_DIR + zipWithFoldersFileName); try { - moitoringUploadsManager - .upload(zis, zipWithFoldersFileName, VSP_ID, VERSION, COMPONENT_ID, - MonitoringUploadType.SNMP_TRAP, USER1); + processFile(ZIP_DIR + ZIP_WITH_FOLDERS_FILE_NAME, inputStream -> monitoringUploadsManager + .upload(inputStream, ZIP_WITH_FOLDERS_FILE_NAME, VSP_ID, VERSION, COMPONENT_ID, + MonitoringUploadType.SNMP_TRAP, USER1)); Assert.fail(); } catch (Exception exception) { - log.debug("",exception); Assert.assertEquals(exception.getMessage(), "Zip file should not contain folders"); } } @Test public void testUploadVEsEventZipWithNonYamlFiles() { - InputStream zis = getFileInputStream(ZIP_DIR + invalidVesFileName); try { - moitoringUploadsManager - .upload(zis, invalidVesFileName, VSP_ID, VERSION, COMPONENT_ID, - MonitoringUploadType.VES_EVENTS, USER1); + processFile(ZIP_DIR + INVALID_VES_FILE_NAME, inputStream -> monitoringUploadsManager + .upload(inputStream, INVALID_VES_FILE_NAME, VSP_ID, VERSION, COMPONENT_ID, + MonitoringUploadType.VES_EVENTS, USER1)); Assert.fail(); } catch (Exception exception) { - log.debug("",exception); Assert.assertEquals(exception.getMessage(), "Wrong VES EVENT Artifact was uploaded - all files contained in Artifact must be YAML " + "files (using .yaml/.yml extensions)"); @@ -113,33 +106,33 @@ public class MonitoringUploadsManagerImplTest { ComponentMonitoringUploadEntity artifact1 = new ComponentMonitoringUploadEntity(VSP_ID, VERSION, COMPONENT_ID, "artifact1"); artifact1.setType(MonitoringUploadType.SNMP_TRAP); - artifact1.setArtifactName(trapFileName); + artifact1.setArtifactName(TRAP_FILE_NAME); ComponentMonitoringUploadEntity artifact2 = new ComponentMonitoringUploadEntity(VSP_ID, VERSION, COMPONENT_ID, "artifact2"); artifact2.setType(MonitoringUploadType.SNMP_POLL); - artifact2.setArtifactName(pollFileName); + artifact2.setArtifactName(POLL_FILE_NAME); ComponentMonitoringUploadEntity artifact3 = new ComponentMonitoringUploadEntity(VSP_ID, VERSION, COMPONENT_ID, "artifact3"); artifact3.setType(MonitoringUploadType.VES_EVENTS); - artifact3.setArtifactName(vesFileName); + artifact3.setArtifactName(VES_FILE_NAME); doReturn(Arrays.asList(artifact1, artifact2, artifact3)) .when(componentArtifactDaoMock).list(anyObject()); MonitoringUploadStatus monitoringUploadStatus = - moitoringUploadsManager.listFilenames(VSP_ID, VERSION, COMPONENT_ID, USER1); + monitoringUploadsManager.listFilenames(VSP_ID, VERSION, COMPONENT_ID, USER1); - Assert.assertEquals(monitoringUploadStatus.getSnmpTrap(), trapFileName); - Assert.assertEquals(monitoringUploadStatus.getSnmpPoll(), pollFileName); - Assert.assertEquals(monitoringUploadStatus.getVesEvent(), vesFileName); + Assert.assertEquals(monitoringUploadStatus.getSnmpTrap(), TRAP_FILE_NAME); + Assert.assertEquals(monitoringUploadStatus.getSnmpPoll(), POLL_FILE_NAME); + Assert.assertEquals(monitoringUploadStatus.getVesEvent(), VES_FILE_NAME); } @Test (expectedExceptions = CoreException.class) public void testDeleteComponentMibWhenNone() { doReturn(Optional.empty()).when(componentArtifactDaoMock).getByType(any()); - moitoringUploadsManager + monitoringUploadsManager .delete(VSP_ID, VERSION, COMPONENT_ID, MonitoringUploadType.SNMP_POLL, USER1); verify(componentArtifactDaoMock, never()).delete(anyObject()); @@ -152,20 +145,20 @@ public class MonitoringUploadsManagerImplTest { .when (componentArtifactDaoMock).getByType(anyObject()); - moitoringUploadsManager + monitoringUploadsManager .delete(VSP_ID, VERSION, COMPONENT_ID, MonitoringUploadType.SNMP_POLL, USER1); verify(componentArtifactDaoMock).delete(anyObject()); } - private InputStream getFileInputStream(String fileName) { + private void processFile(String fileName, Consumer<InputStream> processor) { + URL url = this.getClass().getResource(fileName); - try { - return url.openStream(); - } catch (IOException exception) { - log.debug("",exception); - return null; + try (InputStream inputStream = url.openStream()) { + processor.accept(inputStream); + } catch (IOException e) { + throw new RuntimeException("Failed to process file: " + fileName, e); } } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VendorSoftwareProductManagerImplTest.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VendorSoftwareProductManagerImplTest.java index 77a847a2af..5199dfd365 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VendorSoftwareProductManagerImplTest.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VendorSoftwareProductManagerImplTest.java @@ -104,12 +104,12 @@ import static org.mockito.Mockito.verify; public class VendorSoftwareProductManagerImplTest { - private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); + private static final Logger LOG = LoggerFactory.getLogger(VendorSoftwareProductManagerImplTest.class); private static final String INVALID_VERSION_MSG = "Invalid requested version."; - private static String VSP_ID = "vspId"; - private static String VERSION_ID = "versionId"; + private static final String VSP_ID = "vspId"; + private static final String VERSION_ID = "versionId"; public static final Version VERSION01 = new Version(0, 1); private static final Version VERSION10 = new Version(1, 0); private static final String USER1 = "vspTestUser1"; @@ -348,14 +348,14 @@ public class VendorSoftwareProductManagerImplTest { doReturn(versionInfo).when(versioningManagerMock).getEntityVersionInfo( VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE, VSP_ID, USER1, VersionableEntityAction.Write); - List<String> fgs = new ArrayList<String>(); + List<String> fgs = new ArrayList<>(); fgs.add("fg1"); fgs.add("fg2"); VspDetails existingVsp = createVspDetails(VSP_ID, VERSION01, "VSP1", null, "vendorName", "vlm1Id", "icon", "category", "subCategory", "456", fgs); - List<String> updFgs = new ArrayList<String>(); + List<String> updFgs = new ArrayList<>(); updFgs.add("fg2"); VspDetails updatedVsp = createVspDetails(VSP_ID, VERSION01, "VSP1_updated", null, "vendorName", "vlm1Id", "icon", @@ -372,7 +372,7 @@ public class VendorSoftwareProductManagerImplTest { flavor.setFeatureGroupId("fg1"); dfEntity.setDeploymentFlavorCompositionData(flavor); - List<DeploymentFlavorEntity> dfList = new ArrayList<DeploymentFlavorEntity>(); + List<DeploymentFlavorEntity> dfList = new ArrayList<>(); dfList.add(dfEntity); doReturn(dfList).when(deploymentFlavorDaoMock).list(anyObject()); @@ -561,7 +561,7 @@ public class VendorSoftwareProductManagerImplTest { doReturn(vsp).when(vspInfoDaoMock).get(anyObject()); UploadDataEntity uploadData = new UploadDataEntity(VSP_ID, VERSION01); uploadData.setContentData( - ByteBuffer.wrap(FileUtils.toByteArray(getFileInputStream("/emptyComposition")))); + ByteBuffer.wrap(getBytes("/emptyComposition"))); doReturn(uploadData).when(orchestrationTemplateDataDaoMock) .getOrchestrationTemplate(anyObject(), anyObject()); doReturn(new ToscaServiceModel(new FileContentHandler(), new HashMap<>(), @@ -597,7 +597,7 @@ public class VendorSoftwareProductManagerImplTest { doReturn(vsp).when(vspInfoDaoMock).get(anyObject()); UploadDataEntity uploadData = new UploadDataEntity(VSP_ID, VERSION01); uploadData.setContentData( - ByteBuffer.wrap(FileUtils.toByteArray(getFileInputStream("/emptyComposition")))); + ByteBuffer.wrap(getBytes("/emptyComposition"))); doReturn(uploadData).when(orchestrationTemplateDataDaoMock) .getOrchestrationTemplate(anyObject(), anyObject()); doReturn(new ToscaServiceModel(new FileContentHandler(), new HashMap<>(), @@ -654,27 +654,28 @@ public class VendorSoftwareProductManagerImplTest { // TODO: 3/15/2017 fix and enable //@Test(dependsOnMethods = {"testListFinals"}) - public void testUploadFileMissingFile() { - InputStream zis = getFileInputStream("/vspmanager/zips/missingYml.zip"); + public void testUploadFileMissingFile() throws IOException { - UploadFileResponse uploadFileResponse = - candidateManager.upload(VSP_ID, VERSION01, zis, USER1, "zip", "missingYml"); + try (InputStream zis = this.getClass().getResourceAsStream("/vspmanager/zips/missingYml.zip")) { + UploadFileResponse uploadFileResponse = + candidateManager.upload(VSP_ID, VERSION01, zis, USER1, "zip", "missingYml"); - Assert.assertEquals(uploadFileResponse.getErrors().size(), 0); + Assert.assertEquals(uploadFileResponse.getErrors().size(), 0); + } } // TODO: 3/15/2017 fix and enable //@Test(dependsOnMethods = {"testUploadFileMissingFile"}) public void testUploadNotZipFile() throws IOException { + URL url = this.getClass().getResource("/notZipFile"); - try { + try (InputStream inputStream = url.openStream()) { candidateManager .upload(VSP_ID, VERSION01, - url.openStream(), USER1, "zip", "notZipFile"); + inputStream, USER1, "zip", "notZipFile"); candidateManager.process(VSP_ID, VERSION01, USER1); } catch (Exception ce) { - log.debug("",ce); Assert.assertEquals(ce.getMessage(), Messages.CREATE_MANIFEST_FROM_ZIP.getErrorMessage()); } @@ -692,11 +693,12 @@ public class VendorSoftwareProductManagerImplTest { private List<String> getFileNamesFromFolderInCsar(File csar, String folderName) throws IOException { + List<String> fileNames = new ArrayList<>(); - FileInputStream fileInputStream = new FileInputStream(csar); - try { - ZipInputStream zip = new ZipInputStream(fileInputStream); + try (FileInputStream fileInputStream = new FileInputStream(csar); + ZipInputStream zip = new ZipInputStream(fileInputStream)) { + ZipEntry ze; while ((ze = zip.getNextEntry()) != null) { @@ -705,8 +707,6 @@ public class VendorSoftwareProductManagerImplTest { fileNames.add(name); } } - }finally { - fileInputStream.close(); } return fileNames; @@ -718,10 +718,13 @@ public class VendorSoftwareProductManagerImplTest { checkinSubmitCreatePackage(vspId, user); } - private void uploadFileAndProcess(String vspId, String user, String filePath) { + private void uploadFileAndProcess(String vspId, String user, String filePath) throws IOException { vendorSoftwareProductManager.checkout(vspId, user); - candidateManager.upload(vspId, VERSION01, getFileInputStream(filePath), user, "zip", "file"); - candidateManager.process(vspId, VERSION01, user); + + try (InputStream inputStream = this.getClass().getResourceAsStream(filePath)) { + candidateManager.upload(vspId, VERSION01, inputStream, user, "zip", "file"); + candidateManager.process(vspId, VERSION01, user); + } } private void checkinSubmitCreatePackage(String vspId, String user) throws IOException { @@ -792,13 +795,10 @@ public class VendorSoftwareProductManagerImplTest { capabilities.put(entryValueKey + "_" + key, value); } - public InputStream getFileInputStream(String fileName) { + private byte[] getBytes(String fileName) throws IOException { URL url = this.getClass().getResource(fileName); - try { - return url.openStream(); - } catch (IOException exception) { - exception.printStackTrace(); - return null; + try (InputStream inputStream = url.openStream()) { + return FileUtils.toByteArray(inputStream); } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/utils/VSPCommon.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/utils/VSPCommon.java index 947f33922e..8f87c40cc1 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/utils/VSPCommon.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/utils/VSPCommon.java @@ -21,8 +21,6 @@ package org.openecomp.sdc.vendorsoftwareproduct.utils; import org.openecomp.core.utilities.file.FileUtils; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.versioning.dao.types.Version; @@ -37,8 +35,6 @@ import java.util.zip.ZipOutputStream; public class VSPCommon { - private static final Logger log = (Logger) LoggerFactory.getLogger(VSPCommon.class.getName()); - public static VspDetails createVspDetails(String id, Version version, String name, String desc, String vendorName, String vlm, String icon, String category, String subCategory, @@ -86,18 +82,18 @@ public class VSPCommon { } } else { - try { if (!path.isEmpty()) { path += File.separator; } - zos.putNextEntry(new ZipEntry(path + file.getName())); - InputStream is = new FileInputStream(file); - byte[] data = FileUtils.toByteArray(is); - zos.write(data); - zos.closeEntry(); - } catch (IOException exception) { - log.debug("",exception); - } + + try (InputStream is = new FileInputStream(file)) { + zos.putNextEntry(new ZipEntry(path + file.getName())); + byte[] data = FileUtils.toByteArray(is); + zos.write(data); + zos.closeEntry(); + } catch (IOException exception) { + throw new RuntimeException("Failed to create Zip entry for file: " + file, exception); + } } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/utils/ZipFileUtils.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/utils/ZipFileUtils.java index b2a6f2fe87..b5f57e9f77 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/utils/ZipFileUtils.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/utils/ZipFileUtils.java @@ -20,9 +20,6 @@ package org.openecomp.sdc.vendorsoftwareproduct.utils; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -36,20 +33,20 @@ import java.util.zip.ZipOutputStream; * @since November 08, 2016 */ public class ZipFileUtils { - private static final Logger log = (Logger) LoggerFactory.getLogger(ZipFileUtils.class.getName()); + public InputStream getZipInputStream(String name) { + URL url = getClass().getResource(name); File templateDir = new File(url.getFile()); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ZipOutputStream zos = new ZipOutputStream(baos); + try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ZipOutputStream zos = new ZipOutputStream(baos)) { + + VSPCommon.zipDir(templateDir, "", zos, true); + return new ByteArrayInputStream(baos.toByteArray()); - VSPCommon.zipDir(templateDir, "", zos, true); - try { - zos.close(); } catch (IOException exception) { - log.debug("",exception); + throw new RuntimeException("Failed to read from Zip file: " + name, exception); } - return new ByteArrayInputStream(baos.toByteArray()); } } diff --git a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/utils/CommonUtil.java b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/utils/CommonUtil.java index 1c5293004d..72485d7162 100644 --- a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/utils/CommonUtil.java +++ b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/utils/CommonUtil.java @@ -42,6 +42,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; +import java.util.Objects; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; @@ -67,7 +68,7 @@ public class CommonUtil { throws IOException { Pair<FileContentHandler,List<String> > pair = getFileContentMapFromOrchestrationCandidateZip(uploadFileData); - if(type.equals(OnboardingTypesEnum.ZIP)) { + if(isFileOriginFromZip(type.toString())) { validateNoFolders(pair.getRight()); } @@ -133,7 +134,7 @@ public class CommonUtil { return -1; } - public static boolean validateFilesExtensions(Set<String> allowedExtensions, FileContentHandler + private static boolean validateFilesExtensions(Set<String> allowedExtensions, FileContentHandler files) { for (String fileName : files.getFileList()) { if (!allowedExtensions.contains(FilenameUtils.getExtension(fileName))) { @@ -147,4 +148,9 @@ public class CommonUtil { Set<String> allowedExtensions = new HashSet<>(Arrays.asList("yml", "yaml")); return validateFilesExtensions(allowedExtensions, files); } + + public static boolean isFileOriginFromZip(String fileOrigin){ + return Objects.nonNull(fileOrigin) + && fileOrigin.toLowerCase().equals(OnboardingTypesEnum.ZIP.toString()); + } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileContentHandler.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileContentHandler.java index 8de222e688..d5cd56e058 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileContentHandler.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileContentHandler.java @@ -23,10 +23,13 @@ package org.openecomp.core.utilities.file; import org.apache.commons.collections4.MapUtils; import java.io.ByteArrayInputStream; +import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; +import java.util.Optional; import java.util.Set; +import java.util.function.Function; public class FileContentHandler { @@ -45,12 +48,31 @@ public class FileContentHandler { return null; } - ByteArrayInputStream is = new ByteArrayInputStream(content); - return is; + return new ByteArrayInputStream(content); } - public void addFile(String fileName, byte[] contect) { - files.put(fileName, contect); + /** + * Applies a business logic to a file's content while taking care of all retrieval logic. + * + * @param fileName name of a file inside this content handler. + * @param processor the business logic to work on the file's input stream, which may not be set + * (check the {@link Optional} if no such file can be found + * @param <T> return type, may be {@link java.lang.Void} + * + * @return result produced by the processor + */ + public <T> T processFileContent(String fileName, Function<Optional<InputStream>, T> processor) { + + // do not throw IOException to mimic the existing uses of getFileContent() + try (InputStream contentInputStream = getFileContent(fileName)) { + return processor.apply(Optional.ofNullable(contentInputStream)); + } catch (IOException e) { + throw new ProcessingException("Failed to process file: " + fileName, e); + } + } + + public void addFile(String fileName, byte[] content) { + files.put(fileName, content); } public void addFile(String fileName, InputStream is) { @@ -94,4 +116,26 @@ public class FileContentHandler { public boolean containsFile(String fileName) { return files.containsKey(fileName); } + + /** + * An application-specific runtime exception + */ + private static class ProcessingException extends RuntimeException { + + public ProcessingException() { + super(); + } + + public ProcessingException(String message) { + super(message); + } + + public ProcessingException(Throwable cause) { + super(cause); + } + + public ProcessingException(String msg, Throwable cause) { + super(msg, cause); + } + } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/orchestration/OnboardingTypesEnum.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/orchestration/OnboardingTypesEnum.java index 04e64c33a9..85fe305060 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/orchestration/OnboardingTypesEnum.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/orchestration/OnboardingTypesEnum.java @@ -20,13 +20,11 @@ public enum OnboardingTypesEnum { if (inStr == null) { return null; } + Optional<OnboardingTypesEnum> onboardingTypesOptional = asList(OnboardingTypesEnum.values()).stream() - .filter(onboardingTypesEnum -> onboardingTypesEnum.toString().equals(inStr)).findAny(); - if( onboardingTypesOptional.isPresent()){ - return onboardingTypesOptional.get(); - }else { - return null; - } + .filter(onboardingTypesEnum -> onboardingTypesEnum.toString().equals(inStr.toLowerCase())) + .findAny(); + return onboardingTypesOptional.orElse(null); } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/file/FileContentHandlerTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/file/FileContentHandlerTest.java new file mode 100644 index 0000000000..527ba22c1d --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/file/FileContentHandlerTest.java @@ -0,0 +1,53 @@ +package org.openecomp.core.utilities.file; + +import org.testng.annotations.Test; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Optional; + +import static org.testng.Assert.*; + +/** + * @author EVITALIY + * @since 24 Oct 17 + */ +public class FileContentHandlerTest { + + private static final String FILE_NAME = "test-file.txt"; + + @Test + public void testProcessFileContent() throws Exception { + + final int size = 13; + FileContentHandler contentHandler = new FileContentHandler(); + final byte[] content = new byte[size]; + Arrays.fill(content, (byte) 44); + contentHandler.addFile(FILE_NAME, content); + assertEquals(contentHandler.processFileContent(FILE_NAME, optional -> { + + try { + byte[] buffer = new byte[size]; + assertTrue(optional.isPresent()); + assertEquals(size, optional.get().read(buffer)); + return buffer; + } catch (IOException e) { + throw new RuntimeException("Unexpected error", e); + } + + }), content); + } + + @Test + public void testProcessEmptyFileContent() throws Exception { + FileContentHandler contentHandler = new FileContentHandler(); + contentHandler.addFile(FILE_NAME, new byte[0]); + assertFalse(contentHandler.processFileContent(FILE_NAME, Optional::isPresent)); + } + + @Test + public void testProcessNoFileContent() throws Exception { + FileContentHandler contentHandler = new FileContentHandler(); + assertFalse(contentHandler.processFileContent("filename", Optional::isPresent)); + } +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-heat-lib/src/test/java/org/openecomp/sdc/heat/datatypes/model/EnvironmentTest.java b/openecomp-be/lib/openecomp-heat-lib/src/test/java/org/openecomp/sdc/heat/datatypes/model/EnvironmentTest.java index fc01e2e8b0..6312e5a575 100644 --- a/openecomp-be/lib/openecomp-heat-lib/src/test/java/org/openecomp/sdc/heat/datatypes/model/EnvironmentTest.java +++ b/openecomp-be/lib/openecomp-heat-lib/src/test/java/org/openecomp/sdc/heat/datatypes/model/EnvironmentTest.java @@ -23,16 +23,18 @@ package org.openecomp.sdc.heat.datatypes.model; import org.junit.Test; import org.openecomp.sdc.tosca.services.YamlUtil; +import java.io.IOException; import java.io.InputStream; public class EnvironmentTest { @Test - public void testYamlToServiceTemplateObj() { + public void testYamlToServiceTemplateObj() throws IOException { YamlUtil yamlUtil = new YamlUtil(); - InputStream yamlFile = yamlUtil.loadYamlFileIs("/mock/model/envSettings.env"); - Environment envVars = yamlUtil.yamlToObject(yamlFile, Environment.class); - envVars.toString(); + try (InputStream yamlFile = yamlUtil.loadYamlFileIs("/mock/model/envSettings.env")) { + Environment envVars = yamlUtil.yamlToObject(yamlFile, Environment.class); + envVars.toString(); + } } @Test @@ -46,9 +48,8 @@ public class EnvironmentTest { if (heatResourceName.length() == lastIndexOfUnderscore) { System.out.println(heatResourceName); } else { - String heatResourceNameSuffix = heatResourceName.substring(lastIndexOfUnderscore + 1); + try { - int heatResourceNameSuffixInt = Integer.parseInt(heatResourceNameSuffix); System.out.println(heatResourceName.substring(0, lastIndexOfUnderscore)); } catch (NumberFormatException ignored) { System.out.println(heatResourceName); diff --git a/openecomp-be/lib/openecomp-heat-lib/src/test/java/org/openecomp/sdc/heat/datatypes/model/HeatOrchestrationTemplateTest.java b/openecomp-be/lib/openecomp-heat-lib/src/test/java/org/openecomp/sdc/heat/datatypes/model/HeatOrchestrationTemplateTest.java index 3715b0f999..dd8abdc0b9 100644 --- a/openecomp-be/lib/openecomp-heat-lib/src/test/java/org/openecomp/sdc/heat/datatypes/model/HeatOrchestrationTemplateTest.java +++ b/openecomp-be/lib/openecomp-heat-lib/src/test/java/org/openecomp/sdc/heat/datatypes/model/HeatOrchestrationTemplateTest.java @@ -26,6 +26,7 @@ import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.tosca.services.YamlUtil; +import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; @@ -37,12 +38,13 @@ public class HeatOrchestrationTemplateTest { private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); @Test - public void testYamlToServiceTemplateObj() { + public void testYamlToServiceTemplateObj() throws IOException { YamlUtil yamlUtil = new YamlUtil(); - InputStream yamlFile = yamlUtil.loadYamlFileIs("/mock/model/testHeat.yml"); - HeatOrchestrationTemplate heatOrchestrationTemplate = - yamlUtil.yamlToObject(yamlFile, HeatOrchestrationTemplate.class); - heatOrchestrationTemplate.toString(); + try (InputStream yamlFile = yamlUtil.loadYamlFileIs("/mock/model/testHeat.yml")) { + HeatOrchestrationTemplate heatOrchestrationTemplate = + yamlUtil.yamlToObject(yamlFile, HeatOrchestrationTemplate.class); + heatOrchestrationTemplate.toString(); + } } @Test diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java index a0034a3828..ddbcaf72b9 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java @@ -25,14 +25,12 @@ import org.openecomp.config.api.ConfigurationManager; import org.openecomp.core.utilities.CommonMethods; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.heat.datatypes.manifest.ManifestFile; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.services.ToscaUtil; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; @@ -42,6 +40,7 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolida import org.openecomp.sdc.translator.services.heattotosca.ConfigConstants; import org.openecomp.sdc.translator.services.heattotosca.Constants; import org.openecomp.sdc.translator.services.heattotosca.NameExtractor; +import org.openecomp.sdc.translator.services.heattotosca.errors.DuplicateResourceIdsInDifferentFilesErrorBuilder; import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator; import java.io.InputStream; @@ -385,10 +384,7 @@ public class TranslationContext { } if(nodeAbstractNodeTemplateIdMap.containsKey(originalNodeTemplateId)){ - throw new CoreException((new ErrorCode.ErrorCodeBuilder()) - .withMessage("Resource with id " - + originalNodeTemplateId + " occures more than once in different addOn files") - .build()); + throw new CoreException(new DuplicateResourceIdsInDifferentFilesErrorBuilder(originalNodeTemplateId).build()); } nodeAbstractNodeTemplateIdMap.put(originalNodeTemplateId, abstractNodeTemplateId); this.getUnifiedSubstitutionData().get(serviceTemplateFileName).setNodesRelatedAbstractNode( diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtil.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtil.java index b86038d175..5d1bb1c61e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtil.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtil.java @@ -31,6 +31,7 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolida import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.PortTemplateConsolidationData; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.RequirementAssignmentData; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.TypeComputeConsolidationData; +import org.openecomp.sdc.translator.services.heattotosca.errors.DuplicateResourceIdsInDifferentFilesErrorBuilder; import java.util.ArrayList; import java.util.Collection; @@ -154,10 +155,7 @@ public class ConsolidationDataUtil { if(isNestedResourceIdOccuresInDifferentNestedFiles(context, nestedHeatFileName, nestedNodeTemplateId)){ - throw new CoreException((new ErrorCode.ErrorCodeBuilder()) - .withMessage("Resource with id " - + nestedNodeTemplateId + " occures more than once in different addOn " - + "files").build()); + throw new CoreException(new DuplicateResourceIdsInDifferentFilesErrorBuilder(nestedNodeTemplateId).build()); } ConsolidationData consolidationData = context.getConsolidationData(); diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationService.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationService.java index 16a6301968..d3f2a721c9 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationService.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationService.java @@ -24,6 +24,7 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolida import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.PortTemplateConsolidationData; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.RequirementAssignmentData; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.TypeComputeConsolidationData; +import org.openecomp.sdc.translator.services.heattotosca.errors.DuplicateResourceIdsInDifferentFilesErrorBuilder; import java.util.ArrayList; import java.util.Collection; @@ -637,20 +638,16 @@ public class ConsolidationService { NodeTemplate startingPortNodeTemplate = nodeTemplates.get(portNodeTemplateIdList.get(0)); if (Objects.isNull(startingPortNodeTemplate)) { - throw new CoreException((new ErrorCode.ErrorCodeBuilder()) - .withMessage("Resource with id " - + portNodeTemplateIdList.get(0) + " occures more than once in different addOn files") - .build()); + throw new CoreException( + new DuplicateResourceIdsInDifferentFilesErrorBuilder(portNodeTemplateIdList.get(0)).build()); } for (int i = 1; i < portNodeTemplateIdList.size(); i++) { NodeTemplate portNodeTemplate = nodeTemplates.get(portNodeTemplateIdList.get(i)); if (Objects.isNull(portNodeTemplate)) { - throw new CoreException((new ErrorCode.ErrorCodeBuilder()) - .withMessage("Resource with id " - + portNodeTemplateIdList.get(i) + " occures more than once in different addOn " - + "files").build()); + throw new CoreException( + new DuplicateResourceIdsInDifferentFilesErrorBuilder(portNodeTemplateIdList.get(i)).build()); } if (!isPropertySimilarBetweenNodeTemplates(propertyToCheck, portNodeTemplateIdList, nodeTemplates)) { @@ -695,9 +692,8 @@ public class ConsolidationService { for (int i = 1; i < entityNodeTemplateIds.size(); i++) { NodeTemplate currentNodeTemplate = idToNodeTemplate.get(entityNodeTemplateIds.get(i)); if (Objects.isNull(currentNodeTemplate)) { - throw new CoreException((new ErrorCode.ErrorCodeBuilder()) - .withMessage("Resource with id " - + entityNodeTemplateIds.get(i) + " occures more than once in different addOn files").build()); + throw new CoreException( + new DuplicateResourceIdsInDifferentFilesErrorBuilder(entityNodeTemplateIds.get(i)).build()); } if(propertyExistCondition != isPropertyExistInNodeTemplate(propertyToCheck, currentNodeTemplate)){ return false; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/DuplicateResourceIdsInDifferentFilesErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/DuplicateResourceIdsInDifferentFilesErrorBuilder.java new file mode 100644 index 0000000000..a75e8b391d --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/DuplicateResourceIdsInDifferentFilesErrorBuilder.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.translator.services.heattotosca.errors; + +import org.openecomp.sdc.common.errors.BaseErrorBuilder; +import org.openecomp.sdc.common.errors.ErrorCategory; + +public final class DuplicateResourceIdsInDifferentFilesErrorBuilder extends BaseErrorBuilder { + + private static final String DUPLICATE_RESOURCE_ID_MSG = "Resource with id %s occurs more than once in " + + "different addOn files"; + + public DuplicateResourceIdsInDifferentFilesErrorBuilder(String resourceId) { + getErrorCodeBuilder().withId(TranslatorErrorCodes.DUPLICATE_RESOURCE_ID_IN_DIFFERENT_FILES) + .withCategory(ErrorCategory.APPLICATION) + .withMessage(String.format(DUPLICATE_RESOURCE_ID_MSG, resourceId)); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/TranslatorErrorCodes.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/TranslatorErrorCodes.java index bfcf834ae1..5afb1ae3c2 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/TranslatorErrorCodes.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/TranslatorErrorCodes.java @@ -29,4 +29,5 @@ public class TranslatorErrorCodes { "REFERENCE_TO_UNSUPPORTED_RESOURCE"; public static final String NOT_IN_SYNC_NUMBER_OF_INTERFACES = "NOT_IN_SYNC_NUMBER_OF_INTERFACES"; public static final String INVALID_PROPERTY_VALUE = "INVALID_PROPERTY_VALUE"; + public static final String DUPLICATE_RESOURCE_ID_IN_DIFFERENT_FILES = "DUPLICATE_RESOURCE_ID_IN_DIFFERENT_FILES"; } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/fulltest/UnifiedCompositionMixPatternFullTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/fulltest/UnifiedCompositionMixPatternFullTest.java index b1946b3f9b..9399b91ce1 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/fulltest/UnifiedCompositionMixPatternFullTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/fulltest/UnifiedCompositionMixPatternFullTest.java @@ -2,7 +2,10 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.fulltest; import org.junit.Assert; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.BaseFullTranslationTest; @@ -19,6 +22,9 @@ public class UnifiedCompositionMixPatternFullTest extends BaseFullTranslationTes // do not delete this function. it prevents the superclass setup from running } + @Rule + public ExpectedException exception = ExpectedException.none(); + @Test public void testMixPatterns() throws IOException { inputFilesPath = @@ -52,16 +58,13 @@ public class UnifiedCompositionMixPatternFullTest extends BaseFullTranslationTes @Test public void testDuplicateResourceIdsInDiffAddOnFiles() throws IOException { + exception.expect(CoreException.class); + exception.expectMessage("Resource with id lb_0_int_oam_int_0_port occurs more " + + "than once in different addOn files"); + inputFilesPath = "/mock/services/heattotosca/fulltest/mixPatterns/duplicateResourceIdsInDiffAddOnFiles/in"; - - try { - testTranslationWithInit(); - }catch(Exception e){ - log.debug("",e); - Assert.assertEquals(e.getMessage(), "Resource with id lb_0_int_oam_int_0_port occures more " + - "than once in different addOn files"); - } + testTranslationWithInit(); } @Test diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/VspDetails.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/VspDetails.java index ccadeced62..3f9768b9d7 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/VspDetails.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/VspDetails.java @@ -26,6 +26,7 @@ import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.dao.types.VersionableEntity; import java.util.List; +import java.util.Objects; public class VspDetails implements VersionableEntity { diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/HeatFileAnalyzerRowDataImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/HeatFileAnalyzerRowDataImpl.java index f7ca6463cb..dd303c7bb9 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/HeatFileAnalyzerRowDataImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/HeatFileAnalyzerRowDataImpl.java @@ -53,7 +53,7 @@ public class HeatFileAnalyzerRowDataImpl implements HeatFileAnalyzer { private static final String DESCRIPTION = "DESCRIPTION"; private static final String NESTED_PATTERN = "NESTED_PATTERN"; - private Map<String, Pattern> patterns; + private final Map<String, Pattern> patterns; public HeatFileAnalyzerRowDataImpl() { patterns = new HashMap<>(); @@ -72,16 +72,17 @@ public class HeatFileAnalyzerRowDataImpl implements HeatFileAnalyzer { throws IOException { AnalyzedZipHeatFiles analyzedZipHeatFiles = new AnalyzedZipHeatFiles(); - BufferedReader bfReader; for (Map.Entry<String, byte[]> fileData : files.entrySet()) { String fileName = fileData.getKey(); if (!HeatFileAnalyzer.isYamlFile(fileName)) { analyzedZipHeatFiles.addOtherNonModuleFile(fileName); continue; } + boolean foundHeatIdentifier = false; - try (InputStream is = new ByteArrayInputStream(fileData.getValue())) { - bfReader = new BufferedReader(new InputStreamReader(is)); + try (InputStream is = new ByteArrayInputStream(fileData.getValue()); + BufferedReader bfReader = new BufferedReader(new InputStreamReader(is))) { + String line; boolean isResourcesSection = false; Set<String> nestedFilesNames = new HashSet<>(); @@ -108,11 +109,9 @@ public class HeatFileAnalyzerRowDataImpl implements HeatFileAnalyzer { } analyzedZipHeatFiles.addNestedFiles(fetchFileNamesToReturn(nestedFilesNames, foundHeatIdentifier)); - if (Objects.nonNull(bfReader)) { - bfReader.close(); - } } } + return analyzedZipHeatFiles; } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/utils/CandidateEntityBuilder.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/utils/CandidateEntityBuilder.java index ca5329344b..41510ecc13 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/utils/CandidateEntityBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/utils/CandidateEntityBuilder.java @@ -38,6 +38,7 @@ import org.openecomp.sdc.vendorsoftwareproduct.services.impl.HeatFileAnalyzerRow import org.openecomp.sdc.vendorsoftwareproduct.types.CandidateDataEntityTo; import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.AnalyzedZipHeatFiles; +import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; @@ -45,8 +46,10 @@ import java.util.Objects; import java.util.Optional; public class CandidateEntityBuilder { - private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); - private CandidateService candidateService; + + private static final MdcDataDebugMessage MDC_DATA_DEBUG_MESSAGE = new MdcDataDebugMessage(); + + private final CandidateService candidateService; public CandidateEntityBuilder(CandidateService candidateService) { this.candidateService = candidateService; @@ -57,35 +60,28 @@ public class CandidateEntityBuilder { Map<String, List<ErrorMessage>> uploadErrors, String user) throws Exception { //mdcDataDebugMessage.debugEntryMessage("VSP Id", vspDetails.getId()); - InputStream zipFileManifest = contentMap.getFileContent(SdcCommon.MANIFEST_NAME); - HeatFileAnalyzer heatFileAnalyzer = new HeatFileAnalyzerRowDataImpl(); - AnalyzedZipHeatFiles analyzedZipHeatFiles = - heatFileAnalyzer.analyzeFilesNotEligibleForModulesFromFileAnalyzer(contentMap.getFiles()); - HeatStructureTree tree = getHeatStructureTree(vspDetails, contentMap, analyzedZipHeatFiles); + try (InputStream zipFileManifest = contentMap.getFileContent(SdcCommon.MANIFEST_NAME)) { + HeatFileAnalyzer heatFileAnalyzer = new HeatFileAnalyzerRowDataImpl(); + AnalyzedZipHeatFiles analyzedZipHeatFiles = + heatFileAnalyzer.analyzeFilesNotEligibleForModulesFromFileAnalyzer(contentMap.getFiles()); + HeatStructureTree tree = getHeatStructureTree(vspDetails, contentMap, analyzedZipHeatFiles); - CandidateDataEntityTo candidateDataEntityTo = - new CandidateDataEntityTo(vspDetails.getId(), user, uploadedFileData, tree, contentMap, - vspDetails.getVersion()); - candidateDataEntityTo.setErrors(uploadErrors); - OrchestrationTemplateCandidateData candidateDataEntity = - candidateService.createCandidateDataEntity(candidateDataEntityTo, zipFileManifest, - analyzedZipHeatFiles); + CandidateDataEntityTo candidateDataEntityTo = + new CandidateDataEntityTo(vspDetails.getId(), user, uploadedFileData, tree, contentMap, + vspDetails.getVersion()); + candidateDataEntityTo.setErrors(uploadErrors); + OrchestrationTemplateCandidateData candidateDataEntity = + candidateService.createCandidateDataEntity(candidateDataEntityTo, zipFileManifest, + analyzedZipHeatFiles); - mdcDataDebugMessage.debugExitMessage("VSP Id", vspDetails.getId()); - return candidateDataEntity; + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP Id", vspDetails.getId()); + return candidateDataEntity; + } } -// public OrchestrationTemplateCandidateData buildOrchestrationTemplateFromCsar(VspDetails vspDetails, -// byte[] uploadedFileData, -// FileContentHandler contentMap, -// Map<String, List<ErrorMessage>> uploadErrors, -// String user){ -// -// } - private HeatStructureTree getHeatStructureTree(VspDetails vspDetails, FileContentHandler contentMap, - AnalyzedZipHeatFiles analyzedZipHeatFiles) { + AnalyzedZipHeatFiles analyzedZipHeatFiles) throws IOException { addManifestToFileContentMapIfNotExist(vspDetails, contentMap, analyzedZipHeatFiles); HeatTreeManager heatTreeManager = HeatTreeManagerUtil.initHeatTreeManager(contentMap); heatTreeManager.createTree(); @@ -94,22 +90,24 @@ public class CandidateEntityBuilder { private void addManifestToFileContentMapIfNotExist(VspDetails vspDetails, FileContentHandler fileContentHandler, - AnalyzedZipHeatFiles analyzedZipHeatFiles) { - mdcDataDebugMessage.debugEntryMessage("VSP Id", vspDetails.getId()); + AnalyzedZipHeatFiles analyzedZipHeatFiles) throws IOException { + MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP Id", vspDetails.getId()); + + try (InputStream manifest = fileContentHandler.getFileContent(SdcCommon.MANIFEST_NAME)) { - InputStream manifest = fileContentHandler.getFileContent(SdcCommon.MANIFEST_NAME); - if (Objects.isNull(manifest)) { - Optional<ManifestContent> manifestContentOptional = - candidateService.createManifest(vspDetails, fileContentHandler, analyzedZipHeatFiles); - if (!manifestContentOptional.isPresent()) { - throw new RuntimeException(Messages.CREATE_MANIFEST_FROM_ZIP.getErrorMessage()); + if (Objects.isNull(manifest)) { + Optional<ManifestContent> manifestContentOptional = + candidateService.createManifest(vspDetails, fileContentHandler, analyzedZipHeatFiles); + if (!manifestContentOptional.isPresent()) { + throw new RuntimeException(Messages.CREATE_MANIFEST_FROM_ZIP.getErrorMessage()); + } + ManifestContent manifestContent = manifestContentOptional.get(); + fileContentHandler.addFile( + SdcCommon.MANIFEST_NAME, + String.valueOf(JsonUtil.sbObject2Json(manifestContent)).getBytes()); } - ManifestContent manifestContent = manifestContentOptional.get(); - fileContentHandler.addFile( - SdcCommon.MANIFEST_NAME, - String.valueOf(JsonUtil.sbObject2Json(manifestContent)).getBytes()); + } finally { + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP Id", vspDetails.getId()); } - - mdcDataDebugMessage.debugExitMessage("VSP Id", vspDetails.getId()); } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/errors/OrchestrationTemplateFileExtensionErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/errors/OrchestrationTemplateFileExtensionErrorBuilder.java new file mode 100644 index 0000000000..6545ca1fdd --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/errors/OrchestrationTemplateFileExtensionErrorBuilder.java @@ -0,0 +1,22 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.errors; + +import org.openecomp.sdc.common.errors.ErrorCategory; +import org.openecomp.sdc.common.errors.ErrorCode; + +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.INVALID_EXTENSION; + +public class OrchestrationTemplateFileExtensionErrorBuilder { + private static final String INVALID_EXTENSION_MSG = "Invalid file extension. Valid extensions " + + "are : zip, csar."; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + public OrchestrationTemplateFileExtensionErrorBuilder(){ + builder.withId(INVALID_EXTENSION); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(INVALID_EXTENSION_MSG)); + } + + public ErrorCode build() { + return builder.build(); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/VendorSoftwareProductErrorCodes.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/VendorSoftwareProductErrorCodes.java index da64f5a2e5..d3c2a22fff 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/VendorSoftwareProductErrorCodes.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/VendorSoftwareProductErrorCodes.java @@ -127,4 +127,6 @@ public class VendorSoftwareProductErrorCodes { public static final String DELETE_IMAGE_NOT_ALLOWED = "DELETE_IMAGE_NOT_ALLOWED"; public static final String UPDATE_IMAGE_NOT_ALLOWED = "UPDATE_IMAGE_NOT_ALLOWED"; + public static final String INVALID_EXTENSION = "INVALID_EXTENSION"; + } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/datatypes/CsarFileTypes.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/datatypes/CsarFileTypes.java index 323bd8a5fb..d17f79bb6c 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/datatypes/CsarFileTypes.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/datatypes/CsarFileTypes.java @@ -5,5 +5,6 @@ public enum CsarFileTypes { globalServiceTemplate, externalFile, toscaMetadata, - definitionsFile,; + definitionsFile, + Artifacts; } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterImpl.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterImpl.java index 348739e780..9b694c5207 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterImpl.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterImpl.java @@ -54,7 +54,8 @@ public class ToscaConverterImpl implements ToscaConverter { break; case externalFile: - artifacts.addFile(fileEntry.getKey(), fileEntry.getValue()); + artifacts.addFile( + getConcreteArtifactFileName(fileEntry.getKey()), fileEntry.getValue()); break; case definitionsFile: @@ -94,6 +95,17 @@ public class ToscaConverterImpl implements ToscaConverter { } } + private String getConcreteArtifactFileName(String fileName){ + int artifactIndex = fileName.indexOf(CsarFileTypes.Artifacts.name()); + if(artifactIndex < 0){ + return fileName; + } + + int artifactDirectoryIndex = + artifactIndex + CsarFileTypes.Artifacts.name().length() + 1; + return fileName.substring(artifactDirectoryIndex); + } + private void updateToscaServiceModel(ToscaServiceModel toscaServiceModel, Map<String, ServiceTemplate> serviceTemplates, FileContentHandler externalFilesHandler, diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/test/java/org/openecomp/core/converter/impl/ToscaConverterImplTest.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/test/java/org/openecomp/core/converter/impl/ToscaConverterImplTest.java index f29ca4a427..471e3891c7 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/test/java/org/openecomp/core/converter/impl/ToscaConverterImplTest.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/test/java/org/openecomp/core/converter/impl/ToscaConverterImplTest.java @@ -41,22 +41,18 @@ public class ToscaConverterImplTest { private static final String VIRTUAL_LINK = "virtualLink"; private static final String UNBOUNDED = "UNBOUNDED"; - private static String inputFilesPath; - private static String outputFilesPath; - private static Map<String, ServiceTemplate> expectedOutserviceTemplates; - @Test public void testConvertMainSt() throws IOException { - inputFilesPath = "/mock/toscaConverter/convertMainSt/in"; - outputFilesPath = "/mock/toscaConverter/convertMainSt/out"; + String inputFilesPath = "/mock/toscaConverter/convertMainSt/in"; + String outputFilesPath = "/mock/toscaConverter/convertMainSt/out"; FileContentHandler fileContentHandler = createFileContentHandlerFromInput(inputFilesPath); - expectedOutserviceTemplates = new HashMap<>(); + Map<String, ServiceTemplate> expectedOutserviceTemplates = new HashMap<>(); loadServiceTemplates(outputFilesPath, new ToscaExtensionYamlUtil(), - expectedOutserviceTemplates); + expectedOutserviceTemplates); ToscaServiceModel toscaServiceModel = toscaConverter.convert(fileContentHandler); ServiceTemplate mainSt = toscaServiceModel.getServiceTemplates().get(mainStName); @@ -201,18 +197,15 @@ public class ToscaConverterImplTest { private static void addServiceTemplateFiles(Map<String, ServiceTemplate> serviceTemplates, File[] files, - ToscaExtensionYamlUtil toscaExtensionYamlUtil) - throws IOException { + ToscaExtensionYamlUtil toscaExtensionYamlUtil) throws IOException { + for (File file : files) { + try (InputStream yamlFile = new FileInputStream(file)) { ServiceTemplate serviceTemplateFromYaml = toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class); createConcreteRequirementObjectsInServiceTemplate(serviceTemplateFromYaml, toscaExtensionYamlUtil); serviceTemplates.put(file.getName(), serviceTemplateFromYaml); - try { - yamlFile.close(); - } catch (IOException ignore) { - } } } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/datatypes/ToscaModelTest.java b/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/datatypes/ToscaModelTest.java index c7f4e3f6d1..e8c9c602f8 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/datatypes/ToscaModelTest.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/datatypes/ToscaModelTest.java @@ -46,6 +46,7 @@ import org.openecomp.sdc.tosca.services.ToscaConstants; import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil; import org.openecomp.sdc.tosca.services.YamlUtil; +import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; @@ -271,27 +272,29 @@ public class ToscaModelTest { @Test - public void testYamlToServiceTemplateObj() { - InputStream yamlFile = new YamlUtil().loadYamlFileIs("/mock/model/serviceTemplate.yaml"); - ServiceTemplate serviceTemplateFromYaml = - new YamlUtil().yamlToObject(yamlFile, ServiceTemplate.class); - Assert.assertNotNull(serviceTemplateFromYaml); + public void testYamlToServiceTemplateObj() throws IOException { + try (InputStream yamlFile = new YamlUtil().loadYamlFileIs("/mock/model/serviceTemplate.yaml")) { + ServiceTemplate serviceTemplateFromYaml = + new YamlUtil().yamlToObject(yamlFile, ServiceTemplate.class); + Assert.assertNotNull(serviceTemplateFromYaml); + } } @Test - public void testYamlToServiceTemplateIncludingHeatExtend() { + public void testYamlToServiceTemplateIncludingHeatExtend() throws IOException { ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil(); - InputStream yamlFile = - toscaExtensionYamlUtil.loadYamlFileIs("/mock/model/serviceTemplateHeatExtend.yaml"); - ServiceTemplate serviceTemplateFromYaml = - toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class); - ParameterDefinitionExt parameterDefinitionExt = - (ParameterDefinitionExt) serviceTemplateFromYaml.getTopology_template().getInputs() - .get("inParam1"); - Assert.assertNotNull(parameterDefinitionExt.getLabel()); - String backToYamlString = toscaExtensionYamlUtil.objectToYaml(serviceTemplateFromYaml); - Assert.assertNotNull(backToYamlString); + try (InputStream yamlFile = + toscaExtensionYamlUtil.loadYamlFileIs("/mock/model/serviceTemplateHeatExtend.yaml")) { + ServiceTemplate serviceTemplateFromYaml = + toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class); + ParameterDefinitionExt parameterDefinitionExt = + (ParameterDefinitionExt) serviceTemplateFromYaml.getTopology_template().getInputs() + .get("inParam1"); + Assert.assertNotNull(parameterDefinitionExt.getLabel()); + String backToYamlString = toscaExtensionYamlUtil.objectToYaml(serviceTemplateFromYaml); + Assert.assertNotNull(backToYamlString); + } } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImplTest.java b/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImplTest.java index 7ae91abfa5..aad21634a8 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImplTest.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImplTest.java @@ -78,9 +78,9 @@ public class ToscaAnalyzerServiceImplTest { public ExpectedException thrown = ExpectedException.none(); @Mock - NodeTemplate nodeTemplateMock; + private NodeTemplate nodeTemplateMock; @Mock - ToscaServiceModel toscaServiceModelMock; + private ToscaServiceModel toscaServiceModelMock; @BeforeClass public static void onlyOnceSetUp() throws IOException { @@ -97,27 +97,29 @@ public class ToscaAnalyzerServiceImplTest { @Test public void testGetRequirements() throws Exception { ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil(); - InputStream yamlFile = toscaExtensionYamlUtil - .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml"); - ServiceTemplate - serviceTemplateFromYaml = - toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class); - - NodeTemplate port_0 = - serviceTemplateFromYaml.getTopology_template().getNode_templates().get("cmaui_port_0"); - List<RequirementAssignment> reqList = - toscaAnalyzerService.getRequirements(port_0, ToscaConstants.BINDING_REQUIREMENT_ID); - assertEquals(1, reqList.size()); - - reqList.clear(); - NodeTemplate port_1 = - serviceTemplateFromYaml.getTopology_template().getNode_templates().get("cmaui1_port_1"); - reqList = toscaAnalyzerService.getRequirements(port_1, ToscaConstants.LINK_REQUIREMENT_ID); - assertEquals(2, reqList.size()); - - reqList.clear(); - reqList = toscaAnalyzerService.getRequirements(port_0, ToscaConstants.LINK_REQUIREMENT_ID); - assertEquals(0, reqList.size()); + try (InputStream yamlFile = toscaExtensionYamlUtil + .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) { + + ServiceTemplate + serviceTemplateFromYaml = + toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class); + + NodeTemplate port_0 = + serviceTemplateFromYaml.getTopology_template().getNode_templates().get("cmaui_port_0"); + List<RequirementAssignment> reqList = + toscaAnalyzerService.getRequirements(port_0, ToscaConstants.BINDING_REQUIREMENT_ID); + assertEquals(1, reqList.size()); + + reqList.clear(); + NodeTemplate port_1 = + serviceTemplateFromYaml.getTopology_template().getNode_templates().get("cmaui1_port_1"); + reqList = toscaAnalyzerService.getRequirements(port_1, ToscaConstants.LINK_REQUIREMENT_ID); + assertEquals(2, reqList.size()); + + reqList.clear(); + reqList = toscaAnalyzerService.getRequirements(port_0, ToscaConstants.LINK_REQUIREMENT_ID); + assertEquals(0, reqList.size()); + } } @Test @@ -171,44 +173,45 @@ public class ToscaAnalyzerServiceImplTest { .getSubstituteServiceTemplateName("invalid1", invalidSubstitutableNodeTemplate1); assertEquals(false, substituteServiceTemplateName.isPresent()); - if (substitutableNodeTemplate.isPresent()) { - NodeTemplate invalidSubstitutableNodeTemplate2 = substitutableNodeTemplate.get(); - Object serviceTemplateFilter = invalidSubstitutableNodeTemplate2.getProperties() - .get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME); + substitutableNodeTemplate.ifPresent(nodeTemplate -> { + Object serviceTemplateFilter = nodeTemplate.getProperties() + .get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME); ((Map) serviceTemplateFilter).clear(); toscaAnalyzerService - .getSubstituteServiceTemplateName("invalid2", invalidSubstitutableNodeTemplate2); + .getSubstituteServiceTemplateName("invalid2", nodeTemplate); - } + }); } @Test public void testGetSubstitutableNodeTemplates() throws Exception { ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil(); - InputStream yamlFile = toscaExtensionYamlUtil - .loadYamlFileIs("/mock/analyzerService/ServiceTemplateSubstituteTest.yaml"); - ServiceTemplate serviceTemplateFromYaml = - toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class); - - Map<String, NodeTemplate> substitutableNodeTemplates = - toscaAnalyzerService.getSubstitutableNodeTemplates(serviceTemplateFromYaml); - assertEquals(2, substitutableNodeTemplates.size()); - assertNotNull(substitutableNodeTemplates.get("test_nested1")); - assertNotNull(substitutableNodeTemplates.get("test_nested2")); + try (InputStream yamlFile = toscaExtensionYamlUtil + .loadYamlFileIs("/mock/analyzerService/ServiceTemplateSubstituteTest.yaml")) { + ServiceTemplate serviceTemplateFromYaml = + toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class); + + Map<String, NodeTemplate> substitutableNodeTemplates = + toscaAnalyzerService.getSubstitutableNodeTemplates(serviceTemplateFromYaml); + assertEquals(2, substitutableNodeTemplates.size()); + assertNotNull(substitutableNodeTemplates.get("test_nested1")); + assertNotNull(substitutableNodeTemplates.get("test_nested2")); + + ServiceTemplate emptyServiceTemplate = new ServiceTemplate(); + emptyServiceTemplate.setTopology_template(new TopologyTemplate()); + substitutableNodeTemplates = + toscaAnalyzerService.getSubstitutableNodeTemplates(emptyServiceTemplate); + assertEquals(0, substitutableNodeTemplates.size()); + } - ServiceTemplate emptyServiceTemplate = new ServiceTemplate(); - emptyServiceTemplate.setTopology_template(new TopologyTemplate()); - substitutableNodeTemplates = - toscaAnalyzerService.getSubstitutableNodeTemplates(emptyServiceTemplate); - assertEquals(0, substitutableNodeTemplates.size()); - - yamlFile = toscaExtensionYamlUtil - .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml"); - serviceTemplateFromYaml = toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class); - substitutableNodeTemplates = - toscaAnalyzerService.getSubstitutableNodeTemplates(serviceTemplateFromYaml); - assertEquals(0, substitutableNodeTemplates.size()); + try (InputStream yamlFile = toscaExtensionYamlUtil + .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) { + ServiceTemplate serviceTemplateFromYaml = toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class); + Map<String, NodeTemplate> substitutableNodeTemplates = + toscaAnalyzerService.getSubstitutableNodeTemplates(serviceTemplateFromYaml); + assertEquals(0, substitutableNodeTemplates.size()); + } } @Test @@ -217,35 +220,36 @@ public class ToscaAnalyzerServiceImplTest { thrown.expectMessage( "Invalid Tosca model data, missing 'Node Template' entry for 'Node Template' id cmaui_port_9"); ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil(); - InputStream yamlFile = toscaExtensionYamlUtil - .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml"); - ServiceTemplate nestedServiceTemplateFromYaml = - toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class); - - Optional<Map.Entry<String, NodeTemplate>> mappedNodeTemplate = toscaAnalyzerService - .getSubstitutionMappedNodeTemplateByExposedReq("NestedServiceTemplateSubstituteTest.yaml", - nestedServiceTemplateFromYaml, "local_storage_server_cmaui"); - assertEquals(true, mappedNodeTemplate.isPresent()); - if (mappedNodeTemplate.isPresent()) { - assertEquals("server_cmaui", mappedNodeTemplate.get().getKey()); - assertNotNull(mappedNodeTemplate.get().getValue()); + try (InputStream yamlFile = toscaExtensionYamlUtil + .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) { + ServiceTemplate nestedServiceTemplateFromYaml = + toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class); + + Optional<Map.Entry<String, NodeTemplate>> mappedNodeTemplate = toscaAnalyzerService + .getSubstitutionMappedNodeTemplateByExposedReq("NestedServiceTemplateSubstituteTest.yaml", + nestedServiceTemplateFromYaml, "local_storage_server_cmaui"); + assertEquals(true, mappedNodeTemplate.isPresent()); + mappedNodeTemplate.ifPresent(stringNodeTemplateEntry -> { + assertEquals("server_cmaui", stringNodeTemplateEntry.getKey()); + assertNotNull(stringNodeTemplateEntry.getValue()); + }); + + mappedNodeTemplate = toscaAnalyzerService + .getSubstitutionMappedNodeTemplateByExposedReq("NestedServiceTemplateSubstituteTest.yaml", + nestedServiceTemplateFromYaml, "link_cmaui_port_invalid"); + assertEquals(true, mappedNodeTemplate.isPresent()); + mappedNodeTemplate.ifPresent(stringNodeTemplateEntry -> { + assertEquals("server_cmaui", stringNodeTemplateEntry.getKey()); + assertNotNull(stringNodeTemplateEntry.getValue()); + }); + + ServiceTemplate mainServiceTemplate = toscaServiceModel.getServiceTemplates() + .get(toscaServiceModel.getEntryDefinitionServiceTemplate()); + mappedNodeTemplate = toscaAnalyzerService.getSubstitutionMappedNodeTemplateByExposedReq( + toscaServiceModel.getEntryDefinitionServiceTemplate(), mainServiceTemplate, + "local_storage_server_cmaui"); + assertEquals(false, mappedNodeTemplate.isPresent()); } - - mappedNodeTemplate = toscaAnalyzerService - .getSubstitutionMappedNodeTemplateByExposedReq("NestedServiceTemplateSubstituteTest.yaml", - nestedServiceTemplateFromYaml, "link_cmaui_port_invalid"); - assertEquals(true, mappedNodeTemplate.isPresent()); - if (mappedNodeTemplate.isPresent()) { - assertEquals("server_cmaui", mappedNodeTemplate.get().getKey()); - assertNotNull(mappedNodeTemplate.get().getValue()); - } - - ServiceTemplate mainServiceTemplate = toscaServiceModel.getServiceTemplates() - .get(toscaServiceModel.getEntryDefinitionServiceTemplate()); - mappedNodeTemplate = toscaAnalyzerService.getSubstitutionMappedNodeTemplateByExposedReq( - toscaServiceModel.getEntryDefinitionServiceTemplate(), mainServiceTemplate, - "local_storage_server_cmaui"); - assertEquals(false, mappedNodeTemplate.isPresent()); } @Test @@ -283,14 +287,15 @@ public class ToscaAnalyzerServiceImplTest { thrown.expectMessage( "Invalid Tosca model data, missing 'Node Template' entry for 'Node Template' id cmaui_port_9"); ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil(); - InputStream yamlFile = toscaExtensionYamlUtil - .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml"); - ServiceTemplate nestedServiceTemplateFromYaml = - toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class); + try (InputStream yamlFile = toscaExtensionYamlUtil + .loadYamlFileIs("/mock/analyzerService/NestedServiceTemplateReqTest.yaml")) { + ServiceTemplate nestedServiceTemplateFromYaml = + toscaExtensionYamlUtil.yamlToObject(yamlFile, ServiceTemplate.class); - toscaAnalyzerService - .getSubstitutionMappedNodeTemplateByExposedReq("NestedServiceTemplateSubstituteTest.yaml", - nestedServiceTemplateFromYaml, "link_cmaui_port_invalid"); + toscaAnalyzerService + .getSubstitutionMappedNodeTemplateByExposedReq("NestedServiceTemplateSubstituteTest.yaml", + nestedServiceTemplateFromYaml, "link_cmaui_port_invalid"); + } } @Test diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/impl/ToscaFileOutputServiceCsarImplTest.java b/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/impl/ToscaFileOutputServiceCsarImplTest.java index 4d025e1540..66dda12b4b 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/impl/ToscaFileOutputServiceCsarImplTest.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/impl/ToscaFileOutputServiceCsarImplTest.java @@ -41,7 +41,7 @@ import java.util.zip.ZipFile; public class ToscaFileOutputServiceCsarImplTest { - private ToscaFileOutputServiceCsarImpl toscaFileOutputServiceCSARImpl = + private final ToscaFileOutputServiceCsarImpl toscaFileOutputServiceCSARImpl = new ToscaFileOutputServiceCsarImpl(); @Test @@ -112,21 +112,22 @@ public class ToscaFileOutputServiceCsarImplTest { String resultFileName = "resultFile.zip"; File file = new File(resultFileName); - FileOutputStream fos = new FileOutputStream(file); - fos.write(csarFile); - fos.close(); + try (FileOutputStream fos = new FileOutputStream(file)) { + fos.write(csarFile); + } - ZipFile zipFile = new ZipFile(resultFileName); + try (ZipFile zipFile = new ZipFile(resultFileName)) { - Enumeration<? extends ZipEntry> entries = zipFile.entries(); + Enumeration<? extends ZipEntry> entries = zipFile.entries(); - int count = 0; - while (entries.hasMoreElements()) { - count++; - entries.nextElement(); + int count = 0; + while (entries.hasMoreElements()) { + count++; + entries.nextElement(); + } + Assert.assertEquals(7, count); } - Assert.assertEquals(7, count); - zipFile.close(); + Files.delete(Paths.get(file.getPath())); } @@ -150,21 +151,22 @@ public class ToscaFileOutputServiceCsarImplTest { String resultFileName = "resultFile.zip"; File file = new File(resultFileName); - FileOutputStream fos = new FileOutputStream(file); - fos.write(csarFile); - fos.close(); + try (FileOutputStream fos = new FileOutputStream(file)) { + fos.write(csarFile); + } - ZipFile zipFile = new ZipFile(resultFileName); + try (ZipFile zipFile = new ZipFile(resultFileName)) { - Enumeration<? extends ZipEntry> entries = zipFile.entries(); + Enumeration<? extends ZipEntry> entries = zipFile.entries(); - int count = 0; - while (entries.hasMoreElements()) { - count++; - entries.nextElement(); + int count = 0; + while (entries.hasMoreElements()) { + count++; + entries.nextElement(); + } + Assert.assertEquals(2, count); } - Assert.assertEquals(2, count); - zipFile.close(); + Files.delete(Paths.get(file.getPath())); } } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/VspGeneralLoader.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/VspGeneralLoader.java index fbfde7431e..1d9d2d9774 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/VspGeneralLoader.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/VspGeneralLoader.java @@ -2,6 +2,7 @@ package org.openecomp.core.tools.store; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.Info; import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; import org.openecomp.core.zusammen.plugin.dao.impl.CassandraElementRepository; import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; @@ -10,6 +11,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Objects; public class VspGeneralLoader { @@ -114,16 +116,20 @@ public class VspGeneralLoader { if(changeRef!= null){ subElementContext.setChangeRef(changeRef); } - Optional<ElementEntity> subElementEntity = + Optional<ElementEntity> subElementEntityOptional = cassandraElementRepository.get(context, subElementContext, new ElementEntity(subelementId)); - if (subElementEntity.isPresent()) { + if (subElementEntityOptional.isPresent()) { + Info info = subElementEntityOptional.get().getInfo(); + if (isValid(name, info)) { + return false; + } if (NAME.equals(name)) { - if (value.equals(subElementEntity.get().getInfo().getName())) { + if (value.equals(info.getName())) { return true; } } - if (value.equals(subElementEntity.get().getInfo().getProperty(name))) { + if (value.equals(info.getProperty(name))) { return true; } } @@ -136,5 +142,9 @@ public class VspGeneralLoader { } + private static boolean isValid(String name, Info info) { + return Objects.isNull(info)|| Objects.isNull(info.getProperty(name)); + } + } |