method2testcases
stringlengths
118
3.08k
### Question: MultiCallback implements Callback { public void addView(final Callback callback) { for (int i = 0; i < mCallbacks.size(); i++) { final CallbackWeakReference reference = mCallbacks.get(i); final Callback item = reference.get(); if (item == null) { mCallbacks.remove(reference); } } mCallbacks.addIfAbsent(new CallbackWeakReference(callback)); } MultiCallback(); MultiCallback(final boolean useViewInvalidate); @Override void invalidateDrawable(@NonNull final Drawable who); @Override void scheduleDrawable(@NonNull final Drawable who, @NonNull final Runnable what, final long when); @Override void unscheduleDrawable(@NonNull final Drawable who, @NonNull final Runnable what); void addView(final Callback callback); void removeView(final Callback callback); }### Answer: @Test public void testViewInvalidate() { final MultiCallback viewInvalidateMultiCallback = new MultiCallback(true); viewInvalidateMultiCallback.addView(view); drawable.setCallback(viewInvalidateMultiCallback); drawable.invalidateSelf(); verify(view).invalidate(); }
### Question: GifOptions { public void setInSampleSize(@IntRange(from = 1, to = Character.MAX_VALUE) int inSampleSize) { if (inSampleSize < 1 || inSampleSize > Character.MAX_VALUE) { this.inSampleSize = 1; } else { this.inSampleSize = (char) inSampleSize; } } GifOptions(); void setInSampleSize(@IntRange(from = 1, to = Character.MAX_VALUE) int inSampleSize); void setInIsOpaque(boolean inIsOpaque); }### Answer: @Test public void setInSampleSize() { gifOptions.setInSampleSize(2); assertThat(gifOptions.inSampleSize).isEqualTo((char) 2); }
### Question: GifOptions { public void setInIsOpaque(boolean inIsOpaque) { this.inIsOpaque = inIsOpaque; } GifOptions(); void setInSampleSize(@IntRange(from = 1, to = Character.MAX_VALUE) int inSampleSize); void setInIsOpaque(boolean inIsOpaque); }### Answer: @Test public void setInIsOpaque() { gifOptions.setInIsOpaque(true); assertThat(gifOptions.inIsOpaque).isTrue(); }
### Question: PreservationFinalizationPlugin extends ActionHandler { @Override public ItemStatus execute(WorkerParameters param, HandlerIO handler) throws ProcessingException { try { storeReportToWorkspace(param, handler); storeReportToOffers(param.getContainerName()); cleanupReport(param.getRequestId()); } catch (Exception e) { LOGGER.error("Error on finalization", e); ObjectNode eventDetails = JsonHandler.createObjectNode(); eventDetails.put("error", e.getMessage()); return buildItemStatus(PLUGIN_NAME, FATAL, eventDetails); } return buildItemStatus(PLUGIN_NAME, OK, EventDetails.of("Finalization ok.")); } PreservationFinalizationPlugin(); @VisibleForTesting PreservationFinalizationPlugin(PreservationReportService preservationReportService, LogbookOperationsClient logbookOperationsClient); @Override ItemStatus execute(WorkerParameters param, HandlerIO handler); }### Answer: @Test @RunWithCustomExecutor public void should_finalize_preservation_report() throws Exception { File newLocalFile = tempFolder.newFile(); TestHandlerIO handlerIO = new TestHandlerIO(); handlerIO.setNewLocalFile(newLocalFile); try (InputStream resourceAsStream = getClass().getResourceAsStream("/preservation/preservationRequest"); InputStream scenarioInputStream = getClass().getResourceAsStream("/preservation/preservationDocument")) { populateTestHandlerIo(handlerIO, resourceAsStream, scenarioInputStream); JsonNode logbookOperationJson = JsonHandler.getFromInputStream(getClass().getResourceAsStream("/preservation/logbookOperationOk.json")); given(logbookOperationsClient.selectOperationById(anyString())).willReturn(logbookOperationJson); when(preservationReportService.isReportWrittenInWorkspace(anyString())).thenReturn(false); ItemStatus itemStatus = plugin.execute(parameter, handlerIO); assertThat(itemStatus.getGlobalStatus()).isEqualTo(StatusCode.OK); assertThat(itemStatus.getItemId()).isEqualTo("PRESERVATION_FINALIZATION"); } }
### Question: IngestCleanupDeleteUnitPlugin extends ActionHandler { @Override public List<ItemStatus> executeList(WorkerParameters param, HandlerIO handler) { try { return processUnits(param.getObjectMetadataList()); } catch (ProcessingStatusException e) { LOGGER.error("Unit purge failed with status " + e.getStatusCode(), e); return singletonList(buildItemStatus(INGEST_CLEANUP_DELETE_UNIT, e.getStatusCode(), e.getEventDetails())); } } IngestCleanupDeleteUnitPlugin(); @VisibleForTesting IngestCleanupDeleteUnitPlugin( PurgeDeleteService purgeDeleteService); @Override ItemStatus execute(WorkerParameters param, HandlerIO handler); @Override List<ItemStatus> executeList(WorkerParameters param, HandlerIO handler); static String getId(); }### Answer: @Test @RunWithCustomExecutor public void testExecuteList_OK() throws Exception { WorkerParameters params = WorkerParametersFactory.newWorkerParameters() .setObjectMetadataList(Arrays.asList( buildUnitParams(1), buildUnitParams(2), buildUnitParams(3))); List<ItemStatus> itemStatus = instance.executeList(params, handler); assertThat(itemStatus).hasSize(3); assertThat(itemStatus).allMatch(i -> i.getGlobalStatus() == StatusCode.OK); Map<String, String> unitIdsWithStrategies = ImmutableMap.of( "id_unit_1", "default-fake", "id_unit_2", "default-fake", "id_unit_3", "default-fake"); verify(purgeDeleteService).deleteUnits(eq(unitIdsWithStrategies)); }
### Question: PurgeReportService { public void exportAccessionRegisters(String processId) throws ProcessingStatusException { try (BatchReportClient batchReportClient = batchReportClientFactory.getClient()) { batchReportClient.generatePurgeAccessionRegisterReport( processId, new ReportExportRequest(ACCESSION_REGISTER_REPORT_JSONL)); } catch (VitamClientInternalException e) { throw new ProcessingStatusException(StatusCode.FATAL, "Could not generate purge accession register reports (" + processId + ")", e); } } PurgeReportService(); @VisibleForTesting PurgeReportService( BatchReportClientFactory batchReportClientFactory, WorkspaceClientFactory workspaceClientFactory); void appendUnitEntries(String processId, List<PurgeUnitReportEntry> entries); void appendObjectGroupEntries(String processId, List<PurgeObjectGroupReportEntry> entries); CloseableIterator<String> exportDistinctObjectGroups(String processId); void exportAccessionRegisters(String processId); void cleanupReport(String processId); }### Answer: @Test @RunWithCustomExecutor public void exportAccessionRegisters() throws Exception { InputStream is = PropertiesUtils.getResourceAsStream( "EliminationAction/EliminationActionObjectGroupReportService/objectGroupReport.jsonl"); Response response = mock(Response.class); doReturn(is).when(response).readEntity(InputStream.class); doReturn(response).when(workspaceClient).getObject(PROC_ID, OBJECT_GROUP_REPORT_JSONL); instance.exportAccessionRegisters(PROC_ID); ArgumentCaptor<ReportExportRequest> reportExportRequestArgumentCaptor = ArgumentCaptor.forClass(ReportExportRequest.class); verify(batchReportClient) .generatePurgeAccessionRegisterReport(eq(PROC_ID), reportExportRequestArgumentCaptor.capture()); assertThat(reportExportRequestArgumentCaptor.getValue().getFilename()) .isEqualTo(ACCESSION_REGISTER_REPORT_JSONL); }
### Question: PurgeReportService { public void cleanupReport(String processId) throws ProcessingStatusException { try (BatchReportClient batchReportClient = batchReportClientFactory.getClient()) { batchReportClient.cleanupReport(processId, ReportType.PURGE_UNIT); batchReportClient.cleanupReport(processId, ReportType.PURGE_OBJECTGROUP); } catch (VitamClientInternalException e) { throw new ProcessingStatusException(StatusCode.FATAL, "Could not cleanup purge reports (" + processId + ")", e); } } PurgeReportService(); @VisibleForTesting PurgeReportService( BatchReportClientFactory batchReportClientFactory, WorkspaceClientFactory workspaceClientFactory); void appendUnitEntries(String processId, List<PurgeUnitReportEntry> entries); void appendObjectGroupEntries(String processId, List<PurgeObjectGroupReportEntry> entries); CloseableIterator<String> exportDistinctObjectGroups(String processId); void exportAccessionRegisters(String processId); void cleanupReport(String processId); }### Answer: @Test @RunWithCustomExecutor public void cleanupReport() throws Exception { instance.cleanupReport(PROC_ID); verify(batchReportClient).cleanupReport(PROC_ID, ReportType.PURGE_OBJECTGROUP); verify(batchReportClient).cleanupReport(PROC_ID, ReportType.PURGE_UNIT); }
### Question: PurgeAccessionRegisterPreparationHandler extends ActionHandler { @Override public ItemStatus execute(WorkerParameters param, HandlerIO handler) throws ProcessingException { try { exportAccessionRegister(param.getContainerName()); LOGGER.info("Purge accession register preparation succeeded"); return buildItemStatus(actionId, StatusCode.OK, null); } catch (ProcessingStatusException e) { LOGGER.error( String.format("Purge accession register preparation failed with status [%s]", e.getStatusCode()), e); return buildItemStatus(actionId, e.getStatusCode(), e.getEventDetails()); } } PurgeAccessionRegisterPreparationHandler(String actionId); @VisibleForTesting protected PurgeAccessionRegisterPreparationHandler( String actionId, PurgeReportService purgeReportService); @Override ItemStatus execute(WorkerParameters param, HandlerIO handler); @Override void checkMandatoryIOParameter(HandlerIO handler); }### Answer: @Test @RunWithCustomExecutor public void testExecuteSuccess() throws Exception { instance.execute(params, handler); verify(purgeReportService) .exportAccessionRegisters(VitamThreadUtils.getVitamSession().getRequestId()); }
### Question: PurgeDeleteService { public void deleteObjects(Map<String,String> objectsGuidsWithStrategies) throws StorageServerClientException { storageDelete(objectsGuidsWithStrategies, DataCategory.OBJECT, Strings.EMPTY); } @VisibleForTesting PurgeDeleteService(StorageClientFactory storageClientFactory, MetaDataClientFactory metaDataClientFactory, LogbookLifeCyclesClientFactory logbookLifeCyclesClientFactory); PurgeDeleteService(); void deleteObjects(Map<String,String> objectsGuidsWithStrategies); void deleteObjectGroups(Map<String,String> objectGroupsGuidsWithStrategies); void deleteUnits(Map<String,String> unitsGuidsWithStrategies); void detachObjectGroupFromDeleteParentUnits(String objectGroupId, Set<String> parentUnitsToRemove); }### Answer: @Test @RunWithCustomExecutor public void deleteObjects() throws Exception { instance.deleteObjects(ImmutableMap.of("id1", VitamConfiguration.getDefaultStrategy(), "id2", VitamConfiguration.getDefaultStrategy(), "id3", VitamConfiguration.getDefaultStrategy())); verify(storageClient).delete(VitamConfiguration.getDefaultStrategy(), DataCategory.OBJECT, "id1"); verify(storageClient).delete(VitamConfiguration.getDefaultStrategy(), DataCategory.OBJECT, "id2"); verify(storageClient).delete(VitamConfiguration.getDefaultStrategy(), DataCategory.OBJECT, "id3"); }
### Question: PurgeDeleteService { public void detachObjectGroupFromDeleteParentUnits(String objectGroupId, Set<String> parentUnitsToRemove) throws ProcessingStatusException { try (MetaDataClient metaDataClient = metaDataClientFactory.getClient()) { UpdateMultiQuery updateMultiQuery = new UpdateMultiQuery(); updateMultiQuery.addActions( pull(VitamFieldsHelper.unitups(), parentUnitsToRemove.toArray(new String[0])), add(VitamFieldsHelper.operations(), VitamThreadUtils.getVitamSession().getRequestId()) ); metaDataClient.updateObjectGroupById(updateMultiQuery.getFinalUpdate(), objectGroupId); } catch (MetaDataClientServerException | MetaDataExecutionException | InvalidParseOperationException | InvalidCreateOperationException e) { throw new ProcessingStatusException(StatusCode.FATAL, "An error occurred during object group detachment", e); } } @VisibleForTesting PurgeDeleteService(StorageClientFactory storageClientFactory, MetaDataClientFactory metaDataClientFactory, LogbookLifeCyclesClientFactory logbookLifeCyclesClientFactory); PurgeDeleteService(); void deleteObjects(Map<String,String> objectsGuidsWithStrategies); void deleteObjectGroups(Map<String,String> objectGroupsGuidsWithStrategies); void deleteUnits(Map<String,String> unitsGuidsWithStrategies); void detachObjectGroupFromDeleteParentUnits(String objectGroupId, Set<String> parentUnitsToRemove); }### Answer: @Test @RunWithCustomExecutor public void detachObjectGroupFromDeleteParentUnits() throws Exception { String opId = GUIDFactory.newGUID().toString(); String gotId = GUIDFactory.newGUID().toString(); instance.detachObjectGroupFromDeleteParentUnits(gotId, new HashSet<>(Arrays.asList("unit1", "unit2"))); verify(metaDataClient).updateObjectGroupById(any(), eq(gotId)); }
### Question: PurgeDetachObjectGroupPlugin extends ActionHandler { @Override public ItemStatus execute(WorkerParameters param, HandlerIO handler) throws ProcessingException { String objectGroupId = param.getObjectName(); try { Set<String> parentUnitsToRemove = getParentUnitsToRemove(param); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Detaching deleted parents [" + String.join(", ", parentUnitsToRemove) + "]" + " from object group " + objectGroupId); } purgeDeleteService.detachObjectGroupFromDeleteParentUnits(objectGroupId, parentUnitsToRemove); LOGGER.info("Object group " + objectGroupId + " detachment from parents succeeded"); return buildItemStatus(actionId, StatusCode.OK, null); } catch (ProcessingStatusException e) { LOGGER.error("Object group " + objectGroupId + " detachment from parents failed with status" + " [" + e.getStatusCode() + "]", e); return buildItemStatus(actionId, e.getStatusCode(), e.getEventDetails()); } } PurgeDetachObjectGroupPlugin(String actionId); @VisibleForTesting protected PurgeDetachObjectGroupPlugin( String actionId, PurgeDeleteService purgeDeleteService); @Override ItemStatus execute(WorkerParameters param, HandlerIO handler); @Override void checkMandatoryIOParameter(HandlerIO handler); }### Answer: @Test @RunWithCustomExecutor public void testExecute_OK() throws Exception { ItemStatus itemStatus = instance.execute(params, handler); assertThat(itemStatus.getGlobalStatus()).isEqualTo(StatusCode.OK); verify(purgeDeleteService) .detachObjectGroupFromDeleteParentUnits(eq("id_got_1"), eq(new HashSet<>(singletonList("id_unit_1")))); } @Test @RunWithCustomExecutor public void testExecute_WhenExceptionExpectFatal() throws Exception { doThrow(new ProcessingStatusException(StatusCode.FATAL, null)).when(purgeDeleteService) .detachObjectGroupFromDeleteParentUnits(any(), any()); ItemStatus itemStatus = instance.execute(params, handler); assertThat(itemStatus.getGlobalStatus()).isEqualTo(StatusCode.FATAL); }
### Question: ObjectGroupGraphComputePlugin extends AbstractGraphComputePlugin { GraphComputeResponse.GraphComputeAction getGraphComputeAction() { return GraphComputeResponse.GraphComputeAction.OBJECTGROUP; } ObjectGroupGraphComputePlugin(); @VisibleForTesting ObjectGroupGraphComputePlugin(MetaDataClientFactory metaDataClientFactory); }### Answer: @Test public void testGetGraphComputeAction() { GraphComputeAction action = objectGroupGraphComputePlugin.getGraphComputeAction(); Assertions.assertThat(action).isEqualTo(GraphComputeAction.OBJECTGROUP); }
### Question: ObjectGroupGraphComputePlugin extends AbstractGraphComputePlugin { String getPluginKeyName() { return OBJECT_GROUP_GRAPH_COMPUTE; } ObjectGroupGraphComputePlugin(); @VisibleForTesting ObjectGroupGraphComputePlugin(MetaDataClientFactory metaDataClientFactory); }### Answer: @Test public void testGetPluginKeyName() { String pluginName = objectGroupGraphComputePlugin.getPluginKeyName(); Assertions.assertThat(pluginName).isEqualTo("OBJECT_GROUP_GRAPH_COMPUTE"); }
### Question: GraphCycleDetector { public void removeRelations(String child, Collection<String> parents) { for (String parent : parents) { childToParents.removeMapping(child, parent); parentToChildren.removeMapping(parent, child); } } void addRelations(String child, Collection<String> parents); void removeRelations(String child, Collection<String> parents); Set<String> checkCycles(); }### Answer: @Test public void testRemoveRelations() { GraphCycleDetector instance = new GraphCycleDetector(); instance.addRelations("1", Arrays.asList("2", "3", "4")); instance.removeRelations("1", Arrays.asList("3")); instance.removeRelations("1", Arrays.asList("3")); assertThat(instance.getChildToParents().keySet()).hasSize(1); assertThat(instance.getChildToParents().get("1")).containsExactlyInAnyOrder("2", "4"); assertThat(instance.getParentToChildren().keySet()).hasSize(2); assertThat(instance.getParentToChildren().get("2")).containsExactlyInAnyOrder("1"); assertThat(instance.getParentToChildren().get("4")).containsExactlyInAnyOrder("1"); }
### Question: GraphCycleDetector { public Set<String> checkCycles() { removeNodesWithoutParents(); removeNodesWithoutChildren(); return getCycles(); } void addRelations(String child, Collection<String> parents); void removeRelations(String child, Collection<String> parents); Set<String> checkCycles(); }### Answer: @Test public void testCheckCycles_Empty() { GraphCycleDetector instance = new GraphCycleDetector(); Set<String> cycles = instance.checkCycles(); assertThat(cycles).isEmpty(); }
### Question: AbstractGraphComputePlugin extends ActionHandler { @Override public ItemStatus execute(WorkerParameters param, HandlerIO handler) throws ProcessingException { throw new ProcessingException("No need to implements method"); } AbstractGraphComputePlugin(); @VisibleForTesting AbstractGraphComputePlugin(MetaDataClientFactory metaDataClientFactory); @Override ItemStatus execute(WorkerParameters param, HandlerIO handler); @Override List<ItemStatus> executeList(WorkerParameters workerParameters, HandlerIO handler); @Override void checkMandatoryIOParameter(HandlerIO handler); }### Answer: @Test(expected = ProcessingException.class) public void executeShouldThrowException() throws ProcessingException { HandlerIO handlerIO = mock(HandlerIO.class); abstractGraphComputePlugin.execute(null, handlerIO); }
### Question: UnitGraphComputePlugin extends AbstractGraphComputePlugin { GraphComputeResponse.GraphComputeAction getGraphComputeAction() { return GraphComputeResponse.GraphComputeAction.UNIT; } UnitGraphComputePlugin(); @VisibleForTesting UnitGraphComputePlugin(MetaDataClientFactory metaDataClientFactory); }### Answer: @Test public void testGetGraphComputeAction() { GraphComputeResponse.GraphComputeAction action = unitGraphComputePlugin.getGraphComputeAction(); Assertions.assertThat(action).isEqualTo(GraphComputeResponse.GraphComputeAction.UNIT); }
### Question: UnitGraphComputePlugin extends AbstractGraphComputePlugin { String getPluginKeyName() { return UNIT_GRAPH_COMPUTE; } UnitGraphComputePlugin(); @VisibleForTesting UnitGraphComputePlugin(MetaDataClientFactory metaDataClientFactory); }### Answer: @Test public void testGetPluginKeyName() { String pluginName = unitGraphComputePlugin.getPluginKeyName(); Assertions.assertThat(pluginName).isEqualTo("UNIT_GRAPH_COMPUTE"); }
### Question: ComputedInheritedRulesCheckDistributionThreshold extends CheckDistributionThresholdBase { @Override public ItemStatus execute(WorkerParameters param, HandlerIO handler) throws ProcessingException { return checkThreshold(handler, VitamConfiguration.getComputedInheritedRulesThreshold(), COMPUTED_INHERITED_RULES_CHECK_DISTRIBUTION_THRESHOLD); } ComputedInheritedRulesCheckDistributionThreshold(); ComputedInheritedRulesCheckDistributionThreshold( MetaDataClientFactory metaDataClientFactory); @Override ItemStatus execute(WorkerParameters param, HandlerIO handler); static String getId(); }### Answer: @Test @RunWithCustomExecutor public void whenCheckDistributionComputedInheritedRulesDefaultThresholdOnSelectQueryThenReturnKO() throws Exception { HandlerIO handlerIO = mock(HandlerIO.class); MetaDataClient metaDataClient = mock(MetaDataClient.class); given(metaDataClientFactory.getClient()).willReturn(metaDataClient); VitamThreadUtils.getVitamSession().setTenantId(TENANT_ID); given(handlerIO.getInput(0)).willReturn("SELECT"); given(handlerIO.getInput(1)).willReturn("query.json"); JsonNode queryUnit = JsonHandler.getFromInputStream( getClass().getResourceAsStream("/computeInheritedRules/select_with_default_threshold.json")); given(handlerIO.getJsonFromWorkspace("query.json")).willReturn(queryUnit); given(metaDataClient.selectUnits(any())).willReturn( JsonHandler.getFromInputStream( getClass().getResourceAsStream("/computeInheritedRules/result_metadata_exeed_threshold.json"))); ItemStatus itemStatus = checkDistributionThresholdBase.execute(WorkerParametersFactory.newWorkerParameters(), handlerIO); assertThat(itemStatus).isNotNull(); assertThat(itemStatus.getData().toString()).isEqualTo("{eventDetailData={\"error\":\"Too many units found. Threshold=100000000, found=100000002\"}}"); assertThat(itemStatus.getGlobalStatus()).isEqualTo(StatusCode.KO); }
### Question: ComputeInheritedRulesFinalizationPlugin extends ActionHandler { @Override public ItemStatus execute(WorkerParameters param, HandlerIO handler) throws ProcessingException { cleanupBatchReport(handler); LOGGER.info("Computed inherited rules finalization succeeded"); return buildItemStatus(COMPUTE_INHERITED_RULES_FINALIZATION, StatusCode.OK, null); } ComputeInheritedRulesFinalizationPlugin(); @VisibleForTesting ComputeInheritedRulesFinalizationPlugin(BatchReportClientFactory batchReportClientFactory); @Override ItemStatus execute(WorkerParameters param, HandlerIO handler); @Override void checkMandatoryIOParameter(HandlerIO handler); static String getId(); }### Answer: @Test public void testCleanup() throws Exception { BatchReportClientFactory batchReportClientFactory = mock(BatchReportClientFactory.class); BatchReportClient batchReportClient = mock(BatchReportClient.class); doReturn(batchReportClient).when(batchReportClientFactory).getClient(); ComputeInheritedRulesFinalizationPlugin instance = new ComputeInheritedRulesFinalizationPlugin(batchReportClientFactory); WorkerParameters workerParameters = mock(WorkerParameters.class); HandlerIO handler = mock(HandlerIO.class); doReturn("container").when(handler).getContainerName(); instance.execute(workerParameters, handler); verify(batchReportClient).cleanupReport("container", ReportType.UNIT_COMPUTED_INHERITED_RULES_INVALIDATION); }
### Question: CheckNoObjectsActionHandler extends ActionHandler { @Override public ItemStatus execute(WorkerParameters params, HandlerIO handlerIO) { checkMandatoryParameters(params); final ItemStatus itemStatus = new ItemStatus(HANDLER_ID); try { checkMandatoryIOParameter(handlerIO); if (!checkNoObjectInManifest(handlerIO)) { itemStatus.increment(StatusCode.KO); } else { itemStatus.increment(StatusCode.OK); } } catch (final ProcessingException e) { LOGGER.error(e); itemStatus.increment(StatusCode.FATAL); } return new ItemStatus(HANDLER_ID).setItemsStatus(HANDLER_ID, itemStatus); } CheckNoObjectsActionHandler(); static final String getId(); @Override ItemStatus execute(WorkerParameters params, HandlerIO handlerIO); @Override void checkMandatoryIOParameter(HandlerIO handler); }### Answer: @Test public void checkManifestHavingObjectOrNot() throws Exception { final CheckNoObjectsActionHandler handler = new CheckNoObjectsActionHandler(); when(handlerIO.getInputStreamFromWorkspace(any())).thenReturn(sedaOK); WorkerParameters parameters = params.putParameterValue(WorkerParameterName.workflowStatusKo, StatusCode.OK.name()) .putParameterValue(WorkerParameterName.logBookTypeProcess, LogbookTypeProcess.INGEST.name()) .setObjectNameList(Lists.newArrayList("objectName.json")); final ItemStatus response = handler.execute(parameters, handlerIO); handler.close(); assertEquals(response.getGlobalStatus(), StatusCode.OK); when(handlerIO.getInputStreamFromWorkspace(any())).thenReturn(sedaKO); final ItemStatus responseKO = handler.execute(parameters, handlerIO); handler.close(); assertEquals(responseKO.getGlobalStatus(), StatusCode.KO); }
### Question: DummyHandler extends ActionHandler { public DummyHandler() { } DummyHandler(); static final String getId(); @Override ItemStatus execute(WorkerParameters param, HandlerIO handler); @Override void checkMandatoryIOParameter(HandlerIO handler); }### Answer: @Test public void dummyHandlerTest() throws Exception { final DummyHandler handler = new DummyHandler(); assertEquals("DummyHandler", DummyHandler.getId()); final ItemStatus response = handler.execute(null, null); assertEquals(response.getGlobalStatus(), StatusCode.UNKNOWN); }
### Question: LogBookEventIterator implements Iterator<LogbookEvent>, Iterable<LogbookEvent> { public Stream<LogbookEvent> stream() { return StreamSupport.stream(spliterator(), false); } LogBookEventIterator(XMLEventReader reader); @Override boolean hasNext(); @Override LogbookEvent next(); @Override Iterator<LogbookEvent> iterator(); @Override Spliterator<LogbookEvent> spliterator(); Stream<LogbookEvent> stream(); }### Answer: @Test public void should_create_iterator_of_events() throws Exception { XMLEventReader xmlEventReader = createXmlEventReader(PropertiesUtils.getResourceAsStream("logbook_events.xml")); LogBookEventIterator logbookEvents = new LogBookEventIterator(xmlEventReader); assertThat(logbookEvents.stream().collect(Collectors.toList())).hasSize(2); }
### Question: LogBookEventIterator implements Iterator<LogbookEvent>, Iterable<LogbookEvent> { @Override public Iterator<LogbookEvent> iterator() { return this; } LogBookEventIterator(XMLEventReader reader); @Override boolean hasNext(); @Override LogbookEvent next(); @Override Iterator<LogbookEvent> iterator(); @Override Spliterator<LogbookEvent> spliterator(); Stream<LogbookEvent> stream(); }### Answer: @Test public void should_return_empty_iterator_when_no_events() throws Exception { XMLEventReader xmlEventReader = createXmlEventReader(new ByteArrayInputStream("<LogBook></LogBook>".getBytes())); LogBookEventIterator logbookEvents = new LogBookEventIterator(xmlEventReader); assertThat(logbookEvents.iterator()).isEmpty(); }
### Question: CheckObjectUnitConsistencyActionHandler extends ActionHandler { @Override public ItemStatus execute(WorkerParameters params, HandlerIO handler) throws ProcessingException { checkMandatoryParameters(params); checkMandatoryIOParameter(handler); final ItemStatus itemStatus = new ItemStatus(HANDLER_ID); try { final List<String> notConformOGs = findObjectGroupsNonReferencedByArchiveUnit(handler, params, itemStatus); if (!notConformOGs.isEmpty()) { itemStatus.setData("errorNumber", notConformOGs.size()); } } catch (Exception e) { LOGGER.error(e); itemStatus.increment(StatusCode.KO); } return new ItemStatus(HANDLER_ID).setItemsStatus(HANDLER_ID, itemStatus); } CheckObjectUnitConsistencyActionHandler(); static final String getId(); @Override ItemStatus execute(WorkerParameters params, HandlerIO handler); @Override void checkMandatoryIOParameter(HandlerIO handler); }### Answer: @Test(expected = ProcessingException.class) public void givenObjectUnitConsistencyWithEmptyHandlerIOThrowsException() throws ProcessingException { final HandlerIO action = new HandlerIOImpl(workspaceClientFactory, logbookLifeCyclesClientFactory, "", "", newArrayList()); handler = new CheckObjectUnitConsistencyActionHandler(); handler.execute(params, action); }
### Question: FastValueAccessMap implements Map<K, V> { @Override public boolean containsValue(Object v) { return valuesReferenceCounter.containsKey(wrapNullValue(v)); } @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object o); @Override boolean containsValue(Object v); @Override V get(Object o); @Override V put(K k, V v); @Override V remove(Object k); @Override void putAll(Map<? extends K, ? extends V> map); @Override void clear(); @Override Set<K> keySet(); @Override Collection<V> values(); @Override Set<Entry<K, V>> entrySet(); }### Answer: @Test public void testContainsValue() { Map<String, Integer> instance = new FastValueAccessMap<>(); instance.put("v0", 0); instance.put("v1", 1); instance.remove("v1"); instance.put("v2", 2); instance.put("v2_bis", 2); instance.put("v3", 3); instance.put("v3_bis", 3); instance.remove("v3"); instance.put("v4", 4); instance.put("v4_bis", 4); instance.remove("v4"); instance.remove("v4_bis"); instance.remove("v5"); assertThat(instance.containsValue(null)).isFalse(); assertThat(instance.containsValue(0)).isTrue(); assertThat(instance.containsValue(1)).isFalse(); assertThat(instance.containsValue(2)).isTrue(); assertThat(instance.containsValue(3)).isTrue(); assertThat(instance.containsValue(4)).isFalse(); assertThat(instance.containsValue(5)).isFalse(); }
### Question: WorkspaceBatchRunner implements Runnable { public void transfer(WorkspaceQueue workspaceQueue) throws WorkerspaceQueueException { ParametersChecker.checkParameter("WorkspaceQueue is required", workspaceQueue); if (!started) { throw new WorkerspaceQueueException("Workspace batch runner not started"); } try { queue.put(workspaceQueue); } catch (InterruptedException e) { LOGGER.error(e); throw new WorkerspaceQueueException(e); } } WorkspaceBatchRunner(HandlerIO handlerAsyncIO, Executor executor, int queueSize); @Override void run(); void transfer(WorkspaceQueue workspaceQueue); void start(); void join(); }### Answer: @Test(expected = WorkerspaceQueueException.class) public void whenTransferThenRunnerNotStartedKO() throws WorkerspaceQueueException { WorkspaceQueue workspaceQueue = mock(WorkspaceQueue.class); HandlerIO handlerIO = mock(HandlerIOImpl.class); Executor executor = mock(Executor.class); WorkspaceBatchRunner workspaceBatchRunner = new WorkspaceBatchRunner(handlerIO, executor, 10); workspaceBatchRunner.transfer(workspaceQueue); }
### Question: WorkspaceBatchRunner implements Runnable { public void join() throws WorkerspaceQueueException { if (!started) { throw new WorkerspaceQueueException("Workspace batch runner already started"); } if (stopped) { return; } stopped = true; doDequeue = false; try { waitMonitor.get(); } catch (InterruptedException | ExecutionException e) { LOGGER.error(e); throw new WorkerspaceQueueException(e); } if (null != exceptionOccurred) { throw new WorkerspaceQueueException(exceptionOccurred); } } WorkspaceBatchRunner(HandlerIO handlerAsyncIO, Executor executor, int queueSize); @Override void run(); void transfer(WorkspaceQueue workspaceQueue); void start(); void join(); }### Answer: @Test(expected = WorkerspaceQueueException.class) public void whenJoinThenKO() throws WorkerspaceQueueException { HandlerIO handlerIO = mock(HandlerIOImpl.class); WorkspaceBatchRunner workspaceBatchRunner = new WorkspaceBatchRunner(handlerIO, VitamThreadPoolExecutor.getDefaultExecutor(), 10); workspaceBatchRunner.join(); }
### Question: WorkspaceBatchRunner implements Runnable { public void start() throws WorkerspaceQueueException { if (started) { throw new WorkerspaceQueueException("Workspace batch runner already started"); } started = true; this.executor.execute(this); } WorkspaceBatchRunner(HandlerIO handlerAsyncIO, Executor executor, int queueSize); @Override void run(); void transfer(WorkspaceQueue workspaceQueue); void start(); void join(); }### Answer: @Test(expected = WorkerspaceQueueException.class) public void whenDoubleStartThenOK() throws WorkerspaceQueueException { HandlerIO handlerIO = mock(HandlerIOImpl.class); WorkspaceBatchRunner workspaceBatchRunner = new WorkspaceBatchRunner(handlerIO, VitamThreadPoolExecutor.getDefaultExecutor(), 10); workspaceBatchRunner.start(); workspaceBatchRunner.start(); }
### Question: AsyncWorkspaceTransfer { public void transfer(WorkspaceQueue workspaceQueue) throws WorkerspaceQueueException { if (null == runner) { throw new WorkerspaceQueueException("Workspace batch runner is not started, call startTransfer to start it"); } this.runner.transfer(workspaceQueue); } AsyncWorkspaceTransfer(HandlerIO handlerAsyncIO); void transfer(WorkspaceQueue workspaceQueue); void startTransfer(int queueSize); void waitEndOfTransfer(); }### Answer: @Test(expected = WorkerspaceQueueException.class) public void whenTransferThenKO() throws WorkerspaceQueueException { HandlerIO handlerIO = mock(HandlerIOImpl.class); AsyncWorkspaceTransfer async = new AsyncWorkspaceTransfer(handlerIO); async.transfer(null); }
### Question: AsyncWorkspaceTransfer { public void waitEndOfTransfer() throws WorkerspaceQueueException { if (null != runner) { this.runner.join(); this.runner = null; } } AsyncWorkspaceTransfer(HandlerIO handlerAsyncIO); void transfer(WorkspaceQueue workspaceQueue); void startTransfer(int queueSize); void waitEndOfTransfer(); }### Answer: @Test public void whenWaitEndOfTransferWithoutStartTransferThenOK() throws WorkerspaceQueueException { HandlerIO handlerIO = mock(HandlerIOImpl.class); AsyncWorkspaceTransfer async = new AsyncWorkspaceTransfer(handlerIO); async.waitEndOfTransfer(); }
### Question: WorkspaceMain { public void stop() throws VitamApplicationServerException { vitamStarter.stop(); } WorkspaceMain(String configurationFile); static void main(String[] args); void start(); void startAndJoin(); void stop(); static final String PARAMETER_JETTY_SERVER_PORT; }### Answer: @Test public void givenFileAlreadyExistsWhenConfigureApplicationOKThenRunServer() throws Exception { application = new WorkspaceMain(CONFIG_FILE_NAME); application.stop(); }
### Question: UriUtils { public static String splitUri(String uriString) { String splitedString; ParametersChecker.checkParameter("Uri string is a mandatory parameter", uriString); if (uriString.contains(SLASH)) { final String[] uriWithoutRootFolderTable = uriString.split(SLASH, 2); splitedString = uriWithoutRootFolderTable[1]; } else { splitedString = ""; } return splitedString; } private UriUtils(); static String splitUri(String uriString); }### Answer: @Test public void givenUriWhenSplitThenReturnUriStringNotBlankTrue() { final String splitedString = UriUtils.splitUri(uriName); assertNotNull(splitedString); assertNotEquals("", splitedString); } @Test(expected=IllegalArgumentException.class) public void givenNullUriWhenSplitThenRaiseAnException() { final String splitedString = UriUtils.splitUri(uriNull); assertNotNull(splitedString); assertEquals("", splitedString); }
### Question: Entry { @JsonCreator public Entry(@JsonProperty("name") String name) { ParametersChecker.checkParameter("name is a mandatory parameter", name); this.name = name; } @JsonCreator Entry(@JsonProperty("name") String name); @JsonIgnore String getName(); }### Answer: @Test public void testEntry() { final Entry step = new Entry("NAME_ENTRY"); assertNotNull(step); assertNotNull(step.getName()); assertEquals("NAME_ENTRY", step.getName()); }
### Question: WorkspaceFileSystem implements WorkspaceContentAddressableStorage { @Override public boolean isExistingFolder(String containerName, String folderName) { Path folderPath = getObjectPath(containerName, folderName); return folderPath.toFile().exists() && folderPath.toFile().isDirectory(); } WorkspaceFileSystem(StorageConfiguration configuration); void checkWorkspaceFile(String... paths); @Override void createContainer(String containerName); @Override void purgeContainer(String containerName); @Override void purgeOldFilesInContainer(String containerName, TimeToLive timeToLive); @Override void deleteContainer(String containerName, boolean recursive); @Override boolean isExistingContainer(String containerName); @Override void createFolder(String containerName, String folderName); @Override void deleteFolder(String containerName, String folderName); @Override boolean isExistingFolder(String containerName, String folderName); @Override List<URI> getListUriDigitalObjectFromFolder(String containerName, String folderName); @Override void uncompressObject(String containerName, String folderName, String archiveMimeType, InputStream inputStreamObject); @Override void putObject(String containerName, String objectName, InputStream stream); @Override void putAtomicObject(String containerName, String objectName, InputStream stream, long size); @Override Response getObject(String containerName, String objectName, Long chunkOffset, Long maxChunkSize); @Override void deleteObject(String containerName, String objectName); @Override boolean isExistingObject(String containerName, String objectName); @Override String computeObjectDigest(String containerName, String objectName, DigestType algo); @Override ContainerInformation getContainerInformation(String containerName); @Override JsonNode getObjectInformation(String containerName, String objectName); @Override long countObjects(String containerName); void compress(String containerName, List<String> folderNames, String zipName, String outputContainer); }### Answer: @Test public void givenFolderNotFoundWhenCheckContainerExistenceThenRetunFalse() { Assert.assertFalse(storage.isExistingFolder(CONTAINER_NAME, FOLDER_NAME)); }
### Question: DeferredFileBufferingInputStream extends ProxyInputStream { @Override public void close() throws IOException { if (!closed) { this.in.close(); if (this.tmpFile != null) { Files.delete(this.tmpFile.toPath()); } closed = true; } } DeferredFileBufferingInputStream(InputStream sourceInputStream, long sourceSize, int maxInMemoryBufferSize, File tmpDirectory); @Override void close(); }### Answer: @Test public void testIOExceptionWhenOnDiskBufferingWithBrokenSource() throws IOException { InputStream brokenInputStream = mock(InputStream.class); doThrow(IOException.class).when(brokenInputStream).read(); doThrow(IOException.class).when(brokenInputStream).read(any()); doThrow(IOException.class).when(brokenInputStream).read(any(), anyInt(), anyInt()); doThrow(IOException.class).when(brokenInputStream).close(); InputStream sourceInputStream = new SequenceInputStream( new NullInputStream(100), brokenInputStream ); assertThatThrownBy(() -> new DeferredFileBufferingInputStream(sourceInputStream, 10000, 1000, tempFolder.getRoot())) .isInstanceOf(IOException.class); assertThat(tempFolder.getRoot().list()).isNullOrEmpty(); }
### Question: OntologyServiceImpl implements OntologyService { @Override public RequestResponseOK<OntologyModel> findOntologies(JsonNode queryDsl) throws ReferentialException, InvalidParseOperationException { try (DbRequestResult result = mongoAccess.findDocuments(queryDsl, FunctionalAdminCollections.ONTOLOGY)) { return result.getRequestResponseOK(queryDsl, Ontology.class, OntologyModel.class); } } OntologyServiceImpl(MongoDbAccessAdminImpl mongoAccess, FunctionalBackupService functionalBackupService); @Override RequestResponse<OntologyModel> importOntologies(boolean forceUpdate, List<OntologyModel> ontologyModelList); @Override RequestResponseOK<OntologyModel> findOntologiesForCache(JsonNode queryDsl); @Override RequestResponseOK<OntologyModel> findOntologies(JsonNode queryDsl); @Override void close(); }### Answer: @Test @RunWithCustomExecutor public void givenTestFindAllThenReturnEmpty() throws Exception { VitamThreadUtils.getVitamSession().setTenantId(TENANT_ID); final RequestResponseOK<OntologyModel> ontologyModelList = ontologyService.findOntologies(JsonHandler.createObjectNode()); assertThat(ontologyModelList.getResults()).isEmpty(); }
### Question: OntologyValidator { static boolean stringExceedsMaxLuceneUtf8StorageSize(String textValue, int maxUtf8Length) { if (textValue.length() * MAX_UTF8_BYTES_PER_CHAR < maxUtf8Length) { return false; } return textValue.getBytes(CharsetUtils.UTF8).length >= maxUtf8Length; } OntologyValidator(OntologyLoader ontologyLoader); ObjectNode verifyAndReplaceFields(JsonNode jsonNode); }### Answer: @Test public void testStringExceedsMaxLuceneUtf8StorageSize() { assertThat(stringExceedsMaxLuceneUtf8StorageSize("", 6)).isFalse(); assertThat(stringExceedsMaxLuceneUtf8StorageSize("abcde", 6)).isFalse(); assertThat(stringExceedsMaxLuceneUtf8StorageSize("abcdef", 6)).isTrue(); assertThat(stringExceedsMaxLuceneUtf8StorageSize("abcdefg", 6)).isTrue(); assertThat(stringExceedsMaxLuceneUtf8StorageSize("éé", 6)).isFalse(); assertThat(stringExceedsMaxLuceneUtf8StorageSize("ééé", 6)).isTrue(); assertThat(stringExceedsMaxLuceneUtf8StorageSize("ت", 6)).isFalse(); assertThat(stringExceedsMaxLuceneUtf8StorageSize("تت", 6)).isFalse(); assertThat(stringExceedsMaxLuceneUtf8StorageSize("تتت", 6)).isTrue(); assertThat(stringExceedsMaxLuceneUtf8StorageSize("☃", 6)).isFalse(); assertThat(stringExceedsMaxLuceneUtf8StorageSize("☃☃", 6)).isTrue(); assertThat("😊".length()).isEqualTo(2); assertThat(stringExceedsMaxLuceneUtf8StorageSize("😊", 6)).isFalse(); assertThat(stringExceedsMaxLuceneUtf8StorageSize("a😊", 6)).isFalse(); assertThat(stringExceedsMaxLuceneUtf8StorageSize("aa😊", 6)).isTrue(); }
### Question: ObjectGroup extends MetadataDocument<ObjectGroup> { @Override protected MetadataCollections getMetadataCollections() { return MetadataCollections.OBJECTGROUP; } ObjectGroup(); ObjectGroup(JsonNode content); ObjectGroup(Document content); ObjectGroup(String content); @Override MetadataDocument<ObjectGroup> newInstance(JsonNode content); static final String USAGES; static final String STORAGE; static final String VERSIONS; static final String DATAOBJECTVERSION; static final String VERSIONS_STORAGE; static final String OBJECTSTRATEHY; static final String OBJECTVERSION; static final String OBJECTID; static final String OBJECTSIZE; static final String OBJECTFORMAT; static final String OBJECTDIGEST; static final String OBJECTDIGEST_VALUE; static final String OBJECTDIGEST_TYPE; static final String COPIES; static final String OGDEPTHS; }### Answer: @Test public void givenObjectGroupWhenGetCollection() { final ObjectGroup group = new ObjectGroup(); group.getMetadataCollections(); }
### Question: ResultError extends Result { @Override public boolean isError() { return true; } ResultError(FILTERARGS type); ResultError(FILTERARGS type, final Set<String> set); @Override boolean isError(); ResultError addError(String error); @Override ResultError putFrom(Result from); }### Answer: @Test public void givenResultErrorConstructorWhenCreateWithoutCollectionThenAddNothing() { final ResultError resultError = new ResultError(FILTERARGS.UNITS); assertEquals(0, resultError.getCurrentIds().size()); assertEquals(true, resultError.isError()); }
### Question: OntologyServiceImpl implements OntologyService { @Override public RequestResponseOK<OntologyModel> findOntologiesForCache(JsonNode queryDsl) throws InvalidParseOperationException { final RequestResponseOK<OntologyModel> response = new RequestResponseOK<>(queryDsl); FindIterable<Document> documents = FunctionalAdminCollections.ONTOLOGY.getCollection().find(); for (Document document : documents) { response.addResult(JsonHandler.getFromString(BsonHelper.stringify(document), OntologyModel.class)); } return response; } OntologyServiceImpl(MongoDbAccessAdminImpl mongoAccess, FunctionalBackupService functionalBackupService); @Override RequestResponse<OntologyModel> importOntologies(boolean forceUpdate, List<OntologyModel> ontologyModelList); @Override RequestResponseOK<OntologyModel> findOntologiesForCache(JsonNode queryDsl); @Override RequestResponseOK<OntologyModel> findOntologies(JsonNode queryDsl); @Override void close(); }### Answer: @Test @RunWithCustomExecutor public void givenTestFindAllForCacheThenReturnEmpty() throws Exception { VitamThreadUtils.getVitamSession().setTenantId(TENANT_ID); final RequestResponseOK<OntologyModel> ontologyModelList = ontologyService.findOntologiesForCache(JsonHandler.createObjectNode()); assertThat(ontologyModelList.getResults()).isEmpty(); }
### Question: ResultError extends Result { public ResultError addError(String error) { currentIds.add(error); scores.add(new Float(0)); return this; } ResultError(FILTERARGS type); ResultError(FILTERARGS type, final Set<String> set); @Override boolean isError(); ResultError addError(String error); @Override ResultError putFrom(Result from); }### Answer: @Test public void givenResultErrorWhenAddingErrorThenAddErrorIds() { final ResultError resultError = new ResultError(FILTERARGS.UNITS); resultError.addError("errorId"); assertEquals(1, resultError.getCurrentIds().size()); }
### Question: MongoDbAccessMetadataImpl extends MongoDbAccess { @Override public String getInfo() { final StringBuilder builder = new StringBuilder(); final MongoIterable<String> collectionNames = getMongoDatabase().listCollectionNames(); for (final String s : collectionNames) { builder.append(s); builder.append('\n'); } for (final MetadataCollections coll : MetadataCollections.values()) { if (coll != null && coll.getCollection() != null) { @SuppressWarnings("unchecked") final ListIndexesIterable<Document> list = coll.getCollection().listIndexes(); for (final Document dbObject : list) { builder.append(coll.getName()).append(' ').append(dbObject).append('\n'); } } } return builder.toString(); } MongoDbAccessMetadataImpl(MongoClient mongoClient, String dbname, boolean recreate, ElasticsearchAccessMetadata esClient, List<Integer> tenants); @VisibleForTesting MongoDbAccessMetadataImpl(MongoClient mongoClient, String dbname, boolean recreate, ElasticsearchAccessMetadata esClient); static MongoClientOptions getMongoClientOptions(); @Override String getInfo(); static long getUnitSize(); static long getObjectGroupSize(); ElasticsearchAccessMetadata getEsClient(); void deleteUnitByTenant(Integer... tenantIds); void deleteObjectGroupByTenant(Integer... tenantIds); }### Answer: @Test public void givenMongoDbAccessConstructorWhenCreateWithoutRecreateThenAddNothing() { mongoDbAccess = new MongoDbAccessMetadataImpl(mongoRule.getMongoClient(), mongoRule.getMongoDatabase().getName(), false, esClient, tenantList); assertThat(mongoDbAccess.getInfo()) .contains(DEFAULT_MONGO1) .contains(DEFAULT_MONGO2) .contains(DEFAULT_MONGO3) .contains(DEFAULT_MONGO4) .contains(DEFAULT_MONGO5) .contains(DEFAULT_MONGO6) .contains(DEFAULT_MONGO7) .contains(DEFAULT_MONGO8) ; }
### Question: ExportsPurgeService { public void purgeExpiredFiles(String container) throws ContentAddressableStorageServerException { try (WorkspaceClient workspaceClient = this.workspaceClientFactory.getClient()) { workspaceClient.purgeOldFilesInContainer( container, new TimeToLive(this.timeToLiveInMinutes, ChronoUnit.MINUTES)); } } ExportsPurgeService(int timeToLiveInMinutes); @VisibleForTesting ExportsPurgeService(WorkspaceClientFactory workspaceClientFactory, StorageClientFactory storageClientFactory, int timeToLiveInMinutes); void purgeExpiredFiles(String container); void migrationPurgeDipFilesFromOffers(); }### Answer: @Test public void purgeExpiredDipFilesTest() throws ContentAddressableStorageServerException { WorkspaceClient workspaceClient = mock(WorkspaceClient.class); WorkspaceClientFactory workspaceClientFactory = mock(WorkspaceClientFactory.class); doReturn(workspaceClient).when(workspaceClientFactory).getClient(); ExportsPurgeService exportsPurgeService = new ExportsPurgeService(workspaceClientFactory, null, 10); exportsPurgeService.purgeExpiredFiles(DIP_CONTAINER); verify(workspaceClient).purgeOldFilesInContainer(DIP_CONTAINER, new TimeToLive(10, ChronoUnit.MINUTES)); }
### Question: JsonPath { public static String getTargetOfPath(String path) { if (Strings.isNullOrEmpty(path)) { return null; } final String splitPath[] = path.split(REG_EXP_SEPARATOR); return splitPath[splitPath.length - 1]; } static String getTargetOfPath(String path); static List<String> getSplitPath(String objectNameForHistory); }### Answer: @Test public void testGetTargetOfPathOneLevel() { Assert.assertEquals("_mgt", JsonPath.getTargetOfPath("_mgt")); } @Test public void testGetTargetOfPathTwoLevel() { Assert.assertEquals("ClassificationRule", JsonPath.getTargetOfPath("_mgt.ClassificationRule")); }
### Question: JsonPath { public static List<String> getSplitPath(String objectNameForHistory) { if (Strings.isNullOrEmpty(objectNameForHistory)) { return null; } List<String> splitPathList = new ArrayList<>(); String splitPath[] = objectNameForHistory.split(REG_EXP_SEPARATOR); for (int index = 0; index < splitPath.length - 1; ++index) { splitPathList.add(splitPath[index]); } return splitPathList; } static String getTargetOfPath(String path); static List<String> getSplitPath(String objectNameForHistory); }### Answer: @Test public void testGetPathOneLevel() { Assert.assertTrue(JsonPath.getSplitPath("_mgt").isEmpty()); } @Test public void testGetPathTwoLevel() { List<String> splitPath = JsonPath.getSplitPath("_mgt.ClassificationRule"); Assert.assertEquals(1, splitPath.size()); Assert.assertEquals("_mgt", splitPath.get(0)); } @Test public void testGetPathThreeLevel() { List<String> splitPath = JsonPath.getSplitPath("_mgt.ClassificationRule.ClassificationLevel"); Assert.assertEquals(2, splitPath.size()); Assert.assertEquals("_mgt", splitPath.get(0)); Assert.assertEquals("ClassificationRule", splitPath.get(1)); }
### Question: History { public JsonNode getArrayNode() { final ArrayNode historyArray = JsonHandler.createArrayNode(); ObjectNode history = JsonHandler.createObjectNode(); historyArray.add(history); history.put(UD, LocalDateUtil.getFormattedDateForMongo(LocalDateUtil.now())); ObjectNode data = history.putObject(DATA); data.put(_V, version); if(nodeToHistory.isMissingNode()) { createBranch(data); } else { createBranch(data).set(namePathForHistory, nodeToHistory); } return historyArray; } History(String objectPathForHistory, long version, JsonNode nodeToHistory); JsonNode getArrayNode(); JsonNode getNode(); }### Answer: @Test public void testGetArrayNode() { final String TEST_FIELD = "testField"; final String TEST_VALUE = "testValue"; final String TEST_PATH = "testLevel1.testLevel2"; final int TEST_VERSION = 1; JsonNode nodeToHistory = JsonHandler.createObjectNode().put(TEST_FIELD, TEST_VALUE); History history = new History(TEST_PATH, TEST_VERSION, nodeToHistory); JsonNode arrayNode = history.getArrayNode(); Assert.assertTrue(arrayNode.isArray()); String arrayNodeString = arrayNode.toString(); JsonPath path = JsonPath.from(arrayNodeString); Assert.assertNotNull(path.get("[0].ud")); Assert.assertNotNull(path.get("[0].data")); Assert.assertEquals(TEST_VERSION, path.getInt("[0].data._v")); Assert.assertEquals(TEST_VALUE, path.getString("[0].data." + TEST_PATH + "." + TEST_FIELD)); }
### Question: History { public JsonNode getNode() { ObjectNode history = JsonHandler.createObjectNode(); history.put(UD, LocalDateUtil.getFormattedDateForMongo(LocalDateUtil.now())); ObjectNode data = history.putObject(DATA); data.put(_V, version); createBranch(data).set(namePathForHistory, nodeToHistory); return history; } History(String objectPathForHistory, long version, JsonNode nodeToHistory); JsonNode getArrayNode(); JsonNode getNode(); }### Answer: @Test public void testGetNode() { final String TEST_FIELD = "testField"; final String TEST_VALUE = "testValue"; final String TEST_PATH = "testLevel1.testLevel2"; final int TEST_VERSION = 1; JsonNode nodeToHistory = JsonHandler.createObjectNode().put(TEST_FIELD, TEST_VALUE); History history = new History(TEST_PATH, TEST_VERSION, nodeToHistory); JsonNode node = history.getNode(); Assert.assertTrue(node.isObject()); String arrayNodeString = node.toString(); JsonPath path = JsonPath.from(arrayNodeString); Assert.assertNotNull(path.get("ud")); Assert.assertNotNull(path.get("data")); Assert.assertEquals(TEST_VERSION, path.getInt("data._v")); Assert.assertEquals(TEST_VALUE, path.getString("data." + TEST_PATH + "." + TEST_FIELD)); }
### Question: DataMigrationService { void mongoDataUpdate() throws InterruptedException { processUnits(); processObjectGroups(); } DataMigrationService(); @VisibleForTesting DataMigrationService(DataMigrationRepository dataMigrationRepository, GraphLoader graphLoader); boolean isMongoDataUpdateInProgress(); boolean tryStartMongoDataUpdate(); }### Answer: @Test public void mongoDataUpdate_emptyDataSet() throws Exception { DataMigrationService instance = new DataMigrationService(dataMigrationRepository, graphLoader); instance.mongoDataUpdate(); awaitTermination(instance); assertThat(MetadataCollections.UNIT.getCollection().find().iterator().hasNext()).isFalse(); } @RunWithCustomExecutor @Test public void mongoDataUpdate_checkGraphMigration() throws Exception { String unitDataSetFile = "DataMigrationR6/30UnitDataSet/R6UnitDataSet.json"; importUnitDataSetFile(unitDataSetFile); String ogDataSetFile = "DataMigrationR6/15ObjectGroupDataSet/R6ObjectGroupDataSet.json"; importObjectGroupDataSetFile(ogDataSetFile); DataMigrationService instance = new DataMigrationService(dataMigrationRepository, graphLoader); instance.mongoDataUpdate(); awaitTermination(instance); String expectedUnitDataSetFile = "DataMigrationR6/30UnitDataSet/ExpectedR7UnitDataSet.json"; assertDataSetEqualsExpectedFile(MetadataCollections.UNIT.getCollection(), expectedUnitDataSetFile); String expectedOGDataSetFile = "DataMigrationR6/15ObjectGroupDataSet/ExpectedR7ObjectGroupDataSet.json"; assertDataSetEqualsExpectedFile(MetadataCollections.OBJECTGROUP.getCollection(), expectedOGDataSetFile); }
### Question: DataMigrationRepository { public void bulkUpgradeObjectGroups(List<String> objectGroupIds) { String graphLastPersistedDate = LocalDateUtil.getFormattedDateForMongo(LocalDateUtil.now()); MetadataCollections.OBJECTGROUP.getCollection().updateMany( in(ObjectGroup.ID, objectGroupIds), Updates.set(ObjectGroup.GRAPH_LAST_PERSISTED_DATE, graphLastPersistedDate) ); } DataMigrationRepository(); @VisibleForTesting DataMigrationRepository(int bulkSize); CloseableIterator<List<Unit>> selectUnitBulkInTopDownHierarchyLevel(); Map<String, Unit> getUnitGraphByIds(Collection<String> unitIds); void bulkReplaceUnits(List<Unit> updatedUnits); CloseableIterator<List<String>> selectObjectGroupBulk(); void bulkUpgradeObjectGroups(List<String> objectGroupIds); }### Answer: @Test public void testBulkUpgradeObjectGroups_bulkUpdate() throws Exception { String dataSetFile = "DataMigrationR6/15ObjectGroupDataSet/R6ObjectGroupDataSet.json"; importObjectGroupDataSetFile(dataSetFile); repository.bulkUpgradeObjectGroups(Arrays.asList("1", "6")); ObjectGroup og6_updated = (ObjectGroup) MetadataCollections.OBJECTGROUP.getCollection().find(eq(ObjectGroup.ID, "6")).first(); ObjectGroup og4_not_updated = (ObjectGroup) MetadataCollections.OBJECTGROUP.getCollection().find(eq(ObjectGroup.ID, "4")).first(); assertThat(og6_updated.get(ObjectGroup.GRAPH_LAST_PERSISTED_DATE)).isNotNull(); assertThat(og4_not_updated.get(ObjectGroup.GRAPH_LAST_PERSISTED_DATE)).isNull(); }
### Question: MongoDbAccessMetadataFactory { public static MongoDbAccessMetadataImpl create(MetaDataConfiguration configuration) { ParametersChecker.checkParameter("configuration is a mandatory parameter", configuration); ElasticsearchAccessMetadata esClient; try { esClient = ElasticsearchAccessMetadataFactory.create(configuration); } catch (final MetaDataException | IOException e1) { throw new IllegalArgumentException(e1); } final List<Class<?>> classList = new ArrayList<>(); for (final MetadataCollections e : MetadataCollections.class.getEnumConstants()) { classList.add(e.getClasz()); } MetadataCollections.class.getEnumConstants(); final MongoClient mongoClient = MongoDbAccess.createMongoClient(configuration, VitamCollection.getMongoClientOptions(classList)); return new MongoDbAccessMetadataImpl(mongoClient, configuration.getDbName(), true, esClient, VitamConfiguration.getTenants()); } static MongoDbAccessMetadataImpl create(MetaDataConfiguration configuration); }### Answer: @Test public void testCreateMetadata() { final List<MongoDbNode> mongoNodes = new ArrayList<>(); mongoNodes.add(new MongoDbNode(MongoRule.MONGO_HOST, MongoRule.getDataBasePort())); List<ElasticsearchNode> esNodes = new ArrayList<>(); esNodes.add(new ElasticsearchNode(ElasticsearchRule.getHost(), ElasticsearchRule.getPort())); MetaDataConfiguration config = new MetaDataConfiguration(mongoNodes, MongoRule.VITAM_DB, ElasticsearchRule.VITAM_CLUSTER, esNodes); VitamConfiguration.setTenants(tenantList); MongoDbAccessMetadataImpl mongoDbAccess = MongoDbAccessMetadataFactory.create(config); assertNotNull(mongoDbAccess); assertThat(mongoDbAccess.getMongoDatabase().getName()).isEqualTo(MongoRule.VITAM_DB); mongoDbAccess.close(); }
### Question: MetadataJsonResponseUtils { public static ArrayNode populateJSONObjectResponse(Result result, RequestParserMultiple selectRequest) throws InvalidParseOperationException { ArrayNode jsonListResponse = JsonHandler.createArrayNode(); if (result != null && result.getNbResult() > 0 && selectRequest instanceof SelectParserMultiple && result.hasFinalResult()) { LOGGER.debug("Result document: " + result.getFinal().toString()); jsonListResponse = (ArrayNode) getMetadataJsonObject(result.getListFiltered()); } LOGGER.debug("MetaDataImpl / selectUnitsByQuery /Results: " + jsonListResponse.toString()); return jsonListResponse; } private MetadataJsonResponseUtils(); static ArrayNode populateJSONObjectResponse(Result result, RequestParserMultiple selectRequest); static ArrayNode populateJSONObjectResponse(Result result, Map<String, List<String>> diff); }### Answer: @Test public void given_resultwith_nbreresult_0_thenReturn_JsonNode() throws Exception { final JsonNode jsonNode = MetadataJsonResponseUtils.populateJSONObjectResponse(buildResult(0), new SelectParserMultiple()); assertNotNull(jsonNode); } @Test public void given_resultwith_nbreresult_2_thenthrow_InvalidParseOperationException() throws Exception { assertEquals( MetadataJsonResponseUtils.populateJSONObjectResponse(buildResult(2), new SelectParserMultiple()).size(), 0); }
### Question: FileRulesImportInProgressException extends ReferentialException { public FileRulesImportInProgressException(String message) { super(message); } FileRulesImportInProgressException(String message); FileRulesImportInProgressException(Throwable cause); FileRulesImportInProgressException(String message, Throwable cause); }### Answer: @Test public final void testFileRulesImportInProgressException() { assertEquals("", new FileRulesImportInProgressException("").getMessage()); assertEquals("test", new FileRulesImportInProgressException("test").getMessage()); assertNotNull(new FileRulesImportInProgressException(new Exception()).getCause()); assertNotNull(new FileRulesImportInProgressException("test", new Exception()).getCause()); }
### Question: FileFormatException extends ReferentialException { public FileFormatException(String message) { super(message); } FileFormatException(String message); FileFormatException(Throwable cause); FileFormatException(String message, Throwable cause); }### Answer: @Test public final void testFileFormatException() { assertEquals("", new FileFormatException("").getMessage()); assertEquals("test", new FileFormatException("test").getMessage()); assertNotNull(new FileFormatException(new Exception()).getCause()); assertNotNull(new FileFormatException("test", new Exception()).getCause()); }
### Question: FileRulesException extends ReferentialException { public FileRulesException(String message) { super(message); } FileRulesException(String message); FileRulesException(Throwable cause); FileRulesException(String message, Throwable cause); }### Answer: @Test public final void testFileRulesException() { assertEquals("", new FileRulesException("").getMessage()); assertEquals("test", new FileFormatException("test").getMessage()); assertNotNull(new FileRulesException(new Exception()).getCause()); assertNotNull(new FileRulesException("test", new Exception()).getCause()); }
### Question: VitamCounterService { public String getNextSequenceAsString(Integer tenant, SequenceType sequenceType) throws ReferentialException { Integer sequence = getNextSequence(tenant, sequenceType); return sequenceType.getName() + "-" + String.format("%06d", sequence); } VitamCounterService(MongoDbAccessAdminImpl dbConfiguration, List<Integer> tenants, Map<Integer, List<String>> externalIdentifiers); String getNextSequenceAsString(Integer tenant, SequenceType sequenceType); Integer getNextSequence(Integer tenant, SequenceType sequenceType); VitamSequence getNextBackupSequenceDocument(Integer tenant, SequenceType sequenceType); Integer getSequence(Integer tenant, SequenceType sequenceType); VitamSequence getSequenceDocument(Integer tenant, SequenceType sequenceType); boolean isSlaveFunctionnalCollectionOnTenant(FunctionalAdminCollections collection, Integer tenant); }### Answer: @Test(expected = IllegalArgumentException.class) @RunWithCustomExecutor public void testError() throws Exception { VitamThreadUtils.getVitamSession().setTenantId(TENANT_ID); String ic = vitamCounterService.getNextSequenceAsString(TENANT_ID, SequenceType.valueOf("ABB")); }
### Question: MongoDbAccessAdminFactory { public static final MongoDbAccessAdminImpl create(DbConfiguration configuration, OntologyLoader ontologyLoader) { ParametersChecker.checkParameter("configuration is a mandatory parameter", configuration); final List<Class<?>> classList = new ArrayList<>(); for (final FunctionalAdminCollections e : FunctionalAdminCollections.class.getEnumConstants()) { classList.add(e.getClasz()); } FunctionalAdminCollections.class.getEnumConstants(); final MongoClient mongoClient = MongoDbAccess.createMongoClient(configuration, VitamCollection.getMongoClientOptions(classList)); return new MongoDbAccessAdminImpl(mongoClient, configuration.getDbName(), false, ontologyLoader); } private MongoDbAccessAdminFactory(); static final MongoDbAccessAdminImpl create(DbConfiguration configuration, OntologyLoader ontologyLoader); static final MongoDbAccessAdminImpl create(DbConfiguration configuration, String clusterName, List<ElasticsearchNode> nodes, OntologyLoader ontologyLoader); }### Answer: @Test public void testCreateAdmin() { final List<MongoDbNode> nodes = new ArrayList<>(); nodes.add(new MongoDbNode("localhost", mongoRule.getDataBasePort())); mongoDbAccess = MongoDbAccessAdminFactory.create( new DbConfigurationImpl(nodes, mongoRule.getMongoDatabase().getName(), true, "user", "pwd"), Collections::emptyList); assertNotNull(mongoDbAccess); assertEquals(MongoRule.VITAM_DB, mongoDbAccess.getMongoDatabase().getName()); mongoDbAccess.close(); }
### Question: PreservationReportRepository { public MongoCursor<Document> findCollectionByProcessIdTenant(String processId, int tenantId) { return collection.aggregate( Arrays.asList( match(and(eq(PROCESS_ID, processId), eq(TENANT, tenantId))), Aggregates.project(Projections.fields( new Document(PROCESS_ID, "$processId"), new Document(CREATION_DATE_TIME, "$creationDateTime"), new Document(UNIT_ID, "$unitId"), new Document(OBJECT_GROUP_ID, "$objectGroupId"), new Document(STATUS, "$status"), new Document(ACTION, "$actions"), new Document(ANALYSE_RESULT, "$analyseResult"), new Document(INPUT_OBJECT_ID, "$inputObjectId"), new Document(OUTPUT_OBJECT_ID, "$outputObjectId"), new Document(GRIFFIN_ID, "$griffinId"), new Document(SCENARIO_ID, "$preservationScenarioId") ) )) ).allowDiskUse(true).iterator(); } @VisibleForTesting PreservationReportRepository(MongoDbAccess mongoDbAccess, String collectionName); PreservationReportRepository(MongoDbAccess mongoDbAccess); void bulkAppendReport(List<PreservationReportEntry> reports); MongoCursor<Document> findCollectionByProcessIdTenant(String processId, int tenantId); PreservationStatsModel stats(String processId, int tenantId); void deleteReportByIdAndTenant(String processId, int tenantId); static final String PRESERVATION_REPORT; }### Answer: @Test public void should_find_collection_by_processid_tenant() { populateDatabase(); MongoCursor<Document> iterator = repository.findCollectionByProcessIdTenant(processId, TENANT_ID); List<Document> documents = new ArrayList<>(); while (iterator.hasNext()) { Document reportModel = iterator.next(); documents.add(reportModel); } assertThat(documents.size()).isEqualTo(2); }
### Question: PreservationReportRepository { public void deleteReportByIdAndTenant(String processId, int tenantId) { DeleteResult deleteResult = collection.deleteMany(and(eq(PROCESS_ID, processId), eq(TENANT, tenantId))); LOGGER.info("Deleted document count: " + deleteResult.getDeletedCount() + " for process " + processId); } @VisibleForTesting PreservationReportRepository(MongoDbAccess mongoDbAccess, String collectionName); PreservationReportRepository(MongoDbAccess mongoDbAccess); void bulkAppendReport(List<PreservationReportEntry> reports); MongoCursor<Document> findCollectionByProcessIdTenant(String processId, int tenantId); PreservationStatsModel stats(String processId, int tenantId); void deleteReportByIdAndTenant(String processId, int tenantId); static final String PRESERVATION_REPORT; }### Answer: @Test public void should_delete_report_by_id_and_tenant() { populateDatabase(); repository.deleteReportByIdAndTenant(processId, TENANT_ID); FindIterable<Document> iterable = preservationReportCollection.find(and(eq("processId", processId), eq("tenantId", TENANT_ID))); MongoCursor<Document> iterator = iterable.iterator(); List<Document> documents = new ArrayList<>(); while (iterator.hasNext()) { documents.add(iterator.next()); } assertThat(documents).isEmpty(); assertThat(documents.size()).isEqualTo(0); }
### Question: AuditReportRepository extends ReportCommonRepository { public MongoCursor<Document> findCollectionByProcessIdTenant(String processId, int tenantId) { Bson eqProcessId = eq(AuditObjectGroupModel.PROCESS_ID, processId); Bson eqTenant = eq(AuditObjectGroupModel.TENANT, tenantId); return objectGroupReportCollection .aggregate(Arrays.asList(Aggregates.match(and(eqProcessId, eqTenant)), Aggregates.project(reportProjection()))) .allowDiskUse(true).iterator(); } @VisibleForTesting AuditReportRepository(MongoDbAccess mongoDbAccess, String collectionName); AuditReportRepository(MongoDbAccess mongoDbAccess); void bulkAppendReport(List<AuditObjectGroupModel> reports); void deleteReportByIdAndTenant(String processId, int tenantId); ReportResults computeVitamResults(String processId, Integer tenantId); MongoCursor<Document> findCollectionByProcessIdTenantAndStatus(String processId, int tenantId, String... status); MongoCursor<Document> findCollectionByProcessIdTenant(String processId, int tenantId); AuditStatsModel stats(String processId, int tenantId); static final String AUDIT_OBJECT_GROUP; }### Answer: @Test public void should_find_collection_by_processid_tenant() { populateDatabase(auditReportEntryKO); MongoCursor<Document> iterator = repository.findCollectionByProcessIdTenant(processId, TENANT_ID); List<Document> documents = new ArrayList<>(); while (iterator.hasNext()) { Document reportModel = iterator.next(); documents.add(reportModel); } assertThat(documents.size()).isEqualTo(1); }
### Question: AuditReportRepository extends ReportCommonRepository { public MongoCursor<Document> findCollectionByProcessIdTenantAndStatus(String processId, int tenantId, String... status) { Bson eqProcessId = eq(AuditObjectGroupModel.PROCESS_ID, processId); Bson eqTenant = eq(AuditObjectGroupModel.TENANT, tenantId); Bson inStatus = or(in(AuditObjectGroupModel.METADATA + ".status", status), in(AuditObjectGroupModel.METADATA + ".objectVersions.status", status)); return objectGroupReportCollection .aggregate(Arrays.asList(Aggregates.match(and(eqProcessId, eqTenant, inStatus)), Aggregates.project(reportProjection()))) .allowDiskUse(true).iterator(); } @VisibleForTesting AuditReportRepository(MongoDbAccess mongoDbAccess, String collectionName); AuditReportRepository(MongoDbAccess mongoDbAccess); void bulkAppendReport(List<AuditObjectGroupModel> reports); void deleteReportByIdAndTenant(String processId, int tenantId); ReportResults computeVitamResults(String processId, Integer tenantId); MongoCursor<Document> findCollectionByProcessIdTenantAndStatus(String processId, int tenantId, String... status); MongoCursor<Document> findCollectionByProcessIdTenant(String processId, int tenantId); AuditStatsModel stats(String processId, int tenantId); static final String AUDIT_OBJECT_GROUP; }### Answer: @Test public void should_find_collection_by_processid_tenant_status() { populateDatabase(auditReportEntryKO, auditReportEntryOK, auditReportEntryWARNING); MongoCursor<Document> iterator = repository.findCollectionByProcessIdTenantAndStatus(processId, TENANT_ID, "WARNING", "KO"); List<Document> documents = new ArrayList<>(); while (iterator.hasNext()) { Document reportModel = iterator.next(); documents.add(reportModel); } assertThat(documents.size()).isEqualTo(2); }
### Question: AuditReportRepository extends ReportCommonRepository { public void deleteReportByIdAndTenant(String processId, int tenantId) { super.deleteReportByIdAndTenant(processId, tenantId, objectGroupReportCollection); } @VisibleForTesting AuditReportRepository(MongoDbAccess mongoDbAccess, String collectionName); AuditReportRepository(MongoDbAccess mongoDbAccess); void bulkAppendReport(List<AuditObjectGroupModel> reports); void deleteReportByIdAndTenant(String processId, int tenantId); ReportResults computeVitamResults(String processId, Integer tenantId); MongoCursor<Document> findCollectionByProcessIdTenantAndStatus(String processId, int tenantId, String... status); MongoCursor<Document> findCollectionByProcessIdTenant(String processId, int tenantId); AuditStatsModel stats(String processId, int tenantId); static final String AUDIT_OBJECT_GROUP; }### Answer: @Test public void should_delete_report_by_id_and_tenant() { populateDatabase(auditReportEntryKO, auditReportEntryOK, auditReportEntryWARNING); repository.deleteReportByIdAndTenant(processId, TENANT_ID); FindIterable<Document> iterable = auditReportCollection .find(and(eq("processId", processId), eq("tenantId", TENANT_ID))); MongoCursor<Document> iterator = iterable.iterator(); List<Document> documents = new ArrayList<>(); while (iterator.hasNext()) { documents.add(iterator.next()); } assertThat(documents).isEmpty(); assertThat(documents.size()).isEqualTo(0); }
### Question: UnitComputedInheritedRulesInvalidationRepository extends ReportCommonRepository { public void deleteReportByIdAndTenant(String processId, int tenantId) { super.deleteReportByIdAndTenant(processId, tenantId, collection); } @VisibleForTesting UnitComputedInheritedRulesInvalidationRepository(MongoDbAccess mongoDbAccess, String collectionName); UnitComputedInheritedRulesInvalidationRepository(SimpleMongoDBAccess mongoDbAccess); void bulkAppendReport(List<UnitComputedInheritedRulesInvalidationModel> reports); CloseableIterator<Document> findCollectionByProcessIdTenant(String processId, int tenantId); void deleteReportByIdAndTenant(String processId, int tenantId); }### Answer: @Test public void deleteUnitsAndProgeny_EmptyOK() throws Exception { repository.deleteReportByIdAndTenant("procId1", VitamThreadUtils.getVitamSession().getTenantId()); assertThat(mongoCollection.countDocuments()).isEqualTo(0); }
### Question: UnitComputedInheritedRulesInvalidationRepository extends ReportCommonRepository { public CloseableIterator<Document> findCollectionByProcessIdTenant(String processId, int tenantId) { MongoCursor<Document> cursor = collection.aggregate( Arrays.asList( Aggregates.match(and( eq(UnitComputedInheritedRulesInvalidationModel.PROCESS_ID, processId), eq(UnitComputedInheritedRulesInvalidationModel.TENANT, tenantId) )), Aggregates.project(Projections.fields( new Document("_id", 0), new Document("id", "$_metadata.id") ) )) ) .allowDiskUse(true) .iterator(); return new CloseableIterator<Document>() { @Override public void close() { cursor.close(); } @Override public boolean hasNext() { return cursor.hasNext(); } @Override public Document next() { return cursor.next(); } }; } @VisibleForTesting UnitComputedInheritedRulesInvalidationRepository(MongoDbAccess mongoDbAccess, String collectionName); UnitComputedInheritedRulesInvalidationRepository(SimpleMongoDBAccess mongoDbAccess); void bulkAppendReport(List<UnitComputedInheritedRulesInvalidationModel> reports); CloseableIterator<Document> findCollectionByProcessIdTenant(String processId, int tenantId); void deleteReportByIdAndTenant(String processId, int tenantId); }### Answer: @Test public void findCollectionByProcessIdTenant() throws Exception { List<String> units1 = Arrays.asList("unit1", "unit2", "unit4"); List<String> units2 = Arrays.asList("unit3", "unit4"); repository.bulkAppendReport(buildReport(units1, "procId1")); repository.bulkAppendReport(buildReport(units2, "procId2")); CloseableIterator<Document> documents = repository.findCollectionByProcessIdTenant("procId1", VitamThreadUtils.getVitamSession().getTenantId()); List<String> unitIds = Streams.stream(documents) .map(doc -> doc.getString("id")) .collect(Collectors.toList()); assertThat(unitIds).containsExactlyInAnyOrderElementsOf(units1); }
### Question: EvidenceAuditReportRepository extends ReportCommonRepository { public MongoCursor<Document> findCollectionByProcessIdTenant(String processId, int tenantId) { Bson eqProcessId = eq(AuditObjectGroupModel.PROCESS_ID, processId); Bson eqTenant = eq(AuditObjectGroupModel.TENANT, tenantId); return evidenceAuditReportCollection .aggregate(Arrays.asList(Aggregates.match(and(eqProcessId, eqTenant)), Aggregates.project(evidenceReportProjection()))) .allowDiskUse(true).iterator(); } @VisibleForTesting EvidenceAuditReportRepository(MongoDbAccess mongoDbAccess, String collectionName); EvidenceAuditReportRepository(MongoDbAccess mongoDbAccess); void bulkAppendReport(List<EvidenceAuditObjectModel> reports); void deleteReportByIdAndTenant(String processId, int tenantId); ReportResults computeVitamResults(String processId, Integer tenantId); MongoCursor<Document> findCollectionByProcessIdTenant(String processId, int tenantId); MongoCursor<Document> findCollectionByProcessIdTenantAndStatus(String processId, int tenantId, String... status); EvidenceAuditStatsModel stats(String processId, int tenantId); static final String EVIDENCE_AUDIT; }### Answer: @Test public void should_find_collection_by_processid_tenant() { populateDatabase(evidenceAuditReportEntryKO, evidenceAuditReportEntryOK, evidenceAuditReportEntryWARN); MongoCursor<Document> iterator = evidenceAuditRepository .findCollectionByProcessIdTenant(processId, TENANT_ID); List<Document> documents = new ArrayList<>(); while (iterator.hasNext()) { Document reportModel = iterator.next(); documents.add(reportModel); } assertThat(documents.size()).isEqualTo(3); }
### Question: EvidenceAuditReportRepository extends ReportCommonRepository { public void deleteReportByIdAndTenant(String processId, int tenantId) { super.deleteReportByIdAndTenant(processId, tenantId, evidenceAuditReportCollection); } @VisibleForTesting EvidenceAuditReportRepository(MongoDbAccess mongoDbAccess, String collectionName); EvidenceAuditReportRepository(MongoDbAccess mongoDbAccess); void bulkAppendReport(List<EvidenceAuditObjectModel> reports); void deleteReportByIdAndTenant(String processId, int tenantId); ReportResults computeVitamResults(String processId, Integer tenantId); MongoCursor<Document> findCollectionByProcessIdTenant(String processId, int tenantId); MongoCursor<Document> findCollectionByProcessIdTenantAndStatus(String processId, int tenantId, String... status); EvidenceAuditStatsModel stats(String processId, int tenantId); static final String EVIDENCE_AUDIT; }### Answer: @Test public void should_delete_report_by_id_and_tenant() { populateDatabase(evidenceAuditReportEntryKO, evidenceAuditReportEntryOK, evidenceAuditReportEntryWARN); evidenceAuditRepository.deleteReportByIdAndTenant(processId, TENANT_ID); FindIterable<Document> iterable = evidenceAuditReportCollection .find(and(eq("processId", processId), eq("tenantId", TENANT_ID))); MongoCursor<Document> iterator = iterable.iterator(); List<Document> documents = new ArrayList<>(); while (iterator.hasNext()) { documents.add(iterator.next()); } assertThat(documents).isEmpty(); assertThat(documents.size()).isEqualTo(0); }
### Question: CapacityLruLinkedHashMap extends LinkedHashMap<K, V> { public int getCapacity() { return this.capacity; } protected CapacityLruLinkedHashMap(int capacity, int initialCapacity, float loadFactor); int getCapacity(); }### Answer: @Test public void testCapacity() { final CapacityLruLinkedHashMap<Object, String> capacityLruLinkedHashMap0 = new CapacityLruLinkedHashMap<>(1, 1, 1); capacityLruLinkedHashMap0.put("", ""); capacityLruLinkedHashMap0.put("capacity must be positive", "B[3aky(lHPeu\""); assertFalse(capacityLruLinkedHashMap0.isEmpty()); assertEquals(1, capacityLruLinkedHashMap0.size()); final CapacityLruLinkedHashMap<Object, Object> capacityLruLinkedHashMap1 = new CapacityLruLinkedHashMap<>(1, 0, 1.0F); final int int0 = capacityLruLinkedHashMap1.getCapacity(); assertEquals(1, int0); }
### Question: CapacityLruLinkedHashMap extends LinkedHashMap<K, V> { @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > capacity; } protected CapacityLruLinkedHashMap(int capacity, int initialCapacity, float loadFactor); int getCapacity(); }### Answer: @Test public void testNotRemove() { final CapacityLruLinkedHashMap<Object, String> capacityLruLinkedHashMap0 = new CapacityLruLinkedHashMap<>(3384, 0, 3384); final AbstractMap.SimpleEntry<Object, String> abstractMap_SimpleEntry0 = new AbstractMap.SimpleEntry<>((Object) null, "capacity must be positive"); final boolean boolean0 = capacityLruLinkedHashMap0.removeEldestEntry(abstractMap_SimpleEntry0); assertFalse(boolean0); }
### Question: StrongReferenceCacheEntry implements InterfaceLruCacheEntry<V> { @Override public boolean isStillValid(long timeRef) { return timeRef <= expirationTime; } StrongReferenceCacheEntry(V value, long ttl); @Override V getValue(); @Override boolean isStillValid(long timeRef); @Override boolean resetTime(long ttl); }### Answer: @Test public void testStillValid() { final Integer integer0 = new Integer(227); final StrongReferenceCacheEntry<Integer> strongReferenceCacheEntry0 = new StrongReferenceCacheEntry<>(integer0, 1L); strongReferenceCacheEntry0.isStillValid(189L); final boolean boolean0 = strongReferenceCacheEntry0.isStillValid(1464473409004L); assertTrue(boolean0); }
### Question: StrongReferenceCacheEntry implements InterfaceLruCacheEntry<V> { @Override public V getValue() { if (System.currentTimeMillis() > expirationTime) { return null; } else { return value; } } StrongReferenceCacheEntry(V value, long ttl); @Override V getValue(); @Override boolean isStillValid(long timeRef); @Override boolean resetTime(long ttl); }### Answer: @Test public void testValue() { final StrongReferenceCacheEntry<String> strongReferenceCacheEntry0 = new StrongReferenceCacheEntry<>("", 71L); final String string0 = strongReferenceCacheEntry0.getValue(); assertEquals("", string0); }
### Question: SynchronizedLruCache extends AbstractLruCache<K, V> { @Override public synchronized void clear() { cacheMap.clear(); } SynchronizedLruCache(int capacity, long ttl, int initialCapacity, float loadFactor); SynchronizedLruCache(int capacity, long ttl, int initialCapacity); SynchronizedLruCache(int capacity, long ttl); @Override synchronized void clear(); @Override synchronized V get(K key); @Override int getCapacity(); @Override synchronized int size(); @Override synchronized void put(K key, V value, long ttl); @Override synchronized V remove(K key); @Override synchronized int forceClearOldest(); static final int DEFAULT_INITIAL_CAPACITY; static final float DEFAULT_LOAD_FACTOR; }### Answer: @Test public final void testError() { try { final SynchronizedLruCache<String, Integer> synchronizedLruCache = new SynchronizedLruCache<>(2, -100, 1); fail(ResourcesPrivateUtilTest.SHOULD_RAIZED_AN_EXCEPTION); synchronizedLruCache.clear(); } catch (final IllegalArgumentException e) { } }
### Question: SchemaValidationUtils { public static List<String> extractFieldsFromSchema(String schemaJsonAsString) throws InvalidParseOperationException { List<String> listProperties = new ArrayList<>(); JsonNode externalSchema = JsonHandler.getFromString(schemaJsonAsString); if (externalSchema != null && externalSchema.get(PROPERTIES) != null) { extractPropertyFromJsonNode(externalSchema.get(PROPERTIES), listProperties); } return listProperties; } static List<String> extractFieldsFromSchema(String schemaJsonAsString); }### Answer: @Test public void testExtractFieldsFromSchema() throws Exception { JsonNode jsonArcUnit = JsonHandler.getFromInputStream(PropertiesUtils.getResourceAsStream(ARCHIVE_UNIT_PROFILE_OK_JSON_FILE)); ArchiveUnitProfileModel archiveUnitProfile = JsonHandler.getFromJsonNode(jsonArcUnit, ArchiveUnitProfileModel.class); List<String> extractFields = SchemaValidationUtils.extractFieldsFromSchema(archiveUnitProfile.getControlSchema()); assertEquals(extractFields.size(), 14); assertTrue(extractFields.contains("Rule")); assertTrue(extractFields.contains("StartDate")); assertTrue(extractFields.contains("PreventRulesId")); assertFalse(extractFields.contains("Rules")); assertFalse(extractFields.contains("#management")); }
### Question: CanonicalJsonFormatter { public static InputStream serialize(JsonNode node) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); serialize(node, outputStream); return outputStream.toInputStream(); } catch (IOException e) { throw new IllegalStateException("Unexpected IO exception on memory stream", e); } } private CanonicalJsonFormatter(OutputStreamWriter writer); static InputStream serialize(JsonNode node); static byte[] serializeToByteArray(JsonNode node); static void serialize(JsonNode node, OutputStream outputStream); }### Answer: @Test public void whenSerializeCheckBinaryData() throws Exception { String inputJson = "json_canonicalization/test_input.json"; String expectedOutput = "json_canonicalization/expected_output.json"; try (InputStream is = PropertiesUtils.getResourceAsStream(inputJson); InputStream expectedInputStream = PropertiesUtils.getResourceAsStream(expectedOutput)) { JsonNode jsonNode = JsonHandler.getFromInputStream(is); InputStream resultInputStream = CanonicalJsonFormatter.serialize(jsonNode); assertThat(IOUtils.contentEquals(resultInputStream, expectedInputStream)).isTrue(); } } @Test public void whenSerializeCheckDataParsing() throws Exception { String inputJson = "json_canonicalization/test_input.json"; JsonNode initialJson = JsonHandler.getFromInputStream(PropertiesUtils.getResourceAsStream(inputJson)); JsonNode canonicalJson = JsonHandler.getFromInputStream(CanonicalJsonFormatter.serialize(initialJson)); JsonAssert.assertJsonEquals(initialJson.toString(), canonicalJson.toString()); }
### Question: CanonicalJsonFormatter { public static byte[] serializeToByteArray(JsonNode node) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); serialize(node, outputStream); return outputStream.toByteArray(); } catch (IOException e) { throw new IllegalStateException("Unexpected IO exception on memory stream", e); } } private CanonicalJsonFormatter(OutputStreamWriter writer); static InputStream serialize(JsonNode node); static byte[] serializeToByteArray(JsonNode node); static void serialize(JsonNode node, OutputStream outputStream); }### Answer: @Test public void testSerializeBinary() { ObjectNode jsonNode = JsonHandler.createObjectNode(); jsonNode.put("binary", "123456789az".getBytes()); byte[] result = CanonicalJsonFormatter.serializeToByteArray(jsonNode); assertThat(new String(result)).isEqualTo("{\"binary\":\"MTIzNDU2Nzg5YXo=\"}"); }
### Question: JsonSchemaValidator { public static JsonSchemaValidator forBuiltInSchema(String schemaFilename) { try (InputStream is = JsonSchemaValidator.class.getResourceAsStream(schemaFilename)) { JsonNode schemaJson = JsonHandler.getFromInputStream(is); JsonSchema jsonSchema = JSON_SCHEMA_FACTORY.getJsonSchema(schemaJson); return new JsonSchemaValidator(jsonSchema); } catch (InvalidParseOperationException | ProcessingException | IOException e) { throw new VitamRuntimeException("Could not initialize built-in schema file " + schemaFilename); } } private JsonSchemaValidator(JsonSchema jsonSchema); static JsonSchemaValidator forBuiltInSchema(String schemaFilename); static JsonSchemaValidator forUserSchema(String schemaJsonAsString); void validateJson(JsonNode jsonNode); }### Answer: @Test public void forBuiltInSchema() throws Exception { String schemaFilename = "/test_schema.json"; JsonSchemaValidator schemaValidator = JsonSchemaValidator.forBuiltInSchema(schemaFilename); schemaValidator.validateJson(JsonHandler.createObjectNode() .put("_id", "MyId") .put("Title", "MyTitle") ); assertThatThrownBy(() -> schemaValidator.validateJson(JsonHandler.createObjectNode() .put("Title", "MyTitle") ) ).isInstanceOf(JsonSchemaValidationException.class); } @Test public void givenConstructorWithInexistingSchemaThenException() { assertThatThrownBy(() -> JsonSchemaValidator.forBuiltInSchema("/no_such_file")) .isInstanceOf(VitamRuntimeException.class); } @Test public void givenConstructorWithIncorrectSchemaThenException() { assertThatThrownBy(() -> JsonSchemaValidator.forBuiltInSchema("/test.conf")) .isInstanceOf(VitamRuntimeException.class); }
### Question: JsonSchemaValidator { public static JsonSchemaValidator forUserSchema(String schemaJsonAsString) throws InvalidJsonSchemaException { try { JsonNode schemaAsJson = JsonHandler.getFromString(schemaJsonAsString); ProcessingReport pr = JSON_SCHEMA_FACTORY.getSyntaxValidator().validateSchema(schemaAsJson); if (!pr.isSuccess()) { throw new InvalidJsonSchemaException("External Schema is not valid"); } JsonSchema jsonSchema = JSON_SCHEMA_FACTORY.getJsonSchema(schemaAsJson); return new JsonSchemaValidator(jsonSchema); } catch (InvalidParseOperationException | ProcessingException e) { throw new InvalidJsonSchemaException("External Schema is not valid", e); } } private JsonSchemaValidator(JsonSchema jsonSchema); static JsonSchemaValidator forBuiltInSchema(String schemaFilename); static JsonSchemaValidator forUserSchema(String schemaJsonAsString); void validateJson(JsonNode jsonNode); }### Answer: @Test public void forUserSchema() throws Exception { String schema = "{\"$schema\":\"http: JsonSchemaValidator schemaValidator = JsonSchemaValidator.forUserSchema(schema); schemaValidator.validateJson(JsonHandler.createObjectNode() .put("_id", "MyId") .put("Title", "MyTitle") ); assertThatThrownBy(() -> schemaValidator.validateJson(JsonHandler.createObjectNode() .put("Title", "MyTitle") ) ).isInstanceOf(JsonSchemaValidationException.class); } @Test public void forUserSchemaWithInvalidSchema() { String schema = "invalid"; assertThatThrownBy(() -> JsonSchemaValidator.forUserSchema(schema)) .isInstanceOf(InvalidJsonSchemaException.class); }
### Question: XMLInputFactoryUtils { public static XMLInputFactory newInstance() { XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE); xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE); xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.FALSE); return xmlInputFactory; } static XMLInputFactory newInstance(); }### Answer: @Test public final void shouldNotInjectExternalEntity() throws IOException, XMLStreamException { XMLEventReader eventReader = XMLInputFactoryUtils.newInstance().createXMLEventReader(PropertiesUtils.getResourceAsStream(XML_FILE_WITH_XXE)); while(eventReader.hasNext()) { final XMLEvent event = eventReader.nextEvent(); if(event.isCharacters()) { Assert.assertFalse(event.asCharacters().getData().contains("root:x:0:0")); } } } @Test public final void shoulInjectExternalEntity() throws IOException, XMLStreamException { XMLEventReader eventReader = XMLInputFactory.newInstance().createXMLEventReader(PropertiesUtils.getResourceAsStream(XML_FILE_WITH_XXE)); while(eventReader.hasNext()) { final XMLEvent event = eventReader.nextEvent(); if(event.isCharacters()) { Assert.assertTrue(event.asCharacters().getData().contains("root:x:0:0")); break; } } }
### Question: StatusMessage { @Override public String toString() { try { return JsonHandler.writeAsString(this); } catch (final InvalidParseOperationException e) { LOGGER.warn(e); return "unknownStatusMessage"; } } StatusMessage(); StatusMessage(ServerIdentityInterface serverIdentity); final String getName(); final String getRole(); final int getPid(); @Override String toString(); }### Answer: @Test public void testToString() throws Exception { final StatusMessage statusMessage = new StatusMessage(ServerIdentity.getInstance()); final String jsonExpected = JsonHandler.writeAsString(statusMessage); assertEquals(jsonExpected, statusMessage.toString()); }
### Question: MetadataStorageHelper { public static JsonNode getUnitFromUnitWithLFC(JsonNode document) { if(document == null || !document.hasNonNull(UNIT_KEY)) { throw new IllegalArgumentException("Document should contain a "+UNIT_KEY+" object"); } return document.get(UNIT_KEY); } static JsonNode getUnitWithLFC(JsonNode document, JsonNode lfc); static JsonNode getUnitFromUnitWithLFC(JsonNode document); static JsonNode getGotWithLFC(JsonNode document, JsonNode lfc); }### Answer: @Test public void shouldGetUnit_when_jsonContainsUnit() { ObjectNode document = JsonHandler.createObjectNode(); document.set("unit", JsonHandler.createObjectNode()); document.set("lfc", JsonHandler.createObjectNode()); JsonNode unit = MetadataStorageHelper.getUnitFromUnitWithLFC(document); assertThat(unit).isNotNull(); } @Test public void shouldThrowIllegalArgumentException_when_jsonDoesNotContainsUnit() { ObjectNode document = JsonHandler.createObjectNode(); document.set("lfc", JsonHandler.createObjectNode()); assertThatThrownBy(() -> { MetadataStorageHelper.getUnitFromUnitWithLFC(document); }).isInstanceOf(IllegalArgumentException.class); } @Test public void shouldThrowIllegalArgumentException_when_jsonNull() { ObjectNode document = null; assertThatThrownBy(() -> { MetadataStorageHelper.getUnitFromUnitWithLFC(document); }).isInstanceOf(IllegalArgumentException.class); }
### Question: VitamSession { public void setRequestId(String newRequestId) { checkCallingThread(); final Object oldRequestId = MDC.get(GlobalDataRest.X_REQUEST_ID); if (oldRequestId != requestId) { LOGGER.warn( "Caution : inconsistency detected between content of the VitamSession (requestId:{}) and the Logging MDC (requestId:{})", oldRequestId, requestId); } requestId = newRequestId; MDC.put(GlobalDataRest.X_REQUEST_ID, newRequestId); } VitamSession(VitamThreadFactory.VitamThread owningThread); static VitamSession from(VitamSession origin); Object getOther(); VitamSession setOther(Object other); String getRequestId(); void setRequestId(String newRequestId); void setInternalRequestId(String newRequestId); String getInternalRequestId(); Integer getTenantId(); void setTenantId(Integer newTenantId); void setRequestId(GUID guid); String getContractId(); void setContractId(String contractId); AccessContractModel getContract(); void setContract(AccessContractModel contract); String getContextId(); void setContextId(String contextId); String getSecurityProfileIdentifier(); void setSecurityProfileIdentifier(String securityProfileIdentifier); String getApplicationSessionId(); void setApplicationSessionId(String applicationSessionId); String getPersonalCertificate(); void setPersonalCertificate(String personalCertificate); void mutateFrom(@NotNull VitamSession newSession); void erase(); void checkValidRequestId(); void initIfAbsent(Integer tenantId); @Override String toString(); }### Answer: @Test(expected = IllegalStateException.class) public void testSetRequestIdInDifferentThread() throws Exception { final VitamSession session = new VitamSession(new VitamThreadFactory.VitamThread(null, 0)); session.setRequestId("toto"); }
### Question: VitamSession { public void mutateFrom(@NotNull VitamSession newSession) { if (newSession == null) { throw new IllegalArgumentException("VitamSession should not be null"); } setRequestId(newSession.getRequestId()); setInternalRequestId(newSession.getInternalRequestId()); setTenantId(newSession.getTenantId()); setContractId(newSession.getContractId()); setContract(newSession.getContract()); setOther(newSession.getOther()); setContextId(newSession.getContextId()); setApplicationSessionId(newSession.getApplicationSessionId()); setSecurityProfileIdentifier(newSession.getSecurityProfileIdentifier()); setPersonalCertificate(newSession.getPersonalCertificate()); } VitamSession(VitamThreadFactory.VitamThread owningThread); static VitamSession from(VitamSession origin); Object getOther(); VitamSession setOther(Object other); String getRequestId(); void setRequestId(String newRequestId); void setInternalRequestId(String newRequestId); String getInternalRequestId(); Integer getTenantId(); void setTenantId(Integer newTenantId); void setRequestId(GUID guid); String getContractId(); void setContractId(String contractId); AccessContractModel getContract(); void setContract(AccessContractModel contract); String getContextId(); void setContextId(String contextId); String getSecurityProfileIdentifier(); void setSecurityProfileIdentifier(String securityProfileIdentifier); String getApplicationSessionId(); void setApplicationSessionId(String applicationSessionId); String getPersonalCertificate(); void setPersonalCertificate(String personalCertificate); void mutateFrom(@NotNull VitamSession newSession); void erase(); void checkValidRequestId(); void initIfAbsent(Integer tenantId); @Override String toString(); }### Answer: @Test(expected = IllegalStateException.class) public void testMutateFromInDifferentThread() throws Exception { final VitamSession session1 = new VitamSession(new VitamThreadFactory.VitamThread(null, 0)); final VitamSession session2 = new VitamSession(new VitamThreadFactory.VitamThread(null, 0)); session1.mutateFrom(session2); }
### Question: VitamSession { public void erase() { mutateFrom(new VitamSession(owningThread)); } VitamSession(VitamThreadFactory.VitamThread owningThread); static VitamSession from(VitamSession origin); Object getOther(); VitamSession setOther(Object other); String getRequestId(); void setRequestId(String newRequestId); void setInternalRequestId(String newRequestId); String getInternalRequestId(); Integer getTenantId(); void setTenantId(Integer newTenantId); void setRequestId(GUID guid); String getContractId(); void setContractId(String contractId); AccessContractModel getContract(); void setContract(AccessContractModel contract); String getContextId(); void setContextId(String contextId); String getSecurityProfileIdentifier(); void setSecurityProfileIdentifier(String securityProfileIdentifier); String getApplicationSessionId(); void setApplicationSessionId(String applicationSessionId); String getPersonalCertificate(); void setPersonalCertificate(String personalCertificate); void mutateFrom(@NotNull VitamSession newSession); void erase(); void checkValidRequestId(); void initIfAbsent(Integer tenantId); @Override String toString(); }### Answer: @Test(expected = IllegalStateException.class) public void testEraseInDifferentThread() throws Exception { final VitamSession session = new VitamSession(new VitamThreadFactory.VitamThread(null, 0)); session.erase(); }
### Question: VitamSession { public String getRequestId() { return requestId; } VitamSession(VitamThreadFactory.VitamThread owningThread); static VitamSession from(VitamSession origin); Object getOther(); VitamSession setOther(Object other); String getRequestId(); void setRequestId(String newRequestId); void setInternalRequestId(String newRequestId); String getInternalRequestId(); Integer getTenantId(); void setTenantId(Integer newTenantId); void setRequestId(GUID guid); String getContractId(); void setContractId(String contractId); AccessContractModel getContract(); void setContract(AccessContractModel contract); String getContextId(); void setContextId(String contextId); String getSecurityProfileIdentifier(); void setSecurityProfileIdentifier(String securityProfileIdentifier); String getApplicationSessionId(); void setApplicationSessionId(String applicationSessionId); String getPersonalCertificate(); void setPersonalCertificate(String personalCertificate); void mutateFrom(@NotNull VitamSession newSession); void erase(); void checkValidRequestId(); void initIfAbsent(Integer tenantId); @Override String toString(); }### Answer: @Test public void testGetRequestIdInDifferentThread() throws Exception { final VitamSession session = new VitamSession(new VitamThreadFactory.VitamThread(null, 0)); Assert.assertNull(session.getRequestId()); }
### Question: TextByLang { public List<TextType> getTextTypes() { return textTypes; } TextByLang(); TextByLang(List<TextType> textTypes); List<TextType> getTextTypes(); boolean isNotEmpty(); }### Answer: @Test public void should_remove_default_lang() { ArrayList<TextType> textTypes = new ArrayList<>(); TextType textType = new TextType(); textType.setValue("value"); textTypes.add(textType); TextByLang textByLang = new TextByLang(textTypes); assertThat(textByLang.getTextTypes()).hasSize(0); }
### Question: GUIDImplPrivate extends GUIDImpl { static final int jvmProcessId() { try { int processId = -1; final String customProcessId = SystemPropertyUtil.getNoCheck(FR_GOUV_VITAM_PROCESS_ID); if (customProcessId != null) { processId = parseProcessId(processId, customProcessId); } if (processId < 0) { final ClassLoader loader = getSystemClassLoader(); String value; final Object[] emptyObjects = new Object[0]; final Class<?>[] emptyClasses = new Class[0]; value = jvmProcessIdManagementFactory(loader, emptyObjects, emptyClasses); final int atIndex = value.indexOf('@'); if (atIndex >= 0) { value = value.substring(0, atIndex); } processId = parseProcessId(processId, value); if (processId < 0 || processId > MAX_PID) { processId = RANDOM.nextInt(MAX_PID + 1); } } return processId; } catch (final Exception e) { LOGGER.error("Error while getting JVMPID", e); return RANDOM.nextInt(MAX_PID + 1); } } GUIDImplPrivate(); GUIDImplPrivate(final int objectTypeId); GUIDImplPrivate(final int objectTypeId, final int tenantId); GUIDImplPrivate(final boolean worm); GUIDImplPrivate(final int objectTypeId, final boolean worm); GUIDImplPrivate(final int objectTypeId, final int tenantId, final boolean worm); GUIDImplPrivate(final int objectTypeId, final int tenantId, final int platformId); GUIDImplPrivate(final int objectTypeId, final int tenantId, final int platformId, final boolean worm); GUIDImplPrivate(final byte[] bytes); GUIDImplPrivate(final String idsource); }### Answer: @Test public void testPIDField() { final GUIDImplPrivate id = new GUIDImplPrivate(); assertEquals(GUIDImplPrivate.jvmProcessId(), id.getProcessId()); }
### Question: GUIDFactory { public static final GUID newUnitGUID(final int tenantId) { final int type = GUIDObjectType.UNIT_TYPE; return new GUIDImplPrivate(type, tenantId, serverIdentity.getGlobalPlatformId(), GUIDObjectType.getDefaultWorm(type)); } private GUIDFactory(); static final GUID newGUID(); static final GUID newUnitGUID(final int tenantId); static final GUID newObjectGroupGUID(final int tenantId); static final GUID newObjectGroupGUID(final GUID unitParentGUID); static final GUID newObjectGUID(final int tenantId); static final GUID newObjectGUID(final GUID objectGroupParentGUID); static final GUID newOperationLogbookGUID(final int tenantId); static final GUID newWriteLogbookGUID(final int tenantId); static final GUID newStorageOperationGUID(final int tenantId, final boolean worm); static final GUID newEventGUID(final int tenantId); static final GUID newEventGUID(final GUID logbookGUID); static final GUID newRequestIdGUID(final int tenantId); static final GUID newManifestGUID(final int tenantId); static final GUID newAccessionRegisterSummaryGUID(final int tenantId); static final GUID newAccessionRegisterSymbolicGUID(final int tenantId); static final GUID newContractGUID(final int tenantId); static final GUID newProfileGUID(final int tenantId); static final GUID newOntologyGUID(final int tenantId); static final GUID newContextGUID(); static final GUID newAgencyGUID(final int tenantId); static final GUID newAccessionRegisterDetailGUID( int tenantId); static final boolean isWorm(final GUID uuid); static final int getKeysize(); static final int getKeysizeBase32(); }### Answer: @Test public final void testNewUnitGUID() { final GUID guid = GUIDFactory.newUnitGUID(1); assertEquals(GUIDObjectType.UNIT_TYPE, guid.getObjectId()); assertEquals(1, guid.getTenantId()); assertFalse(guid.isWorm()); }
### Question: GUIDImpl extends GUIDAbstract { @Override @JsonIgnore public final boolean isWorm() { return (guid[PLATFORM_POS] & 0x80) != 0; } GUIDImpl(); GUIDImpl(final byte[] bytes); GUIDImpl(final String idsource); static int getKeySize(); @Override @JsonIgnore final int getVersion(); @Override @JsonIgnore final int getObjectId(); @Override @JsonIgnore final int getTenantId(); @Override @JsonIgnore final boolean isWorm(); @Override @JsonIgnore final int getPlatformId(); @Override @JsonIgnore final byte[] getMacFragment(); @Override @JsonIgnore final int getProcessId(); @Override @JsonIgnore final long getTimestamp(); @Override @JsonIgnore final int getCounter(); @Override @JsonIgnore final String toArkName(); @Override int compareTo(final GUID arg1); }### Answer: @Test public final void testIsWorm() { GUIDImpl guid = null; try { guid = new GUIDImpl(properties.getProperty(FIELDS.BASE32.name())); } catch (final InvalidGuidOperationException e) { LOGGER.error(ResourcesPublicUtilTest.SHOULD_NOT_HAVE_AN_EXCEPTION, e); fail(ResourcesPublicUtilTest.SHOULD_NOT_HAVE_AN_EXCEPTION); } assertFalse(guid.isWorm()); try { guid = new GUIDImpl(properties.getProperty(FIELDS.BASE32B.name())); } catch (final InvalidGuidOperationException e) { LOGGER.error(ResourcesPublicUtilTest.SHOULD_NOT_HAVE_AN_EXCEPTION, e); fail(ResourcesPublicUtilTest.SHOULD_NOT_HAVE_AN_EXCEPTION); } assertTrue(guid.isWorm()); }
### Question: SafeFileChecker { public static void checkSafeFilePath(String path) throws IOException { checkNullParameter(path); try { File sanityCheckedFile = doSanityCheck(path); doCanonicalPathCheck(sanityCheckedFile.getPath()); doDirCheck(sanityCheckedFile.getParent()); doFilenameCheck(sanityCheckedFile.getName()); } catch (Exception ex) { throw new IOException(ex); } } private SafeFileChecker(); static void checkSafeFilePath(String path); static void checkSafePluginsFilesPath(String path); static void checkSafeFilePath(String rootPath, String... subPaths); }### Answer: @Test public void checkValidSubPaths() { for(String subPath : validPaths) { assertThatCode(() -> SafeFileChecker.checkSafeFilePath(VALID_ROOT_PATH, subPath)) .doesNotThrowAnyException(); } } @Test public void checkValidRootPaths() { for(String rootPath : validPaths) { assertThatCode(() -> SafeFileChecker.checkSafeFilePath(rootPath, VALID_SUBPATH)) .doesNotThrowAnyException(); } } @Test public void checkInvalidRootPaths() { for(String rootPath : invalidPaths) { assertThatCode(() -> SafeFileChecker.checkSafeFilePath(rootPath, VALID_SUBPATH)) .isInstanceOf(IOException.class); } } @Test public void checkInvalidSubPaths() { for(String subPath : invalidFilenames) { assertThatCode(() -> SafeFileChecker.checkSafeFilePath(VALID_ROOT_PATH, subPath)) .isInstanceOf(IOException.class); } }
### Question: SanityChecker { public static final void checkXmlAll(File xmlFile) throws InvalidParseOperationException, IOException { checkXmlSanityFileSize(xmlFile); checkXmlSanityTags(xmlFile); checkXmlSanityTagValueSize(xmlFile); } private SanityChecker(); static boolean isValidFileName(String value); static final void checkXmlAll(File xmlFile); static final String sanitizeJson(JsonNode json); static final void checkJsonAll(JsonNode json); static final void checkJsonAll(String json); static final void checkParameter(String... params); static final void checkHTMLFile(File file); static final void checkHeaders(final HttpHeaders headers); static final void checkHeadersMap(MultivaluedMap<String, String> requestHeaders); static final void checkUriParametersMap(MultivaluedMap<String, String> uriParameters); static final long getLimitFileSize(); static final void setLimitFileSize(long limitFileSize); static final long getLimitJsonSize(); static final void setLimitJsonSize(long limitJsonSize); static final int getLimitFieldSize(); static final void setLimitFieldSize(int limitFieldSize); static final int getLimitParamSize(); static final void setLimitParamSize(int limitParamSize); static final String HTTP_PARAMETER_VALUE; }### Answer: @Test public void checkXMLAllOK() throws IOException, InvalidParseOperationException { SanityChecker.checkXmlAll(fileOK); }
### Question: ServerIdentity implements ServerIdentityInterface { public final ServerIdentity setName(String name) { ParametersChecker.checkParameter("Name", name); this.name = name; initializeCommentFormat(); return this; } private ServerIdentity(); @JsonIgnore @Override final String getLoggerMessagePrepend(); @JsonIgnore final String getJsonIdentity(); static final ServerIdentity getInstance(); @JsonIgnore final ServerIdentity setFromPropertyFile(File propertiesFile); @JsonIgnore final ServerIdentity setFromYamlFile(File yamlFile); @JsonIgnore final ServerIdentity setFromMap(Map<String, Object> map); @Override final String getName(); final ServerIdentity setName(String name); @Override final String getRole(); final ServerIdentity setRole(String role); @Override final int getGlobalPlatformId(); final ServerIdentity setServerId(int serverId); @Override final int getServerId(); @Override final int getSiteId(); final ServerIdentity setSiteId(int siteId); }### Answer: @Test public final void testSetName() { testGetInstance(); final ServerIdentity serverIdentity = ServerIdentity.getInstance(); final String role = serverIdentity.getRole(); final int pid = serverIdentity.getGlobalPlatformId(); serverIdentity.setName("name1"); assertEquals("Server Name test", "name1", serverIdentity.getName()); assertEquals("Role still the same", role, serverIdentity.getRole()); assertEquals("Pid still the same", pid, serverIdentity.getGlobalPlatformId()); }
### Question: ServerIdentity implements ServerIdentityInterface { public final ServerIdentity setRole(String role) { ParametersChecker.checkParameter("Role", role); this.role = role; initializeCommentFormat(); return this; } private ServerIdentity(); @JsonIgnore @Override final String getLoggerMessagePrepend(); @JsonIgnore final String getJsonIdentity(); static final ServerIdentity getInstance(); @JsonIgnore final ServerIdentity setFromPropertyFile(File propertiesFile); @JsonIgnore final ServerIdentity setFromYamlFile(File yamlFile); @JsonIgnore final ServerIdentity setFromMap(Map<String, Object> map); @Override final String getName(); final ServerIdentity setName(String name); @Override final String getRole(); final ServerIdentity setRole(String role); @Override final int getGlobalPlatformId(); final ServerIdentity setServerId(int serverId); @Override final int getServerId(); @Override final int getSiteId(); final ServerIdentity setSiteId(int siteId); }### Answer: @Test public final void testSetRole() { testGetInstance(); final ServerIdentity serverIdentity = ServerIdentity.getInstance(); final String name = serverIdentity.getName(); final int pid = serverIdentity.getGlobalPlatformId(); serverIdentity.setRole("name2"); assertEquals("Server Role test", "name2", serverIdentity.getRole()); assertEquals("Name still the same", name, serverIdentity.getName()); assertEquals("Pid still the same", pid, serverIdentity.getGlobalPlatformId()); }
### Question: ServerIdentity implements ServerIdentityInterface { @JsonIgnore public final ServerIdentity setFromYamlFile(File yamlFile) throws FileNotFoundException { try { final ServerIdentityConfigurationImpl serverIdentityConf = PropertiesUtils.readYaml(yamlFile, ServerIdentityConfigurationImpl.class); setYamlConfiguration(serverIdentityConf); } catch (final IOException e) { SysErrLogger.FAKE_LOGGER.ignoreLog(e); } initializeCommentFormat(); return this; } private ServerIdentity(); @JsonIgnore @Override final String getLoggerMessagePrepend(); @JsonIgnore final String getJsonIdentity(); static final ServerIdentity getInstance(); @JsonIgnore final ServerIdentity setFromPropertyFile(File propertiesFile); @JsonIgnore final ServerIdentity setFromYamlFile(File yamlFile); @JsonIgnore final ServerIdentity setFromMap(Map<String, Object> map); @Override final String getName(); final ServerIdentity setName(String name); @Override final String getRole(); final ServerIdentity setRole(String role); @Override final int getGlobalPlatformId(); final ServerIdentity setServerId(int serverId); @Override final int getServerId(); @Override final int getSiteId(); final ServerIdentity setSiteId(int siteId); }### Answer: @Test public final void testSetFromYamlFile() { testGetInstance(); final ServerIdentity serverIdentity = ServerIdentity.getInstance(); final File file = ResourcesPrivateUtilTest.getInstance().getServerIdentityYamlFile(); if (file == null) { LOGGER.error(ResourcesPrivateUtilTest.CANNOT_FIND_RESOURCES_TEST_FILE); } Assume.assumeTrue(ResourcesPrivateUtilTest.CANNOT_FIND_RESOURCES_TEST_FILE, file != null); try { serverIdentity.setFromYamlFile(file); } catch (final FileNotFoundException e) { LOGGER.error("Yaml file not found", e); fail("Should find the Yaml file: " + e.getMessage()); } assertEquals("Name still the same", "name1", serverIdentity.getName()); assertEquals("Role still the same", "role1", serverIdentity.getRole()); assertEquals("Pid still the same", 1, serverIdentity.getSiteId()); }
### Question: AlertServiceImpl implements AlertService { @Override public void createAlert(VitamLogLevel level, String message) { LOGGER.log(level, message); } AlertServiceImpl(); AlertServiceImpl(VitamLogger lOGGER); @Override void createAlert(VitamLogLevel level, String message); @Override void createAlert(String message); }### Answer: @Test public void testCreateDebugAlert() { alertService.createAlert(VitamLogLevel.DEBUG, message); verify(logger).log(VitamLogLevel.DEBUG,message); } @Test public void testCreateAlert() { alertService.createAlert(message); verify(logger).log(VitamLogLevel.INFO,message); }
### Question: DirectedCycle { public boolean isCyclic() { return isCyclic; } DirectedCycle(DirectedGraph graph); boolean hasCycle(); boolean isCyclic(); Stack<Integer> getCycle(); }### Answer: @Test public void given_aCyclycGraph() throws Exception { final File file = PropertiesUtils.getResourceFile("ingest_acyc.json"); final JsonNode json = JsonHandler.getFromFile(file); final DirectedGraph g = new DirectedGraph(json); final DirectedCycle dc = new DirectedCycle(g); assertFalse(dc.isCyclic()); }
### Question: BulkBufferingEntryIterator implements Iterator<T> { @Override public boolean hasNext() { if (this.endOfStream) { return false; } if (this.buffer == null) { load(); } else if (this.nextPos >= this.buffer.size()) { if (this.buffer.size() < bufferSize) { this.endOfStream = true; } else { load(); } } return !this.endOfStream; } BulkBufferingEntryIterator(int bufferSize); @Override boolean hasNext(); @Override T next(); }### Answer: @Test public void testEmpty() { Supplier<List<String>> supplier = mock(Supplier.class); Iterator<String> instance = new BulkBufferingEntryIterator<String>(10) { @Override protected List<String> loadNextChunk(int chunkSize) { return supplier.get(); } }; when(supplier.get()).thenReturn(Collections.emptyList()); assertThat(instance.hasNext()).isFalse(); assertThatThrownBy(instance::next).isInstanceOf(NoSuchElementException.class); verify(supplier).get(); }
### Question: ClientConfigurationImpl implements ClientConfiguration { @Override public int getServerPort() { return serverPort; } ClientConfigurationImpl(); ClientConfigurationImpl(String serverHost, int serverPort); @Override String getServerHost(); @Override int getServerPort(); @Override ClientConfigurationImpl setServerHost(String serverHost); @Override ClientConfigurationImpl setServerPort(int serverPort); @Override boolean isSecure(); }### Answer: @Test public void testBuildOk() { ClientConfigurationImpl clientConfigurationImpl0 = new ClientConfigurationImpl("H.Y", 75); assertEquals(75, clientConfigurationImpl0.getServerPort()); clientConfigurationImpl0 = new ClientConfigurationImpl(); final int int0 = clientConfigurationImpl0.getServerPort(); assertEquals(0, int0); }
### Question: SSLConfiguration { public SSLConfiguration() { } SSLConfiguration(); SSLConfiguration(List<SSLKey> keystore, List<SSLKey> truststore); Registry<ConnectionSocketFactory> getRegistry(SSLContext sslContext); SSLContext createSSLContext(); List<SSLKey> getTruststore(); List<SSLKey> getKeystore(); SSLConfiguration setTruststore(List<SSLKey> truststore); SSLConfiguration setKeystore(List<SSLKey> keystore); String getProtocol(); void setProtocol(String protocol); }### Answer: @Test public void testSSLConfiguration() throws Exception { SSLConfiguration config = new SSLConfiguration(); assertNull(config.getKeystore()); try { context = config.createSSLContext(); fail("Should raized an exception"); } catch (final VitamException e) { } truststore = new ArrayList<>(); keystore = new ArrayList<>(); truststore.add(key); keystore.add(key); config = new SSLConfiguration(keystore, truststore); config.setKeystore(keystore); config.setTruststore(truststore); context = config.createSSLContext(); assertEquals(1, config.getTruststore().size()); assertEquals(1, config.getKeystore().size()); assertNotNull(context); }
### Question: AbstractMockClient implements MockOrRestClient { @Override public void checkStatus() { } @Override void checkStatus(); @Override void checkStatus(MultivaluedHashMap<String, Object> headers); @Override void close(); @Override String getResourcePath(); @Override String getServiceUrl(); @Override void consumeAnyEntityAndClose(Response response); }### Answer: @Test public void testCheckStatus() { final AbstractMockClient client = new AbstractMockClient(); client.checkStatus(); assertEquals("/", client.getResourcePath()); assertEquals("http: client.consumeAnyEntityAndClose(null); client.close(); }
### Question: VitamServerFactory { public static VitamServer newVitamServerOnDefaultPort() { return newVitamServer(defaultPort); } private VitamServerFactory(); static VitamServer newVitamServerOnDefaultPort(); static void setDefaultPort(int port); static int getDefaultPort(); static VitamServer newVitamServer(int port); static VitamServer newVitamServerWithoutConnector(int port); static VitamServer newVitamServerByJettyConf(final String jettyConfigFile); }### Answer: @Test public final void testNewVitamServerOnDefaultPort() { final JunitHelper junitHelper = JunitHelper.getInstance(); final int serverPort = junitHelper.findAvailablePort(); final int oldPort = VitamServerFactory.getDefaultPort(); VitamServerFactory.setDefaultPort(serverPort); final VitamServer server = VitamServerFactory.newVitamServerOnDefaultPort(); assertEquals(serverPort, server.getPort()); assertNull(server.getHandler()); assertFalse(server.isConfigured()); try { server.configure(null); fail("Should raized an axception"); } catch (final VitamApplicationServerException e) { } try { server.startAndJoin(); fail("Should raized an axception"); } catch (final VitamApplicationServerException e) { } junitHelper.releasePort(serverPort); VitamServerFactory.setDefaultPort(oldPort); }
### Question: VitamServerFactory { public static VitamServer newVitamServer(int port) { ParametersChecker.checkValue("Port", port, 1); return new BasicVitamServer(port); } private VitamServerFactory(); static VitamServer newVitamServerOnDefaultPort(); static void setDefaultPort(int port); static int getDefaultPort(); static VitamServer newVitamServer(int port); static VitamServer newVitamServerWithoutConnector(int port); static VitamServer newVitamServerByJettyConf(final String jettyConfigFile); }### Answer: @Test public final void testNewVitamServer() { final JunitHelper junitHelper = JunitHelper.getInstance(); final int port = junitHelper.findAvailablePort(); final VitamServer server = VitamServerFactory.newVitamServer(port); assertEquals(port, server.getPort()); assertNull(server.getHandler()); assertFalse(server.isConfigured()); try { server.configure(null); fail("Should raized an axception"); } catch (final VitamApplicationServerException e) { } try { server.startAndJoin(); fail("Should raized an axception"); } catch (final VitamApplicationServerException e) { } junitHelper.releasePort(port); }