import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.validation.ValidatorFactory;
class CsarValidationTest {
+
+ private final ValidatorFactory validatorFactory = new ValidatorFactory();
@Test
void shouldNotReturnErrors_whenPnfCsarIsValid() throws OnboardPackageException, IOException {
FileContentHandler pnfFileContent = CsarLoader.load("validPnfCompliantWithSOL004.csar", "/Files/PNFs/validation/pmdictionary/validPnfCompliantWithSOL004.csar");
//when
- final ValidationResult validationResult = ValidatorFactory.getValidator(pnfFileContent).validate(pnfFileContent);
+ final ValidationResult validationResult = validatorFactory.getValidator(pnfFileContent).validate(pnfFileContent);
//then
assertThat(validationResult.getErrors(), is(empty()));
FileContentHandler pnfFileContent = CsarLoader.load("invalidPnfCompliantWithSOL004.csar", "/Files/PNFs/validation/pmdictionary/invalidPnfCompliantWithSOL004.csar");
//when
- final ValidationResult validationResult = ValidatorFactory.getValidator(pnfFileContent).validate(pnfFileContent);
+ final ValidationResult validationResult = validatorFactory.getValidator(pnfFileContent).validate(pnfFileContent);
List<ErrorMessage> errorList = validationResult.getErrors();
//then
);
//when
- final ValidationResult validationResult = ValidatorFactory.getValidator(pnfFileContent).validate(pnfFileContent);
+ final ValidationResult validationResult = validatorFactory.getValidator(pnfFileContent).validate(pnfFileContent);
//then
assertThat(validationResult.isValid(), is(true));
);
//when
- final ValidationResult validationResult = ValidatorFactory.getValidator(pnfFileContent).validate(pnfFileContent);
+ final ValidationResult validationResult = validatorFactory.getValidator(pnfFileContent).validate(pnfFileContent);
List<ErrorMessage> errorList = validationResult.getErrors();
//then
}
@Override
- public Response upload(final String vspId, final String versionId, final Attachment fileToUpload, final String user) {
+ public Response upload(String vspId, String versionId, final Attachment fileToUpload, final String user) {
+ vspId = ValidationUtils.sanitizeInputString(vspId);
+ versionId = ValidationUtils.sanitizeInputString(versionId);
final byte[] fileToUploadBytes;
final var filename = ValidationUtils.sanitizeInputString(fileToUpload.getDataHandler().getName());
ArtifactInfo artifactInfo = null;
return Response.ok(uploadFileResponseDto)
.build();
}
- final var version = new Version(ValidationUtils.sanitizeInputString(versionId));
- final var vspDetails = new VspDetails(ValidationUtils.sanitizeInputString(vspId), version);
+ final var version = new Version(versionId);
+ final var vspDetails = vendorSoftwareProductManager.getVsp(vspId, version);
return processOnboardPackage(onboardPackageInfo, vspDetails, errorMessages);
}
if (isInvalidRawZipData(onboardPackage.getFileExtension(), uploadFileResponse, fileContentByteArray, candidateService)) {
return uploadFileResponse;
}
- final UploadFileResponse validateResponse = validate(onboardPackageInfo);
+ final UploadFileResponse validateResponse = validate(vspDetails, onboardPackageInfo);
if (!MapUtils.isEmpty(validateResponse.getErrors())) {
uploadFileResponse.addStructureErrors(validateResponse.getErrors());
return uploadFileResponse;
return false;
}
- public abstract UploadFileResponse validate(final OnboardPackageInfo onboardPackageInfo);
+ public abstract UploadFileResponse validate(final VspDetails vspDetails, final OnboardPackageInfo onboardPackageInfo);
protected abstract OnboardingTypesEnum getHandlerType();
}
import static org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder.getErrorWithParameters;
import java.io.IOException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.collections4.CollectionUtils;
import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData;
import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.validation.CsarSecurityValidator;
-import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.validation.ValidationResult;
import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.validation.Validator;
import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.validation.ValidatorFactory;
import org.openecomp.sdc.vendorsoftwareproduct.security.SecurityManagerException;
public class OrchestrationTemplateCSARHandler extends BaseOrchestrationTemplateHandler {
+ private final ValidatorFactory validatorFactory;
+
+ public OrchestrationTemplateCSARHandler() {
+ this.validatorFactory = new ValidatorFactory();
+ }
+
@Override
- public UploadFileResponse validate(final OnboardPackageInfo onboardPackageInfo) {
+ public UploadFileResponse validate(final VspDetails vspDetails, final OnboardPackageInfo onboardPackageInfo) {
final UploadFileResponse uploadFileResponse = new UploadFileResponse();
if (onboardPackageInfo.getPackageType() == OnboardingTypesEnum.SIGNED_CSAR) {
final OnboardSignedPackage originalOnboardPackage = (OnboardSignedPackage) onboardPackageInfo.getOriginalOnboardPackage();
final OnboardPackage onboardPackage = onboardPackageInfo.getOnboardPackage();
final FileContentHandler fileContentHandler = onboardPackage.getFileContentHandler();
try {
- final Validator validator = ValidatorFactory.getValidator(fileContentHandler);
- final ValidationResult validationResult = validator.validate(fileContentHandler);
- if (CollectionUtils.isNotEmpty(validationResult.getErrors())) {
- uploadFileResponse.addStructureErrors(Map.of(SdcCommon.UPLOAD_FILE, validationResult.getErrors()));
+ final List<String> modelIdList = vspDetails.getModelIdList();
+ if (CollectionUtils.isEmpty(modelIdList)) {
+ final Map<String, List<ErrorMessage>> errorResponseMap = validateSdcModel(fileContentHandler);
+ if (!errorResponseMap.isEmpty()) {
+ uploadFileResponse.addStructureErrors(errorResponseMap);
+ }
+ } else {
+ final Map<String, List<ErrorMessage>> errorResponseMap = validateModels(modelIdList, fileContentHandler);
+ if (!errorResponseMap.isEmpty()) {
+ uploadFileResponse.addStructureErrors(errorResponseMap);
+ }
}
- } catch (IOException exception) {
+ } catch (final IOException exception) {
logger.error(exception.getMessage(), exception);
uploadFileResponse
.addStructureError(SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, Messages.INVALID_CSAR_FILE.getErrorMessage()));
- } catch (CoreException coreException) {
+ } catch (final CoreException coreException) {
logger.error(coreException.getMessage(), coreException);
uploadFileResponse.addStructureError(SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, coreException.getMessage()));
}
return uploadFileResponse;
}
+ private Map<String, List<ErrorMessage>> validateModels(final List<String> modelIdList, final FileContentHandler fileContentHandler) {
+ final Map<String, List<ErrorMessage>> errorResponseMap = new HashMap<>();
+ modelIdList.forEach(model -> {
+ final List<Validator> validators = validatorFactory.getValidators(model);
+ validators.forEach(validator -> {
+ final var validationResult = validator.validate(fileContentHandler);
+ if (CollectionUtils.isNotEmpty(validationResult.getErrors())) {
+ if (errorResponseMap.containsKey(SdcCommon.UPLOAD_FILE)) {
+ errorResponseMap.get(SdcCommon.UPLOAD_FILE).addAll(validationResult.getErrors());
+ } else {
+ errorResponseMap.put(SdcCommon.UPLOAD_FILE, validationResult.getErrors());
+ }
+ }
+ });
+ });
+ return errorResponseMap;
+ }
+
+ private Map<String, List<ErrorMessage>> validateSdcModel(final FileContentHandler fileContentHandler) throws IOException {
+ final var validator = validatorFactory.getValidator(fileContentHandler);
+ final var validationResult = validator.validate(fileContentHandler);
+ if (CollectionUtils.isNotEmpty(validationResult.getErrors())) {
+ return Map.of(SdcCommon.UPLOAD_FILE, validationResult.getErrors());
+ }
+
+ return Collections.emptyMap();
+ }
+
private Optional<UploadFileResponse> validatePackageSecurity(final OnboardSignedPackage signedPackage, final ArtifactInfo artifactInfo) {
final UploadFileResponse uploadFileResponseDto = new UploadFileResponse();
try {
public class OrchestrationTemplateZipHandler extends BaseOrchestrationTemplateHandler {
@Override
- public UploadFileResponse validate(final OnboardPackageInfo onboardPackageInfo) {
+ public UploadFileResponse validate(final VspDetails vspDetails, final OnboardPackageInfo onboardPackageInfo) {
final UploadFileResponse uploadFileResponse = new UploadFileResponse();
final OnboardPackage onboardPackage = onboardPackageInfo.getOnboardPackage();
OrchestrationUtil.getFileContentMap(OnboardingTypesEnum.ZIP, uploadFileResponse, onboardPackage.getFileContent().array());
import static org.openecomp.sdc.tosca.csar.CSARConstants.ETSI_VERSION_2_7_1;
import java.io.IOException;
+import java.util.Comparator;
+import java.util.List;
+import java.util.ServiceLoader;
+import java.util.ServiceLoader.Provider;
+import java.util.stream.Collectors;
import org.openecomp.core.utilities.file.FileContentHandler;
import org.openecomp.sdc.vendorsoftwareproduct.services.impl.etsi.ETSIService;
import org.openecomp.sdc.vendorsoftwareproduct.services.impl.etsi.ETSIServiceImpl;
public class ValidatorFactory {
- private ValidatorFactory() {
+ private final ServiceLoader<Validator> validatorLoader;
+
+ public ValidatorFactory() {
+ this.validatorLoader = ServiceLoader.load(Validator.class);
}
/**
* @return Validator based on the contents of the csar package provided
* @throws IOException when metafile is invalid
*/
- public static Validator getValidator(final FileContentHandler fileContentHandler) throws IOException {
+ public Validator getValidator(final FileContentHandler fileContentHandler) throws IOException {
final ETSIService etsiService = new ETSIServiceImpl(null);
if (!etsiService.isSol004WithToscaMetaDirectory(fileContentHandler)) {
return new ONAPCsarValidator();
}
return new SOL004MetaDirectoryValidator();
}
+
+ /**
+ * Get validators based on the given model.
+ *
+ * @param model the model
+ * @return a list containing all validators for the given model, empty otherwise.
+ */
+ public List<Validator> getValidators(final String model) {
+ return validatorLoader.stream()
+ .map(Provider::get)
+ .filter(validator -> validator.appliesTo(model))
+ .sorted(Comparator.comparingInt(Validator::getOrder))
+ .collect(Collectors.toList());
+ }
}
class SOL004Version4MetaDirectoryValidatorTest extends SOL004MetaDirectoryValidatorTest {
+ private final ValidatorFactory validatorFactory = new ValidatorFactory();
+
@Override
public SOL004MetaDirectoryValidator getSOL004MetaDirectoryValidator() {
return new SOL004Version4MetaDirectoryValidator();
manifestBuilder.withSource(TOSCA_MANIFEST_FILEPATH);
handler.addFile(TOSCA_MANIFEST_FILEPATH, manifestBuilder.build().getBytes(StandardCharsets.UTF_8));
- final Validator validator = ValidatorFactory.getValidator(handler);
+ final Validator validator = validatorFactory.getValidator(handler);
final ValidationResult validationResult = validator.validate(handler);
assertTrue(validationResult.getErrors().isEmpty());
}
manifestBuilder.withSource(TOSCA_MANIFEST_FILEPATH);
handler.addFile(TOSCA_MANIFEST_FILEPATH, manifestBuilder.build().getBytes(StandardCharsets.UTF_8));
- final Validator validator = ValidatorFactory.getValidator(handler);
+ final Validator validator = validatorFactory.getValidator(handler);
final ValidationResult validationResult = validator.validate(handler);
assertExpectedErrors("Non-MANO file does not exist", validationResult.getErrors(), 1);
}
manifestBuilder.withSource(TOSCA_MANIFEST_FILEPATH);
handler.addFile(TOSCA_MANIFEST_FILEPATH, manifestBuilder.build().getBytes(StandardCharsets.UTF_8));
- final Validator validator = ValidatorFactory.getValidator(handler);
+ final Validator validator = validatorFactory.getValidator(handler);
final ValidationResult validationResult = validator.validate(handler);
assertExpectedErrors("Manifest with non existent source files", validationResult.getErrors(), 1);
}
--- /dev/null
+/*
+ * -
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.validation;
+
+import org.openecomp.core.utilities.file.FileContentHandler;
+
+public class TestModelValidator1 implements Validator {
+
+ @Override
+ public ValidationResult validate(FileContentHandler csarContent) {
+ return new CsarValidationResult();
+ }
+
+ @Override
+ public boolean appliesTo(String model) {
+ return "test".equals(model);
+ }
+
+ @Override
+ public int getOrder() {
+ return 0;
+ }
+}
--- /dev/null
+/*
+ * -
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.validation;
+
+import org.openecomp.core.utilities.file.FileContentHandler;
+
+public class TestModelValidator2 implements Validator {
+
+ @Override
+ public ValidationResult validate(FileContentHandler csarContent) {
+ return new CsarValidationResult();
+ }
+
+ @Override
+ public boolean appliesTo(String model) {
+ return "test".equals(model);
+ }
+
+ @Override
+ public int getOrder() {
+ return 1;
+ }
+}
package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.validation;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.openecomp.sdc.be.test.util.TestResourcesHandler.getResourceBytesOrFail;
import static org.openecomp.sdc.tosca.csar.ManifestTokenType.ATTRIBUTE_VALUE_SEPARATOR;
import static org.openecomp.sdc.tosca.csar.ToscaMetaEntry.CREATED_BY_ENTRY;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
-import org.junit.Before;
-import org.junit.Test;
+import java.util.List;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.openecomp.core.utilities.file.FileContentHandler;
-public class ValidatorFactoryTest {
+class ValidatorFactoryTest {
private String metaFile;
private FileContentHandler handler;
+ private ValidatorFactory validatorFactory;
- @Before
- public void setUp(){
+ @BeforeEach
+ void setUp(){
+ validatorFactory = new ValidatorFactory();
handler = new FileContentHandler();
metaFile = new StringBuilder()
.append(TOSCA_META_FILE_VERSION_ENTRY.getName())
.toString();
}
- @Test(expected = IOException.class)
- public void testGivenEmptyMetaFile_thenIOExceptionIsThrown() throws IOException{
+ @Test
+ void testGivenEmptyMetaFile_thenIOExceptionIsThrown() {
handler.addFile(TOSCA_META_PATH_FILE_NAME, "".getBytes(StandardCharsets.UTF_8));
handler.addFile(TOSCA_DEFINITION_FILEPATH, "".getBytes());
handler.addFile(TOSCA_CHANGELOG_FILEPATH, "".getBytes(StandardCharsets.UTF_8));
handler.addFile(TOSCA_MANIFEST_FILEPATH, "".getBytes(StandardCharsets.UTF_8));
- ValidatorFactory.getValidator(handler);
+ assertThrows(IOException.class, () -> validatorFactory.getValidator(handler));
}
@Test
- public void testGivenEmptyBlock0_thenONAPCsarValidatorIsReturned() throws IOException {
+ void testGivenEmptyBlock0_thenONAPCsarValidatorIsReturned() throws IOException {
handler.addFile(TOSCA_META_PATH_FILE_NAME, " ".getBytes(StandardCharsets.UTF_8));
handler.addFile(TOSCA_DEFINITION_FILEPATH, "".getBytes());
handler.addFile(TOSCA_CHANGELOG_FILEPATH, "".getBytes(StandardCharsets.UTF_8));
handler.addFile(TOSCA_MANIFEST_FILEPATH, "".getBytes(StandardCharsets.UTF_8));
- assertEquals(ONAPCsarValidator.class, ValidatorFactory.getValidator(handler).getClass());
+ assertEquals(ONAPCsarValidator.class, validatorFactory.getValidator(handler).getClass());
}
@Test
- public void testGivenNonSOL004MetaDirectoryCompliantMetaFile_thenONAPCSARValidatorIsReturned() throws IOException {
+ void testGivenNonSOL004MetaDirectoryCompliantMetaFile_thenONAPCSARValidatorIsReturned() throws IOException {
metaFile = metaFile +
ENTRY_DEFINITIONS.getName() + ATTRIBUTE_VALUE_SEPARATOR.getToken() + TOSCA_DEFINITION_FILEPATH;
handler.addFile(TOSCA_META_PATH_FILE_NAME, metaFile.getBytes(StandardCharsets.UTF_8));
- assertEquals(ONAPCsarValidator.class, ValidatorFactory.getValidator(handler).getClass());
+ assertEquals(ONAPCsarValidator.class, validatorFactory.getValidator(handler).getClass());
}
@Test
- public void testGivenSOL004MetaDirectoryCompliantMetafile_thenONAPCsarValidatorIsReturned() throws IOException {
+ void testGivenSOL004MetaDirectoryCompliantMetafile_thenONAPCsarValidatorIsReturned() throws IOException {
metaFile = metaFile +
ENTRY_DEFINITIONS.getName() + ATTRIBUTE_VALUE_SEPARATOR.getToken() + TOSCA_DEFINITION_FILEPATH + "\n"
+ ETSI_ENTRY_MANIFEST.getName() + ATTRIBUTE_VALUE_SEPARATOR.getToken() + TOSCA_MANIFEST_FILEPATH + "\n"
+ ETSI_ENTRY_CHANGE_LOG.getName() + ATTRIBUTE_VALUE_SEPARATOR.getToken() + TOSCA_CHANGELOG_FILEPATH + "\n";
handler.addFile(TOSCA_META_PATH_FILE_NAME, metaFile.getBytes(StandardCharsets.UTF_8));
- assertEquals(SOL004MetaDirectoryValidator.class, ValidatorFactory.getValidator(handler).getClass());
+ assertEquals(SOL004MetaDirectoryValidator.class, validatorFactory.getValidator(handler).getClass());
}
@Test
- public void testGivenMultiBlockMetadataWithSOL00CompliantMetaFile_thenSOL004MetaDirectoryValidatorReturned()
+ void testGivenMultiBlockMetadataWithSOL00CompliantMetaFile_thenSOL004MetaDirectoryValidatorReturned()
throws IOException {
handler.addFile(TOSCA_META_PATH_FILE_NAME,
getResourceBytesOrFail("validation.files/metafile/metaFileWithMultipleBlocks.meta"));
handler.addFile(TOSCA_CHANGELOG_FILEPATH, "".getBytes(StandardCharsets.UTF_8));
handler.addFile(TOSCA_MANIFEST_FILEPATH, "".getBytes(StandardCharsets.UTF_8));
- assertEquals(SOL004MetaDirectoryValidator.class, ValidatorFactory.getValidator(handler).getClass());
+ assertEquals(SOL004MetaDirectoryValidator.class, validatorFactory.getValidator(handler).getClass());
+
+ }
+ @Test
+ void testGetValidators() {
+ final List<Validator> validatorList = validatorFactory.getValidators("test");
+ assertFalse(validatorList.isEmpty());
+ assertEquals(2, validatorList.size());
+ assertTrue(validatorList.get(0) instanceof TestModelValidator1);
+ assertTrue(validatorList.get(1) instanceof TestModelValidator2);
+
+ final List<Validator> validatorList1 = validatorFactory.getValidators("test1");
+ assertTrue(validatorList1.isEmpty());
}
}
--- /dev/null
+org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.validation.TestModelValidator1
+org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.validation.TestModelValidator2
\ No newline at end of file