@Test @RunWithCustomExecutor public void givenIngestContractsTestMissingNameReturnBadRequest() throws Exception { VitamThreadUtils.getVitamSession().setTenantId(TENANT_ID); final File fileContracts = PropertiesUtils.getResourceFile("referential_contracts_missingName.json"); final List<IngestContractModel> IngestContractModelList = JsonHandler.getFromFileAsTypeReference(fileContracts, new TypeReference<List<IngestContractModel>>() { }); final RequestResponse<IngestContractModel> response = ingestContractService.createContracts(IngestContractModelList); assertThat(response.isOk()).isFalse(); verifyNoMoreInteractions(functionalBackupService); ArgumentCaptor<LogbookOperationParameters> logbookOperationParametersCaptor = ArgumentCaptor.forClass(LogbookOperationParameters.class); verify(logbookOperationsClientMock, times(1)).create(logbookOperationParametersCaptor.capture()); verify(logbookOperationsClientMock, times(1)).update(logbookOperationParametersCaptor.capture()); List<LogbookOperationParameters> allLogbookOperationParameters = logbookOperationParametersCaptor .getAllValues(); assertThat(allLogbookOperationParameters.size()).isEqualTo(2); assertThat(allLogbookOperationParameters.get(0).getStatus()).isEqualTo(StatusCode.STARTED); assertThat(allLogbookOperationParameters.get(0).getParameterValue(LogbookParameterName.eventType)) .isEqualTo("STP_IMPORT_INGEST_CONTRACT"); assertThat(allLogbookOperationParameters.get(1).getStatus()).isEqualTo(StatusCode.KO); assertThat(allLogbookOperationParameters.get(1).getParameterValue(LogbookParameterName.eventType)) .isEqualTo("STP_IMPORT_INGEST_CONTRACT"); assertThat(allLogbookOperationParameters.get(1).getParameterValue(LogbookParameterName.outcomeDetail)) .isEqualTo("STP_IMPORT_INGEST_CONTRACT.EMPTY_REQUIRED_FIELD.KO"); }
@Override public RequestResponse<IngestContractModel> createContracts(List<IngestContractModel> contractModelList) throws VitamException { ParametersChecker.checkParameter(CONTRACT_IS_MANDATORY_PATAMETER, contractModelList); if (contractModelList.isEmpty()) { return new RequestResponseOK<>(); } contractModelList.forEach(IngestContractModel::setDefaultParams); boolean slaveMode = vitamCounterService .isSlaveFunctionnalCollectionOnTenant(SequenceType.INGEST_CONTRACT_SEQUENCE.getCollection(), ParameterHelper.getTenantParameter()); String operationId = VitamThreadUtils.getVitamSession().getRequestId(); GUID eip = GUIDReader.getGUID(operationId); IngestContractValidationService validationService = new IngestContractValidationService(metaDataClient, managementContractService); ContractLogbookService logbookService = new ContractLogbookService(logbookClient, eip, CONTRACTS_IMPORT_EVENT, CONTRACT_UPDATE_EVENT, CONTRACT_KEY, CONTRACT_CHECK_KEY); logbookService.logStarted(); ArrayNode contractsToPersist = null; final VitamError error = getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), "Ingest contract import error", StatusCode.KO) .setHttpCode(Response.Status.BAD_REQUEST .getStatusCode()); try { for (final IngestContractModel acm : contractModelList) { final String linkParentId = acm.getLinkParentId(); if (linkParentId != null && !validationService.checkIfUnitExist(linkParentId)) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause .rejectAuNotFoundInDatabase(linkParentId) .getReason(), StatusCode.KO)); continue; } final String managementContractId = acm.getManagementContractId(); if (managementContractId != null && !validationService.checkIfManagementContractExists(managementContractId)) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause .rejectMCNotFoundInDatabase(managementContractId) .getReason(), StatusCode.KO).setMessage(MANAGEMENTCONTRACT_NOT_FOUND)); continue; } final Set<String> checkParentId = acm.getCheckParentId(); if (checkParentId != null) { if (!checkParentId.isEmpty() && IngestContractCheckState.UNAUTHORIZED.equals(acm.getCheckParentLink())) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause .rejectInconsistentContract(acm.getName(), "attachments not authorized but checkParentId field is not empty") .getReason(), StatusCode.KO)); continue; } if (!validationService.checkIfAllUnitExist(checkParentId)) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause .rejectAuNotFoundInDatabase(String.join(" ", checkParentId)) .getReason(), StatusCode.KO)); continue; } } if (null != acm.getId()) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause.rejectIdNotAllowedInCreate(acm.getName()) .getReason(), StatusCode.KO)); continue; } if (!acm.isEveryFormatType() && (acm.getFormatType() == null || acm.getFormatType().isEmpty())) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), EVERYFORMAT_LIST_EMPTY, StatusCode.KO).setMessage(FORMAT_MUST_NOT_BE_EMPTY)); continue; } if (acm.isEveryFormatType() && acm.getFormatType() != null) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), EVERYFORMAT_LIST_NOT_EMPTY, StatusCode.KO).setMessage(FORMAT_MUST_BE_EMPTY)); continue; } if (validationService.validateContract(acm, acm.getName(), error)) { acm.setId(GUIDFactory.newContractGUID(ParameterHelper.getTenantParameter()).getId()); } if (acm.getTenant() == null) { acm.setTenant(ParameterHelper.getTenantParameter()); } if (slaveMode) { final Optional<GenericRejectionCause> result = validationService.checkEmptyIdentifierSlaveModeValidator().validate(acm, acm.getIdentifier()); result.ifPresent(t -> error .addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), result.get().getReason(), StatusCode.KO).setMessage(EMPTY_REQUIRED_FIELD) ) ); } } if (null != error.getErrors() && !error.getErrors().isEmpty()) { final String errorsDetails = error.getErrors().stream().map(VitamError::getDescription).distinct() .collect(Collectors.joining(",")); logbookService .logValidationError(errorsDetails, CONTRACTS_IMPORT_EVENT, error.getErrors().get(0).getMessage()); return error; } contractsToPersist = JsonHandler.createArrayNode(); for (final IngestContractModel acm : contractModelList) { ContractHelper.setIdentifier(slaveMode, acm, vitamCounterService, SequenceType.INGEST_CONTRACT_SEQUENCE); final ObjectNode ingestContractNode = (ObjectNode) JsonHandler.toJsonNode(acm); JsonNode hashId = ingestContractNode.remove(VitamFieldsHelper.id()); if (hashId != null) { ingestContractNode.set(UND_ID, hashId); } JsonNode hashTenant = ingestContractNode.remove(VitamFieldsHelper.tenant()); if (hashTenant != null) { ingestContractNode.set(UND_TENANT, hashTenant); } contractsToPersist.add(ingestContractNode); } mongoAccess.insertDocuments(contractsToPersist, FunctionalAdminCollections.INGEST_CONTRACT).close(); functionalBackupService.saveCollectionAndSequence( eip, CONTRACT_BACKUP_EVENT, FunctionalAdminCollections.INGEST_CONTRACT, eip.toString() ); logbookService.logSuccess(); return new RequestResponseOK<IngestContractModel>().addAllResults(contractModelList) .setHttpCode(Response.Status.CREATED.getStatusCode()); } catch (SchemaValidationException | BadRequestException exp) { LOGGER.error(exp); final String err = new StringBuilder("Import ingest contracts error > ").append(exp.getMessage()).toString(); logbookService.logValidationError(err, CONTRACTS_IMPORT_EVENT, CONTRACT_BAD_REQUEST); return getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), exp.getMessage(), StatusCode.KO).setDescription(err).setHttpCode(Response.Status.BAD_REQUEST.getStatusCode()); } catch (final Exception exp) { LOGGER.error(exp); final String err = new StringBuilder("Import ingest contracts error > ").append(exp.getMessage()).toString(); logbookService.logFatalError(err, CONTRACTS_IMPORT_EVENT); return error.setCode(VitamCode.GLOBAL_INTERNAL_SERVER_ERROR.getItem()).setDescription(err).setHttpCode( Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); } }
IngestContractImpl implements ContractService<IngestContractModel> { @Override public RequestResponse<IngestContractModel> createContracts(List<IngestContractModel> contractModelList) throws VitamException { ParametersChecker.checkParameter(CONTRACT_IS_MANDATORY_PATAMETER, contractModelList); if (contractModelList.isEmpty()) { return new RequestResponseOK<>(); } contractModelList.forEach(IngestContractModel::setDefaultParams); boolean slaveMode = vitamCounterService .isSlaveFunctionnalCollectionOnTenant(SequenceType.INGEST_CONTRACT_SEQUENCE.getCollection(), ParameterHelper.getTenantParameter()); String operationId = VitamThreadUtils.getVitamSession().getRequestId(); GUID eip = GUIDReader.getGUID(operationId); IngestContractValidationService validationService = new IngestContractValidationService(metaDataClient, managementContractService); ContractLogbookService logbookService = new ContractLogbookService(logbookClient, eip, CONTRACTS_IMPORT_EVENT, CONTRACT_UPDATE_EVENT, CONTRACT_KEY, CONTRACT_CHECK_KEY); logbookService.logStarted(); ArrayNode contractsToPersist = null; final VitamError error = getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), "Ingest contract import error", StatusCode.KO) .setHttpCode(Response.Status.BAD_REQUEST .getStatusCode()); try { for (final IngestContractModel acm : contractModelList) { final String linkParentId = acm.getLinkParentId(); if (linkParentId != null && !validationService.checkIfUnitExist(linkParentId)) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause .rejectAuNotFoundInDatabase(linkParentId) .getReason(), StatusCode.KO)); continue; } final String managementContractId = acm.getManagementContractId(); if (managementContractId != null && !validationService.checkIfManagementContractExists(managementContractId)) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause .rejectMCNotFoundInDatabase(managementContractId) .getReason(), StatusCode.KO).setMessage(MANAGEMENTCONTRACT_NOT_FOUND)); continue; } final Set<String> checkParentId = acm.getCheckParentId(); if (checkParentId != null) { if (!checkParentId.isEmpty() && IngestContractCheckState.UNAUTHORIZED.equals(acm.getCheckParentLink())) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause .rejectInconsistentContract(acm.getName(), "attachments not authorized but checkParentId field is not empty") .getReason(), StatusCode.KO)); continue; } if (!validationService.checkIfAllUnitExist(checkParentId)) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause .rejectAuNotFoundInDatabase(String.join(" ", checkParentId)) .getReason(), StatusCode.KO)); continue; } } if (null != acm.getId()) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause.rejectIdNotAllowedInCreate(acm.getName()) .getReason(), StatusCode.KO)); continue; } if (!acm.isEveryFormatType() && (acm.getFormatType() == null || acm.getFormatType().isEmpty())) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), EVERYFORMAT_LIST_EMPTY, StatusCode.KO).setMessage(FORMAT_MUST_NOT_BE_EMPTY)); continue; } if (acm.isEveryFormatType() && acm.getFormatType() != null) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), EVERYFORMAT_LIST_NOT_EMPTY, StatusCode.KO).setMessage(FORMAT_MUST_BE_EMPTY)); continue; } if (validationService.validateContract(acm, acm.getName(), error)) { acm.setId(GUIDFactory.newContractGUID(ParameterHelper.getTenantParameter()).getId()); } if (acm.getTenant() == null) { acm.setTenant(ParameterHelper.getTenantParameter()); } if (slaveMode) { final Optional<GenericRejectionCause> result = validationService.checkEmptyIdentifierSlaveModeValidator().validate(acm, acm.getIdentifier()); result.ifPresent(t -> error .addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), result.get().getReason(), StatusCode.KO).setMessage(EMPTY_REQUIRED_FIELD) ) ); } } if (null != error.getErrors() && !error.getErrors().isEmpty()) { final String errorsDetails = error.getErrors().stream().map(VitamError::getDescription).distinct() .collect(Collectors.joining(",")); logbookService .logValidationError(errorsDetails, CONTRACTS_IMPORT_EVENT, error.getErrors().get(0).getMessage()); return error; } contractsToPersist = JsonHandler.createArrayNode(); for (final IngestContractModel acm : contractModelList) { ContractHelper.setIdentifier(slaveMode, acm, vitamCounterService, SequenceType.INGEST_CONTRACT_SEQUENCE); final ObjectNode ingestContractNode = (ObjectNode) JsonHandler.toJsonNode(acm); JsonNode hashId = ingestContractNode.remove(VitamFieldsHelper.id()); if (hashId != null) { ingestContractNode.set(UND_ID, hashId); } JsonNode hashTenant = ingestContractNode.remove(VitamFieldsHelper.tenant()); if (hashTenant != null) { ingestContractNode.set(UND_TENANT, hashTenant); } contractsToPersist.add(ingestContractNode); } mongoAccess.insertDocuments(contractsToPersist, FunctionalAdminCollections.INGEST_CONTRACT).close(); functionalBackupService.saveCollectionAndSequence( eip, CONTRACT_BACKUP_EVENT, FunctionalAdminCollections.INGEST_CONTRACT, eip.toString() ); logbookService.logSuccess(); return new RequestResponseOK<IngestContractModel>().addAllResults(contractModelList) .setHttpCode(Response.Status.CREATED.getStatusCode()); } catch (SchemaValidationException | BadRequestException exp) { LOGGER.error(exp); final String err = new StringBuilder("Import ingest contracts error > ").append(exp.getMessage()).toString(); logbookService.logValidationError(err, CONTRACTS_IMPORT_EVENT, CONTRACT_BAD_REQUEST); return getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), exp.getMessage(), StatusCode.KO).setDescription(err).setHttpCode(Response.Status.BAD_REQUEST.getStatusCode()); } catch (final Exception exp) { LOGGER.error(exp); final String err = new StringBuilder("Import ingest contracts error > ").append(exp.getMessage()).toString(); logbookService.logFatalError(err, CONTRACTS_IMPORT_EVENT); return error.setCode(VitamCode.GLOBAL_INTERNAL_SERVER_ERROR.getItem()).setDescription(err).setHttpCode( Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); } } }
IngestContractImpl implements ContractService<IngestContractModel> { @Override public RequestResponse<IngestContractModel> createContracts(List<IngestContractModel> contractModelList) throws VitamException { ParametersChecker.checkParameter(CONTRACT_IS_MANDATORY_PATAMETER, contractModelList); if (contractModelList.isEmpty()) { return new RequestResponseOK<>(); } contractModelList.forEach(IngestContractModel::setDefaultParams); boolean slaveMode = vitamCounterService .isSlaveFunctionnalCollectionOnTenant(SequenceType.INGEST_CONTRACT_SEQUENCE.getCollection(), ParameterHelper.getTenantParameter()); String operationId = VitamThreadUtils.getVitamSession().getRequestId(); GUID eip = GUIDReader.getGUID(operationId); IngestContractValidationService validationService = new IngestContractValidationService(metaDataClient, managementContractService); ContractLogbookService logbookService = new ContractLogbookService(logbookClient, eip, CONTRACTS_IMPORT_EVENT, CONTRACT_UPDATE_EVENT, CONTRACT_KEY, CONTRACT_CHECK_KEY); logbookService.logStarted(); ArrayNode contractsToPersist = null; final VitamError error = getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), "Ingest contract import error", StatusCode.KO) .setHttpCode(Response.Status.BAD_REQUEST .getStatusCode()); try { for (final IngestContractModel acm : contractModelList) { final String linkParentId = acm.getLinkParentId(); if (linkParentId != null && !validationService.checkIfUnitExist(linkParentId)) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause .rejectAuNotFoundInDatabase(linkParentId) .getReason(), StatusCode.KO)); continue; } final String managementContractId = acm.getManagementContractId(); if (managementContractId != null && !validationService.checkIfManagementContractExists(managementContractId)) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause .rejectMCNotFoundInDatabase(managementContractId) .getReason(), StatusCode.KO).setMessage(MANAGEMENTCONTRACT_NOT_FOUND)); continue; } final Set<String> checkParentId = acm.getCheckParentId(); if (checkParentId != null) { if (!checkParentId.isEmpty() && IngestContractCheckState.UNAUTHORIZED.equals(acm.getCheckParentLink())) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause .rejectInconsistentContract(acm.getName(), "attachments not authorized but checkParentId field is not empty") .getReason(), StatusCode.KO)); continue; } if (!validationService.checkIfAllUnitExist(checkParentId)) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause .rejectAuNotFoundInDatabase(String.join(" ", checkParentId)) .getReason(), StatusCode.KO)); continue; } } if (null != acm.getId()) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause.rejectIdNotAllowedInCreate(acm.getName()) .getReason(), StatusCode.KO)); continue; } if (!acm.isEveryFormatType() && (acm.getFormatType() == null || acm.getFormatType().isEmpty())) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), EVERYFORMAT_LIST_EMPTY, StatusCode.KO).setMessage(FORMAT_MUST_NOT_BE_EMPTY)); continue; } if (acm.isEveryFormatType() && acm.getFormatType() != null) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), EVERYFORMAT_LIST_NOT_EMPTY, StatusCode.KO).setMessage(FORMAT_MUST_BE_EMPTY)); continue; } if (validationService.validateContract(acm, acm.getName(), error)) { acm.setId(GUIDFactory.newContractGUID(ParameterHelper.getTenantParameter()).getId()); } if (acm.getTenant() == null) { acm.setTenant(ParameterHelper.getTenantParameter()); } if (slaveMode) { final Optional<GenericRejectionCause> result = validationService.checkEmptyIdentifierSlaveModeValidator().validate(acm, acm.getIdentifier()); result.ifPresent(t -> error .addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), result.get().getReason(), StatusCode.KO).setMessage(EMPTY_REQUIRED_FIELD) ) ); } } if (null != error.getErrors() && !error.getErrors().isEmpty()) { final String errorsDetails = error.getErrors().stream().map(VitamError::getDescription).distinct() .collect(Collectors.joining(",")); logbookService .logValidationError(errorsDetails, CONTRACTS_IMPORT_EVENT, error.getErrors().get(0).getMessage()); return error; } contractsToPersist = JsonHandler.createArrayNode(); for (final IngestContractModel acm : contractModelList) { ContractHelper.setIdentifier(slaveMode, acm, vitamCounterService, SequenceType.INGEST_CONTRACT_SEQUENCE); final ObjectNode ingestContractNode = (ObjectNode) JsonHandler.toJsonNode(acm); JsonNode hashId = ingestContractNode.remove(VitamFieldsHelper.id()); if (hashId != null) { ingestContractNode.set(UND_ID, hashId); } JsonNode hashTenant = ingestContractNode.remove(VitamFieldsHelper.tenant()); if (hashTenant != null) { ingestContractNode.set(UND_TENANT, hashTenant); } contractsToPersist.add(ingestContractNode); } mongoAccess.insertDocuments(contractsToPersist, FunctionalAdminCollections.INGEST_CONTRACT).close(); functionalBackupService.saveCollectionAndSequence( eip, CONTRACT_BACKUP_EVENT, FunctionalAdminCollections.INGEST_CONTRACT, eip.toString() ); logbookService.logSuccess(); return new RequestResponseOK<IngestContractModel>().addAllResults(contractModelList) .setHttpCode(Response.Status.CREATED.getStatusCode()); } catch (SchemaValidationException | BadRequestException exp) { LOGGER.error(exp); final String err = new StringBuilder("Import ingest contracts error > ").append(exp.getMessage()).toString(); logbookService.logValidationError(err, CONTRACTS_IMPORT_EVENT, CONTRACT_BAD_REQUEST); return getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), exp.getMessage(), StatusCode.KO).setDescription(err).setHttpCode(Response.Status.BAD_REQUEST.getStatusCode()); } catch (final Exception exp) { LOGGER.error(exp); final String err = new StringBuilder("Import ingest contracts error > ").append(exp.getMessage()).toString(); logbookService.logFatalError(err, CONTRACTS_IMPORT_EVENT); return error.setCode(VitamCode.GLOBAL_INTERNAL_SERVER_ERROR.getItem()).setDescription(err).setHttpCode( Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); } } IngestContractImpl(MongoDbAccessAdminImpl mongoAccess, VitamCounterService vitamCounterService); @VisibleForTesting  IngestContractImpl(MongoDbAccessAdminImpl mongoAccess, VitamCounterService vitamCounterService,
        MetaDataClient metaDataClient,
        LogbookOperationsClient logbookClient,
        FunctionalBackupService functionalBackupService,
        ContractService<ManagementContractModel> managementContractService); }
IngestContractImpl implements ContractService<IngestContractModel> { @Override public RequestResponse<IngestContractModel> createContracts(List<IngestContractModel> contractModelList) throws VitamException { ParametersChecker.checkParameter(CONTRACT_IS_MANDATORY_PATAMETER, contractModelList); if (contractModelList.isEmpty()) { return new RequestResponseOK<>(); } contractModelList.forEach(IngestContractModel::setDefaultParams); boolean slaveMode = vitamCounterService .isSlaveFunctionnalCollectionOnTenant(SequenceType.INGEST_CONTRACT_SEQUENCE.getCollection(), ParameterHelper.getTenantParameter()); String operationId = VitamThreadUtils.getVitamSession().getRequestId(); GUID eip = GUIDReader.getGUID(operationId); IngestContractValidationService validationService = new IngestContractValidationService(metaDataClient, managementContractService); ContractLogbookService logbookService = new ContractLogbookService(logbookClient, eip, CONTRACTS_IMPORT_EVENT, CONTRACT_UPDATE_EVENT, CONTRACT_KEY, CONTRACT_CHECK_KEY); logbookService.logStarted(); ArrayNode contractsToPersist = null; final VitamError error = getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), "Ingest contract import error", StatusCode.KO) .setHttpCode(Response.Status.BAD_REQUEST .getStatusCode()); try { for (final IngestContractModel acm : contractModelList) { final String linkParentId = acm.getLinkParentId(); if (linkParentId != null && !validationService.checkIfUnitExist(linkParentId)) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause .rejectAuNotFoundInDatabase(linkParentId) .getReason(), StatusCode.KO)); continue; } final String managementContractId = acm.getManagementContractId(); if (managementContractId != null && !validationService.checkIfManagementContractExists(managementContractId)) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause .rejectMCNotFoundInDatabase(managementContractId) .getReason(), StatusCode.KO).setMessage(MANAGEMENTCONTRACT_NOT_FOUND)); continue; } final Set<String> checkParentId = acm.getCheckParentId(); if (checkParentId != null) { if (!checkParentId.isEmpty() && IngestContractCheckState.UNAUTHORIZED.equals(acm.getCheckParentLink())) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause .rejectInconsistentContract(acm.getName(), "attachments not authorized but checkParentId field is not empty") .getReason(), StatusCode.KO)); continue; } if (!validationService.checkIfAllUnitExist(checkParentId)) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause .rejectAuNotFoundInDatabase(String.join(" ", checkParentId)) .getReason(), StatusCode.KO)); continue; } } if (null != acm.getId()) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause.rejectIdNotAllowedInCreate(acm.getName()) .getReason(), StatusCode.KO)); continue; } if (!acm.isEveryFormatType() && (acm.getFormatType() == null || acm.getFormatType().isEmpty())) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), EVERYFORMAT_LIST_EMPTY, StatusCode.KO).setMessage(FORMAT_MUST_NOT_BE_EMPTY)); continue; } if (acm.isEveryFormatType() && acm.getFormatType() != null) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), EVERYFORMAT_LIST_NOT_EMPTY, StatusCode.KO).setMessage(FORMAT_MUST_BE_EMPTY)); continue; } if (validationService.validateContract(acm, acm.getName(), error)) { acm.setId(GUIDFactory.newContractGUID(ParameterHelper.getTenantParameter()).getId()); } if (acm.getTenant() == null) { acm.setTenant(ParameterHelper.getTenantParameter()); } if (slaveMode) { final Optional<GenericRejectionCause> result = validationService.checkEmptyIdentifierSlaveModeValidator().validate(acm, acm.getIdentifier()); result.ifPresent(t -> error .addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), result.get().getReason(), StatusCode.KO).setMessage(EMPTY_REQUIRED_FIELD) ) ); } } if (null != error.getErrors() && !error.getErrors().isEmpty()) { final String errorsDetails = error.getErrors().stream().map(VitamError::getDescription).distinct() .collect(Collectors.joining(",")); logbookService .logValidationError(errorsDetails, CONTRACTS_IMPORT_EVENT, error.getErrors().get(0).getMessage()); return error; } contractsToPersist = JsonHandler.createArrayNode(); for (final IngestContractModel acm : contractModelList) { ContractHelper.setIdentifier(slaveMode, acm, vitamCounterService, SequenceType.INGEST_CONTRACT_SEQUENCE); final ObjectNode ingestContractNode = (ObjectNode) JsonHandler.toJsonNode(acm); JsonNode hashId = ingestContractNode.remove(VitamFieldsHelper.id()); if (hashId != null) { ingestContractNode.set(UND_ID, hashId); } JsonNode hashTenant = ingestContractNode.remove(VitamFieldsHelper.tenant()); if (hashTenant != null) { ingestContractNode.set(UND_TENANT, hashTenant); } contractsToPersist.add(ingestContractNode); } mongoAccess.insertDocuments(contractsToPersist, FunctionalAdminCollections.INGEST_CONTRACT).close(); functionalBackupService.saveCollectionAndSequence( eip, CONTRACT_BACKUP_EVENT, FunctionalAdminCollections.INGEST_CONTRACT, eip.toString() ); logbookService.logSuccess(); return new RequestResponseOK<IngestContractModel>().addAllResults(contractModelList) .setHttpCode(Response.Status.CREATED.getStatusCode()); } catch (SchemaValidationException | BadRequestException exp) { LOGGER.error(exp); final String err = new StringBuilder("Import ingest contracts error > ").append(exp.getMessage()).toString(); logbookService.logValidationError(err, CONTRACTS_IMPORT_EVENT, CONTRACT_BAD_REQUEST); return getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), exp.getMessage(), StatusCode.KO).setDescription(err).setHttpCode(Response.Status.BAD_REQUEST.getStatusCode()); } catch (final Exception exp) { LOGGER.error(exp); final String err = new StringBuilder("Import ingest contracts error > ").append(exp.getMessage()).toString(); logbookService.logFatalError(err, CONTRACTS_IMPORT_EVENT); return error.setCode(VitamCode.GLOBAL_INTERNAL_SERVER_ERROR.getItem()).setDescription(err).setHttpCode( Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); } } IngestContractImpl(MongoDbAccessAdminImpl mongoAccess, VitamCounterService vitamCounterService); @VisibleForTesting  IngestContractImpl(MongoDbAccessAdminImpl mongoAccess, VitamCounterService vitamCounterService,
        MetaDataClient metaDataClient,
        LogbookOperationsClient logbookClient,
        FunctionalBackupService functionalBackupService,
        ContractService<ManagementContractModel> managementContractService); @Override RequestResponse<IngestContractModel> createContracts(List<IngestContractModel> contractModelList); @Override IngestContractModel findByIdentifier(String identifier); @Override RequestResponseOK<IngestContractModel> findContracts(JsonNode queryDsl); @Override void close(); @Override RequestResponse<IngestContractModel> updateContract(String identifier, JsonNode queryDsl); }
IngestContractImpl implements ContractService<IngestContractModel> { @Override public RequestResponse<IngestContractModel> createContracts(List<IngestContractModel> contractModelList) throws VitamException { ParametersChecker.checkParameter(CONTRACT_IS_MANDATORY_PATAMETER, contractModelList); if (contractModelList.isEmpty()) { return new RequestResponseOK<>(); } contractModelList.forEach(IngestContractModel::setDefaultParams); boolean slaveMode = vitamCounterService .isSlaveFunctionnalCollectionOnTenant(SequenceType.INGEST_CONTRACT_SEQUENCE.getCollection(), ParameterHelper.getTenantParameter()); String operationId = VitamThreadUtils.getVitamSession().getRequestId(); GUID eip = GUIDReader.getGUID(operationId); IngestContractValidationService validationService = new IngestContractValidationService(metaDataClient, managementContractService); ContractLogbookService logbookService = new ContractLogbookService(logbookClient, eip, CONTRACTS_IMPORT_EVENT, CONTRACT_UPDATE_EVENT, CONTRACT_KEY, CONTRACT_CHECK_KEY); logbookService.logStarted(); ArrayNode contractsToPersist = null; final VitamError error = getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), "Ingest contract import error", StatusCode.KO) .setHttpCode(Response.Status.BAD_REQUEST .getStatusCode()); try { for (final IngestContractModel acm : contractModelList) { final String linkParentId = acm.getLinkParentId(); if (linkParentId != null && !validationService.checkIfUnitExist(linkParentId)) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause .rejectAuNotFoundInDatabase(linkParentId) .getReason(), StatusCode.KO)); continue; } final String managementContractId = acm.getManagementContractId(); if (managementContractId != null && !validationService.checkIfManagementContractExists(managementContractId)) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause .rejectMCNotFoundInDatabase(managementContractId) .getReason(), StatusCode.KO).setMessage(MANAGEMENTCONTRACT_NOT_FOUND)); continue; } final Set<String> checkParentId = acm.getCheckParentId(); if (checkParentId != null) { if (!checkParentId.isEmpty() && IngestContractCheckState.UNAUTHORIZED.equals(acm.getCheckParentLink())) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause .rejectInconsistentContract(acm.getName(), "attachments not authorized but checkParentId field is not empty") .getReason(), StatusCode.KO)); continue; } if (!validationService.checkIfAllUnitExist(checkParentId)) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause .rejectAuNotFoundInDatabase(String.join(" ", checkParentId)) .getReason(), StatusCode.KO)); continue; } } if (null != acm.getId()) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), GenericRejectionCause.rejectIdNotAllowedInCreate(acm.getName()) .getReason(), StatusCode.KO)); continue; } if (!acm.isEveryFormatType() && (acm.getFormatType() == null || acm.getFormatType().isEmpty())) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), EVERYFORMAT_LIST_EMPTY, StatusCode.KO).setMessage(FORMAT_MUST_NOT_BE_EMPTY)); continue; } if (acm.isEveryFormatType() && acm.getFormatType() != null) { error.addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), EVERYFORMAT_LIST_NOT_EMPTY, StatusCode.KO).setMessage(FORMAT_MUST_BE_EMPTY)); continue; } if (validationService.validateContract(acm, acm.getName(), error)) { acm.setId(GUIDFactory.newContractGUID(ParameterHelper.getTenantParameter()).getId()); } if (acm.getTenant() == null) { acm.setTenant(ParameterHelper.getTenantParameter()); } if (slaveMode) { final Optional<GenericRejectionCause> result = validationService.checkEmptyIdentifierSlaveModeValidator().validate(acm, acm.getIdentifier()); result.ifPresent(t -> error .addToErrors(getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), result.get().getReason(), StatusCode.KO).setMessage(EMPTY_REQUIRED_FIELD) ) ); } } if (null != error.getErrors() && !error.getErrors().isEmpty()) { final String errorsDetails = error.getErrors().stream().map(VitamError::getDescription).distinct() .collect(Collectors.joining(",")); logbookService .logValidationError(errorsDetails, CONTRACTS_IMPORT_EVENT, error.getErrors().get(0).getMessage()); return error; } contractsToPersist = JsonHandler.createArrayNode(); for (final IngestContractModel acm : contractModelList) { ContractHelper.setIdentifier(slaveMode, acm, vitamCounterService, SequenceType.INGEST_CONTRACT_SEQUENCE); final ObjectNode ingestContractNode = (ObjectNode) JsonHandler.toJsonNode(acm); JsonNode hashId = ingestContractNode.remove(VitamFieldsHelper.id()); if (hashId != null) { ingestContractNode.set(UND_ID, hashId); } JsonNode hashTenant = ingestContractNode.remove(VitamFieldsHelper.tenant()); if (hashTenant != null) { ingestContractNode.set(UND_TENANT, hashTenant); } contractsToPersist.add(ingestContractNode); } mongoAccess.insertDocuments(contractsToPersist, FunctionalAdminCollections.INGEST_CONTRACT).close(); functionalBackupService.saveCollectionAndSequence( eip, CONTRACT_BACKUP_EVENT, FunctionalAdminCollections.INGEST_CONTRACT, eip.toString() ); logbookService.logSuccess(); return new RequestResponseOK<IngestContractModel>().addAllResults(contractModelList) .setHttpCode(Response.Status.CREATED.getStatusCode()); } catch (SchemaValidationException | BadRequestException exp) { LOGGER.error(exp); final String err = new StringBuilder("Import ingest contracts error > ").append(exp.getMessage()).toString(); logbookService.logValidationError(err, CONTRACTS_IMPORT_EVENT, CONTRACT_BAD_REQUEST); return getVitamError(VitamCode.CONTRACT_VALIDATION_ERROR.getItem(), exp.getMessage(), StatusCode.KO).setDescription(err).setHttpCode(Response.Status.BAD_REQUEST.getStatusCode()); } catch (final Exception exp) { LOGGER.error(exp); final String err = new StringBuilder("Import ingest contracts error > ").append(exp.getMessage()).toString(); logbookService.logFatalError(err, CONTRACTS_IMPORT_EVENT); return error.setCode(VitamCode.GLOBAL_INTERNAL_SERVER_ERROR.getItem()).setDescription(err).setHttpCode( Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); } } IngestContractImpl(MongoDbAccessAdminImpl mongoAccess, VitamCounterService vitamCounterService); @VisibleForTesting  IngestContractImpl(MongoDbAccessAdminImpl mongoAccess, VitamCounterService vitamCounterService,
        MetaDataClient metaDataClient,
        LogbookOperationsClient logbookClient,
        FunctionalBackupService functionalBackupService,
        ContractService<ManagementContractModel> managementContractService); @Override RequestResponse<IngestContractModel> createContracts(List<IngestContractModel> contractModelList); @Override IngestContractModel findByIdentifier(String identifier); @Override RequestResponseOK<IngestContractModel> findContracts(JsonNode queryDsl); @Override void close(); @Override RequestResponse<IngestContractModel> updateContract(String identifier, JsonNode queryDsl); static final String CONTRACT_BACKUP_EVENT; }