diff options
Diffstat (limited to 'openecomp-be')
27 files changed, 554 insertions, 359 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/activity-log-rest/activity-log-rest-types/src/main/java/org/openecomp/sdcrests/activitylog/types/ActivityType.java b/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-types/src/main/java/org/openecomp/sdcrests/activitylog/types/ActivityType.java index 6bfd50b401..80160bc202 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-types/src/main/java/org/openecomp/sdcrests/activitylog/types/ActivityType.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/activity-log-rest/activity-log-rest-types/src/main/java/org/openecomp/sdcrests/activitylog/types/ActivityType.java @@ -24,14 +24,15 @@ import java.io.Serializable; public enum ActivityType implements Serializable { - CREATE_NEW("Create New"), - CHECKOUT("Check Out"), - CHECKIN("Check In"), - UPLOAD_HEAT("Upload Heat"), + CREATE_NEW("Create New"), + CHECKOUT("Check Out"), + UNDO_CHECKOUT("Undo Check Out"), + CHECKIN("Check In"), + UPLOAD_HEAT("Upload Heat"), UPLOAD_MONITORING_FILE("Upload Monitoring File"), - SUBMIT("Submit"); + SUBMIT("Submit"); - // after collaboration will be added - this will be added: + // after collaboration will be added - this will be added: /* CREATE_NEW, COMMIT, @@ -39,14 +40,14 @@ public enum ActivityType implements Serializable { REMOVE_PERMISSION, */ - private String name; + private String name; - ActivityType(String name) { - this.name = name; - } + ActivityType(String name) { + this.name = name; + } - @Override - public String toString() { - return name; - } + @Override + public String toString() { + return name; + } } 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-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/impl/VendorLicenseManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/impl/VendorLicenseManagerImpl.java index edbf165ec1..e07a13c2e8 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/impl/VendorLicenseManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/impl/VendorLicenseManagerImpl.java @@ -24,7 +24,6 @@ import static org.openecomp.sdc.vendorlicense.VendorLicenseConstants.VENDOR_LICE import org.openecomp.core.util.UniqueValueUtil; import org.openecomp.sdc.activityLog.ActivityLogManager; -import org.openecomp.sdc.activityLog.ActivityLogManagerFactory; import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCode; @@ -41,17 +40,11 @@ import org.openecomp.sdc.logging.types.LoggerTragetServiceName; import org.openecomp.sdc.vendorlicense.VendorLicenseConstants; import org.openecomp.sdc.vendorlicense.VendorLicenseManager; import org.openecomp.sdc.vendorlicense.dao.EntitlementPoolDao; -import org.openecomp.sdc.vendorlicense.dao.EntitlementPoolDaoFactory; import org.openecomp.sdc.vendorlicense.dao.FeatureGroupDao; -import org.openecomp.sdc.vendorlicense.dao.FeatureGroupDaoFactory; import org.openecomp.sdc.vendorlicense.dao.LicenseAgreementDao; -import org.openecomp.sdc.vendorlicense.dao.LicenseAgreementDaoFactory; import org.openecomp.sdc.vendorlicense.dao.LicenseKeyGroupDao; -import org.openecomp.sdc.vendorlicense.dao.LicenseKeyGroupDaoFactory; import org.openecomp.sdc.vendorlicense.dao.LimitDao; -import org.openecomp.sdc.vendorlicense.dao.LimitDaoFactory; import org.openecomp.sdc.vendorlicense.dao.VendorLicenseModelDao; -import org.openecomp.sdc.vendorlicense.dao.VendorLicenseModelDaoFactory; import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupEntity; import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupModel; @@ -64,10 +57,8 @@ import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; import org.openecomp.sdc.vendorlicense.errors.InvalidDateErrorBuilder; import org.openecomp.sdc.vendorlicense.errors.LimitErrorBuilder; import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade; -import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacadeFactory; import org.openecomp.sdc.vendorlicense.types.VersionedVendorLicenseModel; import org.openecomp.sdc.versioning.VersioningManager; -import org.openecomp.sdc.versioning.VersioningManagerFactory; import org.openecomp.sdc.versioning.VersioningUtil; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.dao.types.VersionStatus; @@ -151,6 +142,12 @@ public class VendorLicenseManagerImpl implements VendorLicenseManager { Version newVersion = versioningManager .undoCheckout(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE, vendorLicenseModelId, user); + + ActivityLogEntity activityLogEntity = + new ActivityLogEntity(vendorLicenseModelId, String.valueOf(newVersion.getMajor() + 1), + ActivityType.UNDO_CHECKOUT.toString(), user, true, "", ""); + activityLogManager.addActionLog(activityLogEntity, user); + vendorLicenseFacade.updateVlmLastModificationTime(vendorLicenseModelId, newVersion); mdcDataDebugMessage.debugExitMessage("VLM id", vendorLicenseModelId); 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 1891cddfd5..dde5d61663 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,18 +244,24 @@ 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) .getActiveVersion(); + + ActivityLogEntity activityLogEntity = + new ActivityLogEntity(vendorSoftwareProductId, String.valueOf(version.getMajor() + 1), + ActivityType.UNDO_CHECKOUT.toString(), user, true, "", ""); + activityLogManager.addActionLog(activityLogEntity, user); + String preVspName = vspInfoDao .get(new VspDetails(vendorSoftwareProductId, version)).getName(); @@ -269,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, @@ -289,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); @@ -373,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; } @@ -391,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 = @@ -407,8 +413,8 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa getFeatureGroupMandatoryErrorBuilder(deploymentlocalFlavor.getModel()); errorCodeList.add(deploymentFlavorErrorBuilder); } - List<ComponentComputeAssociation> componetComputeAssociations = new ArrayList<>(); - componetComputeAssociations = deploymentlocalFlavor.getComponentComputeAssociations(); + List<ComponentComputeAssociation> componetComputeAssociations = + deploymentlocalFlavor.getComponentComputeAssociations(); if (CollectionUtils.isEmpty(componetComputeAssociations)) { CompositionEntityValidationData compositionEntityValidationData = new CompositionEntityValidationData(CompositionEntityType.deployment, deploymentFlavor @@ -445,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 = @@ -572,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); } @@ -600,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 -> @@ -615,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 @@ -623,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()); @@ -634,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(); @@ -653,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()); @@ -673,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, @@ -708,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())) { @@ -750,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) { @@ -779,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) { @@ -797,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; } @@ -847,12 +851,12 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa @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); @@ -860,7 +864,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); @@ -876,17 +880,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); @@ -897,13 +901,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) { @@ -923,7 +927,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"; @@ -960,10 +964,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, @@ -973,7 +975,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa exception); } - mdcDataDebugMessage.debugExitMessage("VSP id", vspId); + MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP id", vspId); return translatedFile; } @@ -981,7 +983,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(); @@ -1002,13 +1004,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, @@ -1036,9 +1038,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; } @@ -1059,7 +1061,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), @@ -1071,7 +1073,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; } @@ -1079,11 +1081,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); } @@ -1122,7 +1124,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! @@ -1168,18 +1170,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) { @@ -1196,14 +1198,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; } @@ -1233,7 +1236,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/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/util/ConfigurationManager.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/util/ConfigurationManager.java index 1f5e20fd0b..bde9d06ae4 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/util/ConfigurationManager.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/util/ConfigurationManager.java @@ -20,25 +20,28 @@ package org.openecomp.core.nosqldb.util; +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.tosca.services.YamlUtil; import java.io.FileInputStream; -import java.io.FileNotFoundException; +import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.function.Function; /** * The type Configuration manager. */ public class ConfigurationManager { - private static final String CONFIGURATION_YAML_FILE = "configuration.yaml"; - private static final String cassandraKey = "cassandraConfig"; + static final String CONFIGURATION_YAML_FILE = "configuration.yaml"; + + private static final String CASSANDRA_KEY = "cassandraConfig"; private static final String DEFAULT_KEYSPACE_NAME = "dox"; private static final String CASSANDRA_ADDRESSES = "cassandra.addresses"; private static final String CASSANDRA_DOX_KEY_STORE = "cassandra.dox.keystore"; @@ -49,14 +52,14 @@ public class ConfigurationManager { private static final String CASSANDRA_SSL = "cassandra.ssl"; private static final String CASSANDRA_TRUSTSTORE = "cassandra.Truststore"; private static final String CASSANDRA_TRUSTSTORE_PASSWORD = "cassandra.TruststorePassword"; - private static final String cassandraHostsKey = "cassandraHosts"; - private static final String cassandraPortKey = "port"; - private static final String cassandraUsernameKey = "username"; - private static final String cassandraPasswordKey = "password"; - private static final String cassandraAuthenticateKey = "authenticate"; - private static final String cassandraSSLKey = "ssl"; - private static final String cassandraTruststorePathKey = "truststorePath"; - private static final String cassandraTruststorePasswordKey = "truststorePassword"; + private static final String CASSANDRA_HOSTS_KEY = "cassandraHosts"; + private static final String CASSANDRA_PORT_KEY = "port"; + private static final String CASSANDRA_USERNAME_KEY = "username"; + private static final String CASSANDRA_PASSWORD_KEY = "password"; + private static final String CASSANDRA_AUTHENTICATE_KEY = "authenticate"; + private static final String CASSANDRA_SSL_KEY = "ssl"; + private static final String CASSANDRA_TRUSTSTORE_PATH_KEY = "truststorePath"; + private static final String CASSANDRA_TRUSTSTORE_PASSWORD_KEY = "truststorePassword"; private static ConfigurationManager instance = null; private final LinkedHashMap<String, Object> cassandraConfiguration; @@ -64,18 +67,24 @@ public class ConfigurationManager { private ConfigurationManager() { - YamlUtil yamlUtil = new YamlUtil(); + String configurationYamlFile = System.getProperty(CONFIGURATION_YAML_FILE); - InputStream yamlAsString; - if (configurationYamlFile != null) { - yamlAsString = getConfigFileIs(configurationYamlFile); - } else { - //Load from resources - yamlAsString = yamlUtil.loadYamlFileIs("/" + CONFIGURATION_YAML_FILE); - } - Map<String, LinkedHashMap<String, Object>> configurationMap = yamlUtil.yamlToMap(yamlAsString); - cassandraConfiguration = configurationMap.get(cassandraKey); + Function<InputStream, Map<String, LinkedHashMap<String, Object>>> reader = (is) -> { + YamlUtil yamlUtil = new YamlUtil(); + return yamlUtil.yamlToMap(is); + }; + + try { + + Map<String, LinkedHashMap<String, Object>> configurationMap = configurationYamlFile != null + ? readFromFile(configurationYamlFile, reader) // load from file + : FileUtils.readViaInputStream(CONFIGURATION_YAML_FILE, reader); // or from resource + cassandraConfiguration = configurationMap.get(CASSANDRA_KEY); + + } catch (IOException e) { + throw new RuntimeException("Failed to read configuration", e); + } } /** @@ -101,7 +110,7 @@ public class ConfigurationManager { if (addresses != null) { return addresses.split(","); } - List lsAddresses = (ArrayList) cassandraConfiguration.get(cassandraHostsKey); + List lsAddresses = (ArrayList) cassandraConfiguration.get(CASSANDRA_HOSTS_KEY); String[] addressesArray; addressesArray = (String[]) lsAddresses.toArray(new String[lsAddresses.size()]); return addressesArray; @@ -131,7 +140,7 @@ public class ConfigurationManager { public String getUsername() { String username = System.getProperty(CASSANDRA_USER); if (username == null) { - username = (String) cassandraConfiguration.get(cassandraUsernameKey); + username = (String) cassandraConfiguration.get(CASSANDRA_USERNAME_KEY); } return username; } @@ -144,7 +153,7 @@ public class ConfigurationManager { public String getPassword() { String password = System.getProperty(CASSANDRA_PASSWORD); if (password == null) { - password = (String) cassandraConfiguration.get(cassandraPasswordKey); + password = (String) cassandraConfiguration.get(CASSANDRA_PASSWORD_KEY); } return password; } @@ -157,7 +166,7 @@ public class ConfigurationManager { public String getTruststorePath() { String truststorePath = System.getProperty(CASSANDRA_TRUSTSTORE); if (truststorePath == null) { - truststorePath = (String) cassandraConfiguration.get(cassandraTruststorePathKey); + truststorePath = (String) cassandraConfiguration.get(CASSANDRA_TRUSTSTORE_PATH_KEY); } return truststorePath; } @@ -170,7 +179,7 @@ public class ConfigurationManager { public String getTruststorePassword() { String truststorePassword = System.getProperty(CASSANDRA_TRUSTSTORE_PASSWORD); if (truststorePassword == null) { - truststorePassword = (String) cassandraConfiguration.get(cassandraTruststorePasswordKey); + truststorePassword = (String) cassandraConfiguration.get(CASSANDRA_TRUSTSTORE_PASSWORD_KEY); } return truststorePassword; } @@ -184,7 +193,7 @@ public class ConfigurationManager { int port; String sslPort = System.getProperty(CASSANDRA_PORT); if (sslPort == null) { - sslPort = (String) cassandraConfiguration.get(cassandraPortKey); + sslPort = (String) cassandraConfiguration.get(CASSANDRA_PORT_KEY); if (sslPort == null) { sslPort = "0"; } @@ -200,7 +209,7 @@ public class ConfigurationManager { * @return the boolean */ public boolean isSsl() { - return getBooleanResult(CASSANDRA_SSL, cassandraSSLKey); + return getBooleanResult(CASSANDRA_SSL, CASSANDRA_SSL_KEY); } /** @@ -209,7 +218,7 @@ public class ConfigurationManager { * @return the boolean */ public boolean isAuthenticate() { - return getBooleanResult(CASSANDRA_AUTHENTICATE, cassandraAuthenticateKey); + return getBooleanResult(CASSANDRA_AUTHENTICATE, CASSANDRA_AUTHENTICATE_KEY); } private Boolean getBooleanResult(String property, String key) { @@ -226,13 +235,9 @@ public class ConfigurationManager { return res; } - private InputStream getConfigFileIs(String file) { - InputStream is = null; - try { - is = new FileInputStream(file); - } catch (FileNotFoundException exception) { - log.debug("",exception); + private <T> T readFromFile(String file, Function<InputStream, T> reader) throws IOException { + try (InputStream is = new FileInputStream(file)) { + return reader.apply(is); } - return is; } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/util/ConfigurationManagerTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/util/ConfigurationManagerTest.java new file mode 100644 index 0000000000..f8d5d2dce7 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/util/ConfigurationManagerTest.java @@ -0,0 +1,73 @@ +package org.openecomp.core.nosqldb.util; + +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.Closeable; +import java.io.IOException; +import java.lang.reflect.Field; + +import static org.testng.Assert.*; + +/** + * @author EVITALIY + * @since 22 Oct 17 + */ +public class ConfigurationManagerTest { + + private static final String NON_EXISTENT = "unexistentfile"; + + @BeforeMethod + public void resetInstance() throws NoSuchFieldException, IllegalAccessException { + Field field = ConfigurationManager.class.getDeclaredField("instance"); + field.setAccessible(true); + field.set(null, null); + } + + @Test(expectedExceptions = IOException.class, + expectedExceptionsMessageRegExp = ".*" + NON_EXISTENT + ".*") + public void testGetInstanceSystemProperty() throws Throwable { + + try (ConfigurationSystemPropertyUpdater updater = new ConfigurationSystemPropertyUpdater(NON_EXISTENT)) { + ConfigurationManager.getInstance(); + } catch (RuntimeException e) { + Throwable cause = e.getCause(); + throw cause == null ? e : cause; + } + } + + @Test() + public void testGetInstanceDefault() throws Exception { + + try (ConfigurationSystemPropertyUpdater property = new ConfigurationSystemPropertyUpdater()) { + ConfigurationManager manager = ConfigurationManager.getInstance(); + assertNotNull(manager.getUsername()); + } + } + + + private static class ConfigurationSystemPropertyUpdater implements Closeable { + + private final String oldValue; + + private ConfigurationSystemPropertyUpdater(String value) { + this.oldValue = System.getProperty(ConfigurationManager.CONFIGURATION_YAML_FILE); + System.setProperty(ConfigurationManager.CONFIGURATION_YAML_FILE, value); + } + + private ConfigurationSystemPropertyUpdater() { + this.oldValue = System.getProperty(ConfigurationManager.CONFIGURATION_YAML_FILE); + System.clearProperty(ConfigurationManager.CONFIGURATION_YAML_FILE); + } + + @Override + public void close() throws IOException { + + if (oldValue == null) { + System.clearProperty(ConfigurationManager.CONFIGURATION_YAML_FILE); + } else { + System.setProperty(ConfigurationManager.CONFIGURATION_YAML_FILE, oldValue); + } + } + } +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java index 6ff213c34c..6ab3f8b049 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java @@ -28,6 +28,7 @@ import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.tosca.services.YamlUtil; import java.io.ByteArrayInputStream; +import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; @@ -54,7 +55,16 @@ public class FileUtils { * @param function logic to be applied to the input stream */ public static <T> T readViaInputStream(String fileName, Function<InputStream, T> function) { - return readViaInputStream(FileUtils.class.getClassLoader().getResource(fileName), function); + + Objects.requireNonNull(fileName); + + // the leading slash doesn't make sense and doesn't work when used with a class loader + URL resource = FileUtils.class.getClassLoader().getResource(fileName.startsWith("/") ? fileName.substring(1) : fileName); + if (resource == null) { + throw new IllegalArgumentException("Resource not found: " + fileName); + } + + return readViaInputStream(resource, function); } /** diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/file/FileUtilsTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/file/FileUtilsTest.java new file mode 100644 index 0000000000..e32aa39904 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/file/FileUtilsTest.java @@ -0,0 +1,48 @@ +package org.openecomp.core.utilities.file; + +import org.testng.annotations.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.util.function.Function; + +import static org.testng.Assert.assertTrue; + +/** + * @author EVITALIY + * @since 22 Oct 17 + */ +public class FileUtilsTest { + + private static final String TEST_RESOURCE = FileUtilsTest.class.getPackage().getName() + .replace('.', '/') + "/test-resource.txt"; + + private static final Function<InputStream, Integer> TEST_FUNCTION = (s) -> { + + try { + return s.available(); + } catch (IOException e) { + throw new RuntimeException(e); + } + }; + + @Test + public void testReadViaInputStreamWithSlash() throws Exception { + assertTrue(FileUtils.readViaInputStream(TEST_RESOURCE, TEST_FUNCTION) > 0); + } + + @Test + public void testReadViaInputStreamWithoutSlash() throws Exception { + assertTrue(FileUtils.readViaInputStream(TEST_RESOURCE, TEST_FUNCTION) > 0); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testReadViaInputStreamNull() throws Exception { + FileUtils.readViaInputStream((String) null, TEST_FUNCTION); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testReadViaInputStreamNotFound() throws Exception { + FileUtils.readViaInputStream("notfound.txt", TEST_FUNCTION); + } +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/org/openecomp/core/utilities/file/test-resource.txt b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/org/openecomp/core/utilities/file/test-resource.txt new file mode 100644 index 0000000000..dce400c8a5 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/org/openecomp/core/utilities/file/test-resource.txt @@ -0,0 +1 @@ +CLASSPATH RESOURCE
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/impl/ZusammenConnectorImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/impl/ZusammenConnectorImpl.java index fa08ba49a8..deb5ffde35 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/impl/ZusammenConnectorImpl.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/impl/ZusammenConnectorImpl.java @@ -60,13 +60,12 @@ public class ZusammenConnectorImpl implements ZusammenConnector { @Override public Collection<Item> listItems(SessionContext context) { - Response<Collection<Item>> response = - itemAdaptorFactory.createInterface(context).list(context); - if (response.isSuccessful()) { - return response.getValue(); - } else { - return null; + Response<Collection<Item>> response = itemAdaptorFactory.createInterface(context).list(context); + if (!response.isSuccessful()) { + throw new RuntimeException( + "Failed to list Items. message:" + response.getReturnCode().toString()); } + return response.getValue(); } @Override @@ -76,7 +75,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { return response.getValue(); } else { throw new RuntimeException( - "failed to create Item. message:" + response.getReturnCode().getMessage()); + "failed to create Item. message:" + response.getReturnCode().toString()); } } @@ -87,7 +86,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { if (!response.isSuccessful()) { throw new RuntimeException("failed to update Item . ItemId:" + itemId + "" + - " message:" + response.getReturnCode().getMessage()); + " message:" + response.getReturnCode().toString()); } } @@ -98,7 +97,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { if (!versions.isSuccessful()) { logErrorMessageToMdc(ItemElementLoggerTargetServiceName.ITEM_VERSION_RETRIEVAL, versions .getReturnCode()); - throw new RuntimeException(versions.getReturnCode().getMessage()); // TODO: 3/26/2017 + throw new RuntimeException(versions.getReturnCode().toString()); // TODO: 3/26/2017 } return versions.getValue(); } @@ -114,7 +113,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { throw new RuntimeException("failed to create Item Version. ItemId:" + itemId + " based " + "on:" + baseVersionId + " message:" + response - .getReturnCode().getMessage()); + .getReturnCode().toString()); } } @@ -126,7 +125,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { if (!response.isSuccessful()) { throw new RuntimeException( String.format("failed to create Item Version. ItemId: %s, versionId: %s, message: %s", - itemId.getValue(), versionId.getValue(), response.getReturnCode().getMessage())); + itemId.getValue(), versionId.getValue(), response.getReturnCode().toString())); } } @@ -151,7 +150,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { throw new RuntimeException(String.format( "failed to reset Item Version back to %s. ItemId: %s, versionId: %s, message: %s", changeRef, itemId.getValue(), versionId.getValue(), - response.getReturnCode().getMessage())); + response.getReturnCode().toString())); } } @@ -166,7 +165,7 @@ public class ZusammenConnectorImpl implements ZusammenConnector { } else { logErrorMessageToMdc(ItemElementLoggerTargetServiceName.ELEMENT_GET_BY_PROPERTY, elementInfosResponse.getReturnCode()); - throw new RuntimeException(elementInfosResponse.getReturnCode().getMessage()); + throw new RuntimeException(elementInfosResponse.getReturnCode().toString()); } } @@ -187,11 +186,15 @@ public class ZusammenConnectorImpl implements ZusammenConnector { @Override public Optional<Element> saveElement(SessionContext context, ElementContext elementContext, ZusammenElement element, String message) { - Response<Element> saveResponse = elementAdaptorFactory.createInterface(context) + Response<Element> response = elementAdaptorFactory.createInterface(context) .save(context, elementContext, element, message); - return saveResponse.isSuccessful() - ? Optional.of(saveResponse.getValue()) - : Optional.empty(); // TODO: 3/21/2017 error? + if (!response.isSuccessful()) { + throw new RuntimeException(String + .format("Failed to save element %s. ItemId: %s, versionId: %s, message: %s", + element.getElementId().getValue(), elementContext.getItemId().getValue(), + elementContext.getVersionId().getValue(), response.getReturnCode().toString())); + } + return Optional.of(response.getValue()); } private void logErrorMessageToMdc(ItemElementLoggerTargetServiceName diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementCollaborationStore.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementCollaborationStore.java index 76b0a900c1..ac103c0fbf 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementCollaborationStore.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementCollaborationStore.java @@ -11,17 +11,20 @@ import org.openecomp.core.zusammen.plugin.dao.ElementRepository; import org.openecomp.core.zusammen.plugin.dao.ElementRepositoryFactory; import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import java.util.ArrayList; import java.util.Collection; -import java.util.HashSet; -import java.util.Objects; import java.util.Optional; -import java.util.stream.Collectors; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getCollaborationElement; import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getSpaceName; public class ElementCollaborationStore { + private static final String SUB_ELEMENT_NOT_EXIST_ERROR_MSG = + "List sub elements error: item %s, version %s - " + + "element %s, which appears as sub element of element %s, does not exist"; + public Collection<CollaborationElement> listElements(SessionContext context, ElementContext elementContext, Id elementId) { @@ -33,14 +36,26 @@ public class ElementCollaborationStore { } ElementRepository elementRepository = getElementRepository(context); - return elementRepository.get(context, elementEntityContext, new ElementEntity(elementId)) - .map(ElementEntity::getSubElementIds).orElse(new HashSet<>()).stream() - .map(subElementId -> elementRepository - .get(context, elementEntityContext, new ElementEntity(subElementId)).get()) - .filter(Objects::nonNull) - .map(subElement -> ZusammenPluginUtil - .getCollaborationElement(elementEntityContext, subElement)) - .collect(Collectors.toList()); + String elementIdValue = elementId.getValue(); + String versionIdValue = elementContext.getChangeRef() == null + ? elementContext.getVersionId().getValue() + : elementContext.getChangeRef(); + Collection<CollaborationElement> subElements = new ArrayList<>(); + + Optional<ElementEntity> element = + elementRepository.get(context, elementEntityContext, new ElementEntity(elementId)); + if (element.isPresent() && element.get().getSubElementIds() != null) { + for (Id subElementId : element.get().getSubElementIds()) { + ElementEntity subElement = + elementRepository.get(context, elementEntityContext, new ElementEntity(subElementId)) + .orElseThrow( + () -> new IllegalStateException(String.format(SUB_ELEMENT_NOT_EXIST_ERROR_MSG, + elementContext.getItemId().getValue(), versionIdValue, + subElementId.getValue(), elementIdValue))); + subElements.add(getCollaborationElement(elementEntityContext, subElement)); + } + } + return subElements; } public CollaborationElement getElement(SessionContext context, ElementContext elementContext, @@ -49,8 +64,7 @@ public class ElementCollaborationStore { new ElementEntityContext(ZusammenPluginUtil.getPrivateSpaceName(context), elementContext); return getElementRepository(context) .get(context, elementEntityContext, new ElementEntity(elementId)) - .map(elementEntity -> ZusammenPluginUtil - .getCollaborationElement(elementEntityContext, elementEntity)) + .map(elementEntity -> getCollaborationElement(elementEntityContext, elementEntity)) .orElse(null); } @@ -78,7 +92,7 @@ public class ElementCollaborationStore { ZusammenPluginUtil.getElementEntity(element)); } - public boolean checkHealth(SessionContext sessionContext){ + public boolean checkHealth(SessionContext sessionContext) { return getElementRepository(sessionContext).checkHealth(sessionContext); } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionCollaborationStore.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionCollaborationStore.java index ae23b6e8a9..db3066c313 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionCollaborationStore.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionCollaborationStore.java @@ -14,7 +14,10 @@ import org.openecomp.core.zusammen.plugin.dao.ElementRepositoryFactory; import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginConstants.ROOT_ELEMENTS_PARENT_ID; import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getSpaceName; public class VersionCollaborationStore { @@ -25,46 +28,74 @@ public class VersionCollaborationStore { throw new UnsupportedOperationException( "In this plugin implementation tag is supported only on versionId"); } - copyElements(context, getSpaceName(context, Space.PRIVATE), itemId, versionId, tag.getName()); + String space = getSpaceName(context, Space.PRIVATE); + ElementEntityContext targetContext = new ElementEntityContext(space, itemId, versionId); + targetContext.setChangeRef(tag.getName()); + copyElements(context, new ElementEntityContext(space, itemId, versionId), targetContext, + getElementRepository(context)); } public CollaborationMergeChange resetItemVersionHistory(SessionContext context, Id itemId, Id versionId, String changeRef) { ElementRepository elementRepository = getElementRepository(context); - ElementEntityContext elementContext = - new ElementEntityContext(getSpaceName(context, Space.PRIVATE), itemId, versionId); - CollaborationMergeChange resetChange = new CollaborationMergeChange(); + String spaceName = getSpaceName(context, Space.PRIVATE); + ElementEntityContext versionContext = new ElementEntityContext(spaceName, itemId, versionId); - Collection<ElementEntity> versionElements = elementRepository.list(context, elementContext); - versionElements.stream() - .map(elementEntity -> - convertElementEntityToElementChange(elementEntity, elementContext, Action.DELETE)) - .forEach(resetChange.getChangedElements()::add); + Collection<ElementEntity> deletedElements = + deleteElements(context, versionContext, elementRepository); - elementContext.setChangeRef(changeRef); - Collection<ElementEntity> changeRefElements = elementRepository.list(context, elementContext); - changeRefElements.stream() - .map(elementEntity -> - convertElementEntityToElementChange(elementEntity, elementContext, Action.CREATE)) - .forEach(resetChange.getChangedElements()::add); + ElementEntityContext changeRefContext = new ElementEntityContext(spaceName, itemId, versionId); + changeRefContext.setChangeRef(changeRef); - return resetChange; // TODO: 4/19/2017 version change... + Collection<ElementEntity> createdElements = + copyElements(context, changeRefContext, versionContext, elementRepository); + + // TODO: 4/19/2017 version change... + return createCollaborationMergeChange(versionContext, deletedElements, createdElements); } - private void copyElements(SessionContext context, String space, Id itemId, Id sourceVersionId, - String targetTag) { - ElementRepository elementRepository = getElementRepository(context); - ElementEntityContext elementContext = new ElementEntityContext(space, itemId, sourceVersionId); + private Collection<ElementEntity> deleteElements(SessionContext context, + ElementEntityContext elementContext, + ElementRepository elementRepository) { + Collection<ElementEntity> elements = elementRepository.list(context, elementContext); + elements.forEach(element -> elementRepository + .delete(context, elementContext, new ElementEntity(element.getId()))); + elementRepository.delete(context, elementContext, new ElementEntity(ROOT_ELEMENTS_PARENT_ID)); + return elements; + } - Collection<ElementEntity> versionElements = elementRepository.list(context, elementContext); + private Collection<ElementEntity> copyElements(SessionContext context, + ElementEntityContext sourceElementContext, + ElementEntityContext targetElementContext, + ElementRepository elementRepository) { + Collection<ElementEntity> elements = elementRepository.list(context, sourceElementContext); + elements.forEach(elementEntity -> + elementRepository.create(context, targetElementContext, elementEntity)); + return elements; + } + + private CollaborationMergeChange createCollaborationMergeChange( + ElementEntityContext versionContext, + Collection<ElementEntity> deletedElements, + Collection<ElementEntity> createdElements) { + CollaborationMergeChange mergeChange = new CollaborationMergeChange(); + mergeChange.getChangedElements().addAll( + convertToCollaborationElementChanges(versionContext, deletedElements, Action.DELETE)); + mergeChange.getChangedElements().addAll( + convertToCollaborationElementChanges(versionContext, createdElements, Action.CREATE)); + return mergeChange; + } - elementContext.setChangeRef(targetTag); - versionElements - .forEach(elementEntity -> elementRepository.create(context, elementContext, elementEntity)); + private List<CollaborationElementChange> convertToCollaborationElementChanges( + ElementEntityContext elementContext, Collection<ElementEntity> changedElements, + Action action) { + return changedElements.stream() + .map(element -> convertToCollaborationElementChange(element, elementContext, action)) + .collect(Collectors.toList()); } - private CollaborationElementChange convertElementEntityToElementChange( + private CollaborationElementChange convertToCollaborationElementChange( ElementEntity elementEntity, ElementEntityContext elementContext, Action action) { CollaborationElementChange elementChange = new CollaborationElementChange(); elementChange diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraElementRepository.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraElementRepository.java index c19e8799d1..6cc1350444 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraElementRepository.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraElementRepository.java @@ -16,12 +16,6 @@ package org.openecomp.core.zusammen.plugin.dao.impl; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.mapping.annotations.Accessor; -import com.datastax.driver.mapping.annotations.Param; -import com.datastax.driver.mapping.annotations.Query; -import com.google.gson.reflect.TypeToken; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.Namespace; import com.amdocs.zusammen.datatypes.SessionContext; @@ -29,6 +23,12 @@ import com.amdocs.zusammen.datatypes.item.Info; import com.amdocs.zusammen.datatypes.item.Relation; import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; import com.amdocs.zusammen.utils.fileutils.json.JsonUtil; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.mapping.annotations.Accessor; +import com.datastax.driver.mapping.annotations.Param; +import com.datastax.driver.mapping.annotations.Query; +import com.google.gson.reflect.TypeToken; import org.openecomp.core.zusammen.plugin.dao.ElementRepository; import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; @@ -38,22 +38,30 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; -import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; public class CassandraElementRepository implements ElementRepository { + private static final String VERSION_ELEMENT_NOT_EXIST_ERROR_MSG = + "List version elements error: " + + "element %s, which appears as an element of item %s version %s, does not exist"; + @Override public Collection<ElementEntity> list(SessionContext context, ElementEntityContext elementContext) { Set<String> elementIds = getVersionElementIds(context, elementContext); - return elementIds.stream() - .map(elementId -> get(context, elementContext, new ElementEntity(new Id(elementId))).get()) - .filter(Objects::nonNull) - .collect(Collectors.toList()); + Collection<ElementEntity> elements = new ArrayList<>(); + for (String elementId : elementIds) { + elements.add(get(context, elementContext, new ElementEntity(new Id(elementId))) + .orElseThrow( + () -> new IllegalStateException(String.format(VERSION_ELEMENT_NOT_EXIST_ERROR_MSG, + elementId, elementContext.getItemId().getValue(), + getVersionId(elementContext))))); + } + return elements; } @Override diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java index c1f69cf3bf..4e1a60fff8 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java @@ -119,9 +119,12 @@ public class HeatToToscaUtil { mdcDataDebugMessage.debugEntryMessage(null, null); HeatToToscaTranslator heatToToscaTranslator = HeatToToscaTranslatorFactory.getInstance().createInterface(); - InputStream fileContent = fileNameContentMap.getFileContent(SdcCommon.MANIFEST_NAME); - heatToToscaTranslator.addManifest(SdcCommon.MANIFEST_NAME, FileUtils.toByteArray(fileContent)); + try (InputStream fileContent = fileNameContentMap.getFileContent(SdcCommon.MANIFEST_NAME)) { + heatToToscaTranslator.addManifest(SdcCommon.MANIFEST_NAME, FileUtils.toByteArray(fileContent)); + } catch (IOException e) { + throw new RuntimeException("Failed to read manifest", e); + } fileNameContentMap.getFileList().stream() .filter(fileName -> !(fileName.equals(SdcCommon.MANIFEST_NAME))).forEach( @@ -143,7 +146,7 @@ public class HeatToToscaUtil { return heatToToscaTranslator.translate(); } catch (IOException e) { // rethrow as a RuntimeException to keep the signature backward compatible - throw new RuntimeException(e); + throw new RuntimeException("Failed to read Heat template tree", e); } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/utils/ResourceWalker.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/utils/ResourceWalker.java index 353b791a1f..9ff1ff9992 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/utils/ResourceWalker.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/utils/ResourceWalker.java @@ -40,8 +40,7 @@ public class ResourceWalker { Exception { Map<String, String> filesContent = new HashMap<>(); traverse(resourceDirectoryToStart, (fileName, stream) -> { - BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); - try { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { filesContent.put(fileName, IOUtils.toString(reader)); } catch (IOException exception) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/util/ValidationTestUtil.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/util/ValidationTestUtil.java index fa1946f987..2b58a30e50 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/util/ValidationTestUtil.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/util/ValidationTestUtil.java @@ -25,6 +25,7 @@ import org.testng.Assert; import java.io.File; import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.IOException; import java.io.StringWriter; import java.net.URL; @@ -55,8 +56,6 @@ public class ValidationTestUtil { private static Map<String, byte[]> getContentMapByPath(String path) { Map<String, byte[]> contentMap = new HashMap<>(); - byte[] fileContent; - FileInputStream fis; URL url = ValidationTestUtil.class.getResource(path); File pathFile = new File(url.getFile()); File[] files; @@ -71,13 +70,13 @@ public class ValidationTestUtil { } for (File file : files) { - try { - fis = new FileInputStream(file); - fileContent = FileUtils.toByteArray(fis); - contentMap.put(file.getName(), fileContent); + + try (FileInputStream fis = new FileInputStream(file)) { + contentMap.put(file.getName(), FileUtils.toByteArray(fis)); } catch (IOException e) { - log.debug("",e); + throw new RuntimeException("Failed to read file: " + file, e); } + } return contentMap; } 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-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersioningManagerImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersioningManagerImpl.java index 0bbe3f81e7..4a49d5391f 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersioningManagerImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersioningManagerImpl.java @@ -492,11 +492,12 @@ public class VersioningManagerImpl implements VersioningManager { versionInfoEntity.setActiveVersion(userCandidateVersion.getVersion()); versionInfoEntity.getViewableVersions().add(versionInfoEntity.getActiveVersion()); versionInfoEntity.setStatus(VersionStatus.Available); - versionInfoDao.update(versionInfoEntity); closeVersionOnEntity(versionInfoEntity.getEntityType(), versionInfoEntity.getEntityId(), versionInfoEntity.getActiveVersion()); + versionInfoDao.update(versionInfoEntity); + return versionInfoEntity.getActiveVersion(); } 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/tools/zusammen-tools/src/main/resources/zusammenMainTool.sh b/openecomp-be/tools/zusammen-tools/src/main/resources/zusammenMainTool.sh index 42c347f4e8..78af19b0f9 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/resources/zusammenMainTool.sh +++ b/openecomp-be/tools/zusammen-tools/src/main/resources/zusammenMainTool.sh @@ -22,5 +22,5 @@ else fi echo "Configuration file location: ${CONF_FILE_LOCATION}" -java -Dlog.home=/apps/jetty/base/be/logs -Dconfiguration.yaml=${CONF_FILE_LOCATION} -jar openecomp-zusammen-tools-1.0-SNAPSHOT.jar org.openecomp.core.tools.main.ZusammenMainTool $1 $2 $3 $4 $5 $6 +java -Dlog.home=/apps/jetty/base/be/logs -Dconfiguration.yaml=${CONF_FILE_LOCATION} -jar openecomp-zusammen-tools-1.2.0-SNAPSHOT.jar org.openecomp.core.tools.main.ZusammenMainTool $1 $2 $3 $4 $5 $6 STATUS="${?}" echo "${STATUS}" |