method2testcases
stringlengths 118
6.63k
|
---|
### Question:
CmdUtils { public static String run(CommandLine commandline) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); DefaultExecutor exec = new DefaultExecutor(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60*1000); exec.setWatchdog(watchdog); exec.setExitValues(null); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream); exec.setStreamHandler(streamHandler); exec.execute(commandline); String out = outputStream.toString("utf8"); String error = errorStream.toString("utf8"); return out + error; } catch (Exception e) { logger.error(e.getMessage(), e); return e.toString(); } } static String run(CommandLine commandline); static String runCmd(String cmd); static String run(String[] cmd); static String callShell(String cmd); }### Answer:
@Test public void test() { CommandLine cmd =new CommandLine("ps"); cmd.addArgument("-ef"); String rt=CmdUtils.run(cmd); System.err.println(rt); } |
### Question:
TimeViewUtils { public static String format(Date date) { long delta = new Date().getTime() - date.getTime(); if (delta < 1L * ONE_MINUTE) { long seconds = toSeconds(delta); return (seconds <= 0 ? 1 : seconds) + ONE_SECOND_AGO; } if (delta < 45L * ONE_MINUTE) { long minutes = toMinutes(delta); return (minutes <= 0 ? 1 : minutes) + ONE_MINUTE_AGO; } if (delta < 24L * ONE_HOUR) { long hours = toHours(delta); return (hours <= 0 ? 1 : hours) + ONE_HOUR_AGO; } if (delta < 48L * ONE_HOUR) { return "昨天"; } if (delta < 30L * ONE_DAY) { long days = toDays(delta); return (days <= 0 ? 1 : days) + ONE_DAY_AGO; } if (delta < 12L * 4L * ONE_WEEK) { long months = toMonths(delta); return (months <= 0 ? 1 : months) + ONE_MONTH_AGO; } else { long years = toYears(delta); return (years <= 0 ? 1 : years) + ONE_YEAR_AGO; } } static String format(Date date); }### Answer:
@Test public void test() { try{ SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:m:s"); Date date = format.parse("2017-09-08 08:35:35"); System.out.println(TimeViewUtils.format(date)); }catch (Exception e){ } } |
### Question:
IOUtils { public static String getPath( String path){ if(path == null || path.equals("") ) return ""; String[] a = path.split("\\/"); path=path.replace(a[a.length-1],""); return path; } IOUtils(String body, String path); void setPath(String path); void setBody(String body); static void createDir(String path); static void writeFile(String body, String path); static String readFile(String path); static String getPath( String path); static boolean delFile(String path); }### Answer:
@Test public void test() { String p=IOUtils.getPath("/data/www/ROOT/1.txt"); System.out.println(p); } |
### Question:
EntityFinder { public <T, ID> T findById(CrudRepository<T, ID> repository, ID id, String notFoundMessage) { Optional<T> findResult = repository.findById(id); return getEntity(findResult, notFoundMessage); } T findById(CrudRepository<T, ID> repository,
ID id,
String notFoundMessage); T findOne(QuerydslPredicateExecutor<T> predicateExecutor,
Predicate predicate,
String notFoundMessage); }### Answer:
@Test public void findByIdShouldReturnResultWhenIsPresent() throws Exception { String processInstanceId = "5"; ProcessInstanceEntity processInstanceEntity = mock(ProcessInstanceEntity.class); given(repository.findById(processInstanceId)).willReturn(Optional.of(processInstanceEntity)); ProcessInstanceEntity retrieveProcessInstanceEntity = entityFinder.findById(repository, processInstanceId, "error"); assertThat(retrieveProcessInstanceEntity).isEqualTo(processInstanceEntity); }
@Test public void findByIdShouldThrowExceptionWhenNotPresent() throws Exception { String processInstanceId = "5"; given(repository.findById(processInstanceId)).willReturn(Optional.empty()); expectedException.expect(IllegalStateException.class); expectedException.expectMessage("Error"); entityFinder.findById(repository, processInstanceId, "Error"); } |
### Question:
QueryRelProvider implements RelProvider { @Override public String getCollectionResourceRelFor(Class<?> aClass) { return resourceRelationDescriptors.get(aClass).getCollectionResourceRel(); } QueryRelProvider(); @Override String getItemResourceRelFor(Class<?> aClass); @Override String getCollectionResourceRelFor(Class<?> aClass); @Override boolean supports(Class<?> aClass); }### Answer:
@Test public void getCollectionResourceRelForShouldReturnProcessInstancesWhenIsProcessInstanceEntity() { String collectionResourceRel = relProvider.getCollectionResourceRelFor(ProcessInstanceEntity.class); assertThat(collectionResourceRel).isEqualTo("processInstances"); }
@Test public void getCollectionResourceRelForShouldReturnTasksWhenIsTaskEntity() { String collectionResourceRel = relProvider.getCollectionResourceRelFor(TaskEntity.class); assertThat(collectionResourceRel).isEqualTo("tasks"); }
@Test public void getCollectionResourceRelForShouldReturnVariablesWhenIsProcessVariableEntity() { String collectionResourceRel = relProvider.getCollectionResourceRelFor(ProcessVariableEntity.class); assertThat(collectionResourceRel).isEqualTo("variables"); }
@Test public void getCollectionResourceRelForShouldReturnVariablesWhenIsTaskVariableEntity() { String collectionResourceRel = relProvider.getCollectionResourceRelFor(TaskVariableEntity.class); assertThat(collectionResourceRel).isEqualTo("variables"); }
@Test public void getCollectionResourceRelForShouldReturnProcessDefinitionsWhenIsProcessDefinitionEntity() { String collectionResourceRel = relProvider.getCollectionResourceRelFor(ProcessDefinitionEntity.class); assertThat(collectionResourceRel).isEqualTo("processDefinitions"); } |
### Question:
QueryRelProvider implements RelProvider { @Override public boolean supports(Class<?> aClass) { return resourceRelationDescriptors.keySet().contains(aClass); } QueryRelProvider(); @Override String getItemResourceRelFor(Class<?> aClass); @Override String getCollectionResourceRelFor(Class<?> aClass); @Override boolean supports(Class<?> aClass); }### Answer:
@Test public void shouldSupportProcessDefinitionEntity() { boolean supports = relProvider.supports(ProcessDefinitionEntity.class); assertThat(supports).isTrue(); }
@Test public void shouldSupportProcessInstanceEntity() { boolean supports = relProvider.supports(ProcessInstanceEntity.class); assertThat(supports).isTrue(); }
@Test public void shouldSupportTaskEntity() { boolean supports = relProvider.supports(TaskEntity.class); assertThat(supports).isTrue(); }
@Test public void shouldSupportProcessVariableEntity() { boolean supports = relProvider.supports(ProcessVariableEntity.class); assertThat(supports).isTrue(); }
@Test public void shouldSupportTaskVariableEntity() { boolean supports = relProvider.supports(TaskVariableEntity.class); assertThat(supports).isTrue(); }
@Test public void shouldNotSupportUncoveredClasses() { boolean supports = relProvider.supports(ActivitiEntityMetadata.class); assertThat(supports).isFalse(); } |
### Question:
ProcessStartedEventHandler implements QueryEventHandler { @Override public void handle(CloudRuntimeEvent<?, ?> event) { CloudProcessStartedEvent startedEvent = (CloudProcessStartedEvent) event; String processInstanceId = startedEvent.getEntity().getId(); LOGGER.debug("Handling start of process Instance " + processInstanceId); Optional<ProcessInstanceEntity> findResult = processInstanceRepository.findById(processInstanceId); ProcessInstanceEntity processInstanceEntity = findResult.orElseThrow( () -> new QueryException("Unable to find process instance with the given id: " + processInstanceId)); if (ProcessInstance.ProcessInstanceStatus.CREATED.equals(processInstanceEntity.getStatus())) { processInstanceEntity.setStatus(ProcessInstance.ProcessInstanceStatus.RUNNING); processInstanceEntity.setName(startedEvent.getEntity().getName()); processInstanceEntity.setLastModified(new Date(startedEvent.getTimestamp())); processInstanceRepository.save(processInstanceEntity); } } ProcessStartedEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void handleShouldUpdateProcessInstanceStatusToRunningAndUpdateInstanceName() { CloudProcessStartedEvent event = buildProcessStartedEvent(); ProcessInstanceEntity currentProcessInstanceEntity = mock(ProcessInstanceEntity.class); given(currentProcessInstanceEntity.getStatus()).willReturn(ProcessInstance.ProcessInstanceStatus.CREATED); given(processInstanceRepository.findById(event.getEntity().getId())).willReturn(Optional.of(currentProcessInstanceEntity)); handler.handle(event); verify(processInstanceRepository).save(currentProcessInstanceEntity); verify(currentProcessInstanceEntity).setStatus(ProcessInstance.ProcessInstanceStatus.RUNNING); verify(currentProcessInstanceEntity).setName(event.getEntity().getName()); }
@Test public void handleShouldIgnoreEventIfProcessInstanceIsAlreadyInRunningStatus() { CloudProcessStartedEvent event = buildProcessStartedEvent(); ProcessInstanceEntity currentProcessInstanceEntity = mock(ProcessInstanceEntity.class); given(currentProcessInstanceEntity.getStatus()).willReturn(ProcessInstance.ProcessInstanceStatus.RUNNING); given(processInstanceRepository.findById(event.getEntity().getId())).willReturn(Optional.of(currentProcessInstanceEntity)); handler.handle(event); verify(processInstanceRepository, never()).save(currentProcessInstanceEntity); verify(currentProcessInstanceEntity, never()).setStatus(ProcessInstance.ProcessInstanceStatus.RUNNING); }
@Test public void handleShouldThrowExceptionWhenRelatedProcessInstanceIsNotFound() { CloudProcessStartedEvent event = buildProcessStartedEvent(); given(processInstanceRepository.findById("200")).willReturn(Optional.empty()); expectedException.expect(QueryException.class); expectedException.expectMessage("Unable to find process instance with the given id: "); handler.handle(event); } |
### Question:
ProcessStartedEventHandler implements QueryEventHandler { @Override public String getHandledEvent() { return ProcessRuntimeEvent.ProcessEvents.PROCESS_STARTED.name(); } ProcessStartedEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void getHandledEventShouldReturnProcessStartedEvent() { String handledEvent = handler.getHandledEvent(); assertThat(handledEvent).isEqualTo(ProcessRuntimeEvent.ProcessEvents.PROCESS_STARTED.name()); } |
### Question:
QueryEventHandlerContext { public void handle(CloudRuntimeEvent<?, ?>... events) { if (events != null) { for (CloudRuntimeEvent<?, ?> event : events) { QueryEventHandler handler = handlers.get(event.getEventType().name()); if (handler != null) { LOGGER.debug("Handling event: " + handler.getHandledEvent()); handler.handle(event); } else { LOGGER.info("No handler found for event: " + event.getEventType().name() + ". Ignoring event"); } } } } QueryEventHandlerContext(Set<QueryEventHandler> handlers); void handle(CloudRuntimeEvent<?, ?>... events); }### Answer:
@Test public void handleShouldSelectHandlerBasedOnEventType() { CloudTaskCreatedEvent event = new CloudTaskCreatedEventImpl(); context.handle(event); verify(handler).handle(event); }
@Test public void handleShouldDoNothingWhenNoHandlerIsFoundForTheGivenEvent() { CloudTaskCompletedEvent event = new CloudTaskCompletedEventImpl(); context.handle(event); verify(handler, never()).handle(any()); } |
### Question:
ProcessSuspendedEventHandler implements QueryEventHandler { @Override public void handle(CloudRuntimeEvent<?, ?> event) { CloudProcessSuspendedEvent suspendedEvent = (CloudProcessSuspendedEvent) event; String processInstanceId = suspendedEvent.getEntity().getId(); ProcessInstanceEntity processInstanceEntity = processInstanceRepository.findById(processInstanceId) .orElseThrow( () -> new QueryException("Unable to find process instance with the given id: " + processInstanceId) ); processInstanceEntity.setStatus(ProcessInstance.ProcessInstanceStatus.SUSPENDED); processInstanceEntity.setLastModified(new Date(suspendedEvent.getTimestamp())); processInstanceRepository.save(processInstanceEntity); } ProcessSuspendedEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void handleShouldUpdateCurrentProcessInstanceStateToSuspended() { CloudProcessSuspendedEvent event = buildProcessSuspendedEvent(); ProcessInstanceEntity currentProcessInstanceEntity = mock(ProcessInstanceEntity.class); given(processInstanceRepository.findById(event.getEntity().getId())).willReturn(Optional.of(currentProcessInstanceEntity)); handler.handle(event); verify(processInstanceRepository).save(currentProcessInstanceEntity); verify(currentProcessInstanceEntity).setStatus(ProcessInstance.ProcessInstanceStatus.SUSPENDED); verify(currentProcessInstanceEntity).setLastModified(any(Date.class)); }
@Test public void handleShouldThrowExceptionWhenRelatedProcessInstanceIsNotFound() { CloudProcessSuspendedEvent event = buildProcessSuspendedEvent(); given(processInstanceRepository.findById("200")).willReturn(Optional.empty()); expectedException.expect(QueryException.class); expectedException.expectMessage("Unable to find process instance with the given id: "); handler.handle(event); } |
### Question:
ProcessSuspendedEventHandler implements QueryEventHandler { @Override public String getHandledEvent() { return ProcessRuntimeEvent.ProcessEvents.PROCESS_SUSPENDED.name(); } ProcessSuspendedEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void getHandledEventShouldReturnProcessSuspendedEvent() { String handledEvent = handler.getHandledEvent(); assertThat(handledEvent).isEqualTo(ProcessRuntimeEvent.ProcessEvents.PROCESS_SUSPENDED.name()); } |
### Question:
ProcessCompletedEventHandler implements QueryEventHandler { @Override public void handle(CloudRuntimeEvent<?, ?> event) { CloudProcessCompletedEvent completedEvent = (CloudProcessCompletedEvent) event; String processInstanceId = completedEvent.getEntity().getId(); Optional<ProcessInstanceEntity> findResult = processInstanceRepository.findById(processInstanceId); if (findResult.isPresent()) { ProcessInstanceEntity processInstanceEntity = findResult.get(); processInstanceEntity.setStatus(ProcessInstance.ProcessInstanceStatus.COMPLETED); processInstanceEntity.setLastModified(new Date(completedEvent.getTimestamp())); processInstanceRepository.save(processInstanceEntity); } else { throw new QueryException("Unable to find process instance with the given id: " + processInstanceId); } } ProcessCompletedEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void handleShouldUpdateCurrentProcessInstanceStateToCompleted() { CloudProcessCompletedEvent event = createProcessCompletedEvent(); ProcessInstanceEntity currentProcessInstanceEntity = mock(ProcessInstanceEntity.class); given(processInstanceRepository.findById(event.getEntity().getId())).willReturn(Optional.of(currentProcessInstanceEntity)); handler.handle(event); verify(processInstanceRepository).save(currentProcessInstanceEntity); verify(currentProcessInstanceEntity).setStatus(ProcessInstance.ProcessInstanceStatus.COMPLETED); verify(currentProcessInstanceEntity).setLastModified(any(Date.class)); }
@Test public void handleShouldThrowExceptionWhenRelatedProcessInstanceIsNotFound() { CloudProcessCompletedEvent event = createProcessCompletedEvent(); given(processInstanceRepository.findById("200")).willReturn(Optional.empty()); expectedException.expect(QueryException.class); expectedException.expectMessage("Unable to find process instance with the given id: "); handler.handle(event); } |
### Question:
EntityFinder { public <T> T findOne(QuerydslPredicateExecutor<T> predicateExecutor, Predicate predicate, String notFoundMessage) { Optional<T> findResult = predicateExecutor.findOne(predicate); return getEntity(findResult, notFoundMessage); } T findById(CrudRepository<T, ID> repository,
ID id,
String notFoundMessage); T findOne(QuerydslPredicateExecutor<T> predicateExecutor,
Predicate predicate,
String notFoundMessage); }### Answer:
@Test public void findOneShouldReturnResultWhenIsPresent() throws Exception { Predicate predicate = mock(Predicate.class); ProcessInstanceEntity processInstanceEntity = mock(ProcessInstanceEntity.class); given(repository.findOne(predicate)).willReturn(Optional.of(processInstanceEntity)); ProcessInstanceEntity retrievedProcessInstanceEntity = entityFinder.findOne(repository, predicate, "error"); assertThat(retrievedProcessInstanceEntity).isEqualTo(processInstanceEntity); }
@Test public void findOneShouldThrowExceptionWhenNotPresent() throws Exception { Predicate predicate = mock(Predicate.class); given(repository.findOne(predicate)).willReturn(Optional.empty()); expectedException.expect(IllegalStateException.class); expectedException.expectMessage("Error"); entityFinder.findOne(repository, predicate, "Error"); } |
### Question:
ProcessCompletedEventHandler implements QueryEventHandler { @Override public String getHandledEvent() { return ProcessRuntimeEvent.ProcessEvents.PROCESS_COMPLETED.name(); } ProcessCompletedEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void getHandledEventShouldReturnProcessCompletedEvent() { String handledEvent = handler.getHandledEvent(); assertThat(handledEvent).isEqualTo(ProcessRuntimeEvent.ProcessEvents.PROCESS_COMPLETED.name()); } |
### Question:
ProcessUpdatedEventHandler implements QueryEventHandler { @Override public void handle(CloudRuntimeEvent<?, ?> event) { CloudProcessUpdatedEvent updatedEvent = (CloudProcessUpdatedEvent) event; ProcessInstance eventProcessInstance = updatedEvent.getEntity(); ProcessInstanceEntity processInstanceEntity = processInstanceRepository.findById(eventProcessInstance.getId()) .orElseThrow( () -> new QueryException("Unable to find process instance with the given id: " + eventProcessInstance.getId()) ); processInstanceEntity.setBusinessKey(eventProcessInstance.getBusinessKey()); processInstanceEntity.setName(eventProcessInstance.getName()); processInstanceEntity.setLastModified(new Date(updatedEvent.getTimestamp())); processInstanceRepository.save(processInstanceEntity); } ProcessUpdatedEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void handleShouldUpdateCurrentProcessInstance() { CloudProcessUpdatedEvent event = buildProcessUpdatedEvent(); ProcessInstanceEntity currentProcessInstanceEntity = mock(ProcessInstanceEntity.class); given(processInstanceRepository.findById(event.getEntity().getId())).willReturn(Optional.of(currentProcessInstanceEntity)); handler.handle(event); verify(processInstanceRepository).save(currentProcessInstanceEntity); verify(currentProcessInstanceEntity).setBusinessKey(event.getEntity().getBusinessKey()); verify(currentProcessInstanceEntity).setName(event.getEntity().getName()); verify(currentProcessInstanceEntity).setLastModified(any(Date.class)); verifyNoMoreInteractions(currentProcessInstanceEntity); }
@Test public void handleShouldThrowExceptionWhenRelatedProcessInstanceIsNotFound() { CloudProcessUpdatedEvent event = buildProcessUpdatedEvent(); String id = event.getEntity().getId(); given(processInstanceRepository.findById(id)).willReturn(Optional.empty()); expectedException.expect(QueryException.class); expectedException.expectMessage("Unable to find process instance with the given id: "); handler.handle(event); } |
### Question:
ProcessUpdatedEventHandler implements QueryEventHandler { @Override public String getHandledEvent() { return ProcessRuntimeEvent.ProcessEvents.PROCESS_UPDATED.name(); } ProcessUpdatedEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void getHandledEventShouldReturnProcessUpdatedEvent() { String handledEvent = handler.getHandledEvent(); assertThat(handledEvent).isEqualTo(ProcessRuntimeEvent.ProcessEvents.PROCESS_UPDATED.name()); } |
### Question:
ProcessDeployedEventHandler implements QueryEventHandler { @Override public void handle(CloudRuntimeEvent<?, ?> event) { CloudProcessDeployedEvent processDeployedEvent = (CloudProcessDeployedEvent) event; ProcessDefinition eventProcessDefinition = processDeployedEvent.getEntity(); LOGGER.debug("Handling process deployed event for " + eventProcessDefinition.getKey()); ProcessDefinitionEntity processDefinition = new ProcessDefinitionEntity(processDeployedEvent.getServiceName(), processDeployedEvent.getServiceFullName(), processDeployedEvent.getServiceVersion(), processDeployedEvent.getAppName(), processDeployedEvent.getAppVersion()); processDefinition.setId(eventProcessDefinition.getId()); processDefinition.setDescription(eventProcessDefinition.getDescription()); processDefinition.setFormKey(eventProcessDefinition.getFormKey()); processDefinition.setKey(eventProcessDefinition.getKey()); processDefinition.setName(eventProcessDefinition.getName()); processDefinition.setVersion(eventProcessDefinition.getVersion()); processDefinition.setServiceType(processDeployedEvent.getServiceType()); processDefinitionRepository.save(processDefinition); ProcessModelEntity processModelEntity = new ProcessModelEntity(processDefinition, processDeployedEvent.getProcessModelContent()); processModelEntity.setId(processDefinition.getId()); processModelRepository.save(processModelEntity); } ProcessDeployedEventHandler(ProcessDefinitionRepository processDefinitionRepository,
ProcessModelRepository processModelRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void handleShouldStoreProcessDefinitionAndProcessModel() { ProcessDefinitionImpl eventProcess = new ProcessDefinitionImpl(); eventProcess.setId(UUID.randomUUID().toString()); eventProcess.setKey("myProcess"); eventProcess.setName("My Process"); eventProcess.setDescription("This is my process description"); eventProcess.setFormKey("formKey"); eventProcess.setVersion(2); CloudProcessDeployedEventImpl processDeployedEvent = new CloudProcessDeployedEventImpl(eventProcess); processDeployedEvent.setAppName("myApp"); processDeployedEvent.setAppVersion("2.1"); processDeployedEvent.setServiceFullName("my.full.service.name"); processDeployedEvent.setServiceName("name"); processDeployedEvent.setServiceType("runtime-bundle"); processDeployedEvent.setServiceVersion("1.0"); processDeployedEvent.setProcessModelContent("<model/>"); handler.handle(processDeployedEvent); ArgumentCaptor<ProcessDefinitionEntity> processDefinitionCaptor = ArgumentCaptor.forClass(ProcessDefinitionEntity.class); verify(processDefinitionRepository).save(processDefinitionCaptor.capture()); ProcessDefinitionEntity storedProcess = processDefinitionCaptor.getValue(); assertThat(storedProcess) .hasId(eventProcess.getId()) .hasKey(eventProcess.getKey()) .hasName(eventProcess.getName()) .hasDescription(eventProcess.getDescription()) .hasFormKey(eventProcess.getFormKey()) .hasVersion(eventProcess.getVersion()) .hasAppName(processDeployedEvent.getAppName()) .hasAppVersion(processDeployedEvent.getAppVersion()) .hasServiceFullName(processDeployedEvent.getServiceFullName()) .hasServiceName(processDeployedEvent.getServiceName()) .hasServiceType(processDeployedEvent.getServiceType()) .hasServiceVersion(processDeployedEvent.getServiceVersion()); ArgumentCaptor<ProcessModelEntity> processModelCaptor = ArgumentCaptor.forClass(ProcessModelEntity.class); verify(processModelRepository).save(processModelCaptor.capture()); assertThat(processModelCaptor.getValue()) .hasProcessModelContent("<model/>"); } |
### Question:
ProcessDeployedEventHandler implements QueryEventHandler { @Override public String getHandledEvent() { return ProcessDefinitionEvent.ProcessDefinitionEvents.PROCESS_DEPLOYED.name(); } ProcessDeployedEventHandler(ProcessDefinitionRepository processDefinitionRepository,
ProcessModelRepository processModelRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void getHandledEventShouldReturnProcessDeployedEvent() { String handledEvent = handler.getHandledEvent(); Assertions.assertThat(handledEvent).isEqualTo(ProcessDefinitionEvent.ProcessDefinitionEvents.PROCESS_DEPLOYED.name()); } |
### Question:
ProcessResumedEventHandler implements QueryEventHandler { @Override public void handle(CloudRuntimeEvent<?, ?> event) { CloudProcessResumedEvent processResumedEvent = (CloudProcessResumedEvent) event; String processInstanceId = processResumedEvent.getEntity().getId(); Optional<ProcessInstanceEntity> findResult = processInstanceRepository.findById(processInstanceId); ProcessInstanceEntity processInstanceEntity = findResult.orElseThrow(() -> new QueryException("Unable to find process instance with the given id: " + processInstanceId)); processInstanceEntity.setStatus(ProcessInstance.ProcessInstanceStatus.RUNNING); processInstanceEntity.setLastModified(new Date(processResumedEvent.getTimestamp())); processInstanceRepository.save(processInstanceEntity); } ProcessResumedEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void handleShouldUpdateCurrentProcessInstanceStateToRunning() { ProcessInstanceImpl eventProcessInstance = new ProcessInstanceImpl(); eventProcessInstance.setId(UUID.randomUUID().toString()); CloudProcessResumedEvent event = new CloudProcessResumedEventImpl(eventProcessInstance); ProcessInstanceEntity currentProcessInstanceEntity = mock(ProcessInstanceEntity.class); given(processInstanceRepository.findById(eventProcessInstance.getId())).willReturn(Optional.of(currentProcessInstanceEntity)); handler.handle(event); verify(processInstanceRepository).save(currentProcessInstanceEntity); verify(currentProcessInstanceEntity).setStatus(ProcessInstance.ProcessInstanceStatus.RUNNING); verify(currentProcessInstanceEntity).setLastModified(any(Date.class)); }
@Test public void handleShouldThrowExceptionWhenRelatedProcessInstanceIsNotFound() { ProcessInstanceImpl eventProcessInstance = new ProcessInstanceImpl(); eventProcessInstance.setId(UUID.randomUUID().toString()); CloudProcessResumedEvent event = new CloudProcessResumedEventImpl(eventProcessInstance); given(processInstanceRepository.findById(eventProcessInstance.getId())).willReturn(Optional.empty()); expectedException.expect(QueryException.class); expectedException.expectMessage("Unable to find process instance with the given id: "); handler.handle(event); } |
### Question:
ProcessResumedEventHandler implements QueryEventHandler { @Override public String getHandledEvent() { return ProcessRuntimeEvent.ProcessEvents.PROCESS_RESUMED.name(); } ProcessResumedEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void getHandledEventShouldReturnProcessResumedEvent() { String handledEvent = handler.getHandledEvent(); assertThat(handledEvent).isEqualTo(ProcessRuntimeEvent.ProcessEvents.PROCESS_RESUMED.name()); } |
### Question:
ProcessCancelledEventHandler implements QueryEventHandler { @Override public void handle(CloudRuntimeEvent<?, ?> event) { CloudProcessCancelledEvent cancelledEvent = (CloudProcessCancelledEvent) event; LOGGER.debug("Handling cancel of process Instance " + cancelledEvent.getEntity().getId()); updateProcessInstanceStatus( processInstanceRepository .findById(cancelledEvent.getEntity().getId()) .orElseThrow(() -> new QueryException( "Unable to find process instance with the given id: " + cancelledEvent.getEntity().getId())), cancelledEvent.getTimestamp()); } ProcessCancelledEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void testUpdateExistingProcessInstanceWhenCancelled() { ProcessInstanceEntity processInstanceEntity = mock(ProcessInstanceEntity.class); given(processInstanceRepository.findById("200")).willReturn(Optional.of(processInstanceEntity)); handler.handle(createProcessCancelledEvent("200" )); verify(processInstanceRepository).save(processInstanceEntity); verify(processInstanceEntity).setStatus(ProcessInstance.ProcessInstanceStatus.CANCELLED); verify(processInstanceEntity).setLastModified(any(Date.class)); }
@Test public void testThrowExceptionWhenProcessInstanceNotFound() { given(processInstanceRepository.findById("200")).willReturn(Optional.empty()); expectedException.expect(QueryException.class); expectedException.expectMessage("Unable to find process instance with the given id: "); handler.handle(createProcessCancelledEvent("200")); } |
### Question:
ProcessCancelledEventHandler implements QueryEventHandler { @Override public String getHandledEvent() { return ProcessRuntimeEvent.ProcessEvents.PROCESS_CANCELLED.name(); } ProcessCancelledEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void getHandledEventShouldReturnProcessCancelledEvent() { String handledEvent = handler.getHandledEvent(); assertThat(handledEvent).isEqualTo(ProcessRuntimeEvent.ProcessEvents.PROCESS_CANCELLED.name()); } |
### Question:
ProcessCreatedEventHandler implements QueryEventHandler { @Override public void handle(CloudRuntimeEvent<?, ?> event) { CloudProcessCreatedEvent createdEvent = (CloudProcessCreatedEvent) event; LOGGER.debug("Handling created process Instance " + createdEvent.getEntity().getId()); ProcessInstanceEntity createdProcessInstanceEntity = new ProcessInstanceEntity(); createdProcessInstanceEntity.setServiceName(createdEvent.getServiceName()); createdProcessInstanceEntity.setServiceFullName(createdEvent.getServiceFullName()); createdProcessInstanceEntity.setServiceVersion(createdEvent.getServiceVersion()); createdProcessInstanceEntity.setAppName(createdEvent.getAppName()); createdProcessInstanceEntity.setAppVersion(createdEvent.getAppVersion()); createdProcessInstanceEntity.setProcessDefinitionId(createdEvent.getEntity().getProcessDefinitionId()); createdProcessInstanceEntity.setId(createdEvent.getEntity().getId()); createdProcessInstanceEntity.setStatus(ProcessInstance.ProcessInstanceStatus.CREATED); createdProcessInstanceEntity.setLastModified(new Date(createdEvent.getTimestamp())); createdProcessInstanceEntity.setName(createdEvent.getEntity().getName()); createdProcessInstanceEntity.setProcessDefinitionKey(createdEvent.getEntity().getProcessDefinitionKey()); createdProcessInstanceEntity.setInitiator(createdEvent.getEntity().getInitiator()); createdProcessInstanceEntity.setBusinessKey(createdEvent.getEntity().getBusinessKey()); createdProcessInstanceEntity.setStartDate(createdEvent.getEntity().getStartDate()); createdProcessInstanceEntity.setParentId(createdEvent.getEntity().getParentId()); createdProcessInstanceEntity.setProcessDefinitionVersion(createdEvent.getEntity().getProcessDefinitionVersion()); processInstanceRepository.save(createdProcessInstanceEntity); } ProcessCreatedEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void handleShouldUpdateCurrentProcessInstanceStateToCreated() { CloudProcessCreatedEvent event = buildProcessCreatedEvent(); handler.handle(event); ArgumentCaptor<ProcessInstanceEntity> argumentCaptor = ArgumentCaptor.forClass(ProcessInstanceEntity.class); verify(processInstanceRepository).save(argumentCaptor.capture()); ProcessInstanceEntity processInstanceEntity = argumentCaptor.getValue(); Assertions.assertThat(processInstanceEntity) .hasId(event.getEntity().getId()) .hasProcessDefinitionId(event.getEntity().getProcessDefinitionId()) .hasServiceName(event.getServiceName()) .hasProcessDefinitionKey(event.getEntity().getProcessDefinitionKey()) .hasStatus(ProcessInstance.ProcessInstanceStatus.CREATED) .hasName(event.getEntity().getName()); } |
### Question:
ProcessCreatedEventHandler implements QueryEventHandler { @Override public String getHandledEvent() { return ProcessRuntimeEvent.ProcessEvents.PROCESS_CREATED.name(); } ProcessCreatedEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void getHandledEventShouldReturnProcessCreatedEvent() { String handledEvent = handler.getHandledEvent(); assertThat(handledEvent).isEqualTo(ProcessRuntimeEvent.ProcessEvents.PROCESS_CREATED.name()); } |
### Question:
VariableValueJsonConverter implements AttributeConverter<VariableValue<?>, String> { @Override public String convertToDatabaseColumn(VariableValue<?> variableValue) { try { return objectMapper.writeValueAsString(variableValue); } catch (JsonProcessingException e) { throw new QueryException("Unable to serialize variable.", e); } } VariableValueJsonConverter(); VariableValueJsonConverter(ObjectMapper objectMapper); @Override String convertToDatabaseColumn(VariableValue<?> variableValue); @Override VariableValue<?> convertToEntityAttribute(String dbData); }### Answer:
@Test public void convertToDatabaseColumnShouldConvertToJson() throws Exception { given(objectMapper.writeValueAsString(ENTITY_REPRESENTATION)).willReturn(JSON_REPRESENTATION); String convertedValue = converter.convertToDatabaseColumn(ENTITY_REPRESENTATION); assertThat(convertedValue).isEqualTo(JSON_REPRESENTATION); }
@Test public void convertToDatabaseColumnShouldThrowQueryExceptionWhenAnExceptionOccursWhileProcessing() throws Exception { MockJsonProcessingException exception = new MockJsonProcessingException("any"); given(objectMapper.writeValueAsString(ENTITY_REPRESENTATION)).willThrow(exception); Throwable thrown = catchThrowable(() -> converter.convertToDatabaseColumn(ENTITY_REPRESENTATION)); assertThat(thrown) .isInstanceOf(QueryException.class) .hasMessage("Unable to serialize variable.") .hasCause(exception); } |
### Question:
VariableValueJsonConverter implements AttributeConverter<VariableValue<?>, String> { @Override public VariableValue<?> convertToEntityAttribute(String dbData) { try { return objectMapper.readValue(dbData, VariableValue.class); } catch (IOException e) { throw new QueryException("Unable to deserialize variable.", e); } } VariableValueJsonConverter(); VariableValueJsonConverter(ObjectMapper objectMapper); @Override String convertToDatabaseColumn(VariableValue<?> variableValue); @Override VariableValue<?> convertToEntityAttribute(String dbData); }### Answer:
@Test public void convertToEntityAttributeShouldConvertFromJson() throws Exception { given(objectMapper.readValue(JSON_REPRESENTATION, VariableValue.class)).willReturn(ENTITY_REPRESENTATION); VariableValue<?> convertedValue = converter.convertToEntityAttribute(JSON_REPRESENTATION); assertThat(convertedValue).isEqualTo(ENTITY_REPRESENTATION); }
@Test public void convertToEntityAttributeShouldThrowExceptionWhenExceptionOccursWhileReading() throws Exception { IOException ioException = new IOException(); given(objectMapper.readValue(JSON_REPRESENTATION, VariableValue.class)).willThrow(ioException); Throwable thrown = catchThrowable(() -> converter.convertToEntityAttribute(JSON_REPRESENTATION)); assertThat(thrown) .isInstanceOf(QueryException.class) .hasMessage("Unable to deserialize variable.") .hasCause(ioException); } |
### Question:
QueryRelProvider implements RelProvider { @Override public String getItemResourceRelFor(Class<?> aClass) { return resourceRelationDescriptors.get(aClass).getItemResourceRel(); } QueryRelProvider(); @Override String getItemResourceRelFor(Class<?> aClass); @Override String getCollectionResourceRelFor(Class<?> aClass); @Override boolean supports(Class<?> aClass); }### Answer:
@Test public void getItemResourceRelForShouldReturnProcessDefinitionWhenIsProcessDefinitionEntity() { String itemResourceRel = relProvider.getItemResourceRelFor(ProcessDefinitionEntity.class); assertThat(itemResourceRel).isEqualTo("processDefinition"); }
@Test public void getItemResourceRelForShouldReturnProcessInstanceWhenIsProcessInstanceEntity() { String itemResourceRel = relProvider.getItemResourceRelFor(ProcessInstanceEntity.class); assertThat(itemResourceRel).isEqualTo("processInstance"); }
@Test public void getItemResourceRelForShouldReturnTaskWhenIsTaskEntity() { String itemResourceRel = relProvider.getItemResourceRelFor(TaskEntity.class); assertThat(itemResourceRel).isEqualTo("task"); }
@Test public void getItemResourceRelForShouldReturnVariableWhenIsProcessVariableEntity() { String itemResourceRel = relProvider.getItemResourceRelFor(ProcessVariableEntity.class); assertThat(itemResourceRel).isEqualTo("variable"); }
@Test public void getItemResourceRelForShouldReturnVariableWhenIsTaskVariableEntity() { String itemResourceRel = relProvider.getItemResourceRelFor(TaskVariableEntity.class); assertThat(itemResourceRel).isEqualTo("variable"); } |
### Question:
MessageProducerCommandContextCloseListener implements CommandContextCloseListener { @Override public void closed(CommandContext commandContext) { List<CloudRuntimeEvent<?, ?>> events = commandContext.getGenericAttribute(PROCESS_ENGINE_EVENTS); if (events != null && !events.isEmpty()) { CloudRuntimeEvent<?, ?>[] payload = events.stream() .filter(CloudRuntimeEventImpl.class::isInstance) .map(CloudRuntimeEventImpl.class::cast) .map(runtimeBundleInfoAppender::appendRuntimeBundleInfoTo) .toArray(CloudRuntimeEvent<?, ?>[]::new); Message<CloudRuntimeEvent<?, ?>[]> message = messageBuilderChainFactory.create(null) .withPayload(payload) .build(); producer.auditProducer().send(message); } } MessageProducerCommandContextCloseListener(ProcessEngineChannels producer,
MessageBuilderChainFactory<ExecutionContext> messageBuilderChainFactory,
RuntimeBundleInfoAppender runtimeBundleInfoAppender ); @Override void closed(CommandContext commandContext); @Override void closing(CommandContext commandContext); @Override void afterSessionsFlush(CommandContext commandContext); @Override void closeFailure(CommandContext commandContext); static final String PROCESS_ENGINE_EVENTS; }### Answer:
@Test public void closedShouldSendEventsRegisteredOnTheCommandContext() { processEngineEventsAggregator.add(event); given(commandContext.getGenericAttribute(MessageProducerCommandContextCloseListener.PROCESS_ENGINE_EVENTS)) .willReturn(Collections.singletonList(event)); closeListener.closed(commandContext); verify(auditChannel).send(messageArgumentCaptor.capture()); assertThat(messageArgumentCaptor.getValue() .getPayload()).containsExactly(event); CloudRuntimeEvent<?, ?>[] result = messageArgumentCaptor.getValue().getPayload(); assertThat(result).hasSize(1); assertThat(result[0].getProcessInstanceId()).isEqualTo(MOCK_PROCESS_INSTANCE_ID); assertThat(result[0].getParentProcessInstanceId()).isEqualTo(MOCK_PARENT_PROCESS_INSTANCE_ID); assertThat(result[0].getBusinessKey()).isEqualTo(MOCK_BUSINESS_KEY); assertThat(result[0].getProcessDefinitionId()).isEqualTo(MOCK_PROCESS_DEFINITION_ID); assertThat(result[0].getProcessDefinitionKey()).isEqualTo(MOCK_PROCESS_DEFINITION_KEY); assertThat(result[0].getProcessDefinitionVersion()).isEqualTo(MOCK_PROCESS_DEFINITION_VERSION); assertThat(result[0].getAppName()).isEqualTo(APP_NAME); assertThat(result[0].getServiceName()).isEqualTo(SPRING_APP_NAME); assertThat(result[0].getServiceType()).isEqualTo(SERVICE_TYPE); assertThat(result[0].getServiceVersion()).isEqualTo(SERVICE_VERSION); }
@Test public void closedShouldDoNothingWhenRegisteredEventsIsNull() { given(commandContext.getGenericAttribute(MessageProducerCommandContextCloseListener.PROCESS_ENGINE_EVENTS)) .willReturn(null); closeListener.closed(commandContext); verify(auditChannel, never()).send(any()); }
@Test public void closedShouldDoNothingWhenRegisteredEventsIsEmpty() { given(commandContext.getGenericAttribute(MessageProducerCommandContextCloseListener.PROCESS_ENGINE_EVENTS)) .willReturn(Collections.emptyList()); closeListener.closed(commandContext); verify(auditChannel, never()).send(any()); }
@Test public void closedShouldSendMessageHeadersWithExecutionContext() { given(commandContext.getGenericAttribute(MessageProducerCommandContextCloseListener.PROCESS_ENGINE_EVENTS)) .willReturn(Collections.singletonList(event)); closeListener.closed(commandContext); verify(auditChannel).send(messageArgumentCaptor.capture()); assertThat(messageArgumentCaptor.getValue() .getHeaders()).containsEntry("routingKey", MOCK_ROUTING_KEY) .containsEntry("messagePayloadType",LORG_ACTIVITI_CLOUD_API_MODEL_SHARED_EVENTS_CLOUD_RUNTIME_EVENT) .containsEntry("appName", APP_NAME) .containsEntry("serviceName",SPRING_APP_NAME) .containsEntry("serviceType", SERVICE_TYPE) .containsEntry("serviceVersion", SERVICE_VERSION) .containsEntry("serviceFullName",SPRING_APP_NAME); } |
### Question:
ProcessEngineEventsAggregator extends BaseCommandContextEventsAggregator<CloudRuntimeEvent<?,?>, MessageProducerCommandContextCloseListener> { @Override public void add(CloudRuntimeEvent<?, ?> element) { CommandContext commandContext = getCurrentCommandContext(); String executionId = resolveExecutionId(element); ExecutionContext executionContext = resolveExecutionContext(commandContext, executionId); if(executionContext != null) { ExecutionContextInfoAppender executionContextInfoAppender = createExecutionContextInfoAppender(executionContext); CloudRuntimeEventImpl<?,?> event = CloudRuntimeEventImpl.class.cast(element); element = executionContextInfoAppender.appendExecutionContextInfoTo(event); } super.add(element); } ProcessEngineEventsAggregator(MessageProducerCommandContextCloseListener closeListener); @Override void add(CloudRuntimeEvent<?, ?> element); }### Answer:
@Test public void addShouldRegisterCloseListenerWhenItIsMissing() { given(commandContext.hasCloseListener(MessageProducerCommandContextCloseListener.class)).willReturn(false); eventsAggregator.add(event); verify(commandContext).addCloseListener(closeListener); }
@Test public void addShouldNotRegisterCloseListenerWhenItIsAlreadyRegistered() { given(commandContext.hasCloseListener(MessageProducerCommandContextCloseListener.class)).willReturn(true); eventsAggregator.add(event); verify(commandContext, never()).addCloseListener(closeListener); }
@Test public void addShouldAddTheEventEventToTheEventAttributeListWhenTheAttributeAlreadyExists() { ArrayList<CloudRuntimeEvent<?,?>> currentEvents = new ArrayList<>(); given(commandContext.getGenericAttribute(MessageProducerCommandContextCloseListener.PROCESS_ENGINE_EVENTS)).willReturn(currentEvents); eventsAggregator.add(event); assertThat(currentEvents).containsExactly(event); verify(commandContext, never()).addAttribute(eq(MessageProducerCommandContextCloseListener.PROCESS_ENGINE_EVENTS), any()); }
@Test public void addShouldCreateAnewListAndRegisterItAsAttributeWhenTheAttributeDoesNotExist() { given(commandContext.getGenericAttribute(MessageProducerCommandContextCloseListener.PROCESS_ENGINE_EVENTS)).willReturn(null); eventsAggregator.add(event); verify(commandContext).addAttribute(eq(MessageProducerCommandContextCloseListener.PROCESS_ENGINE_EVENTS), eventsCaptor.capture()); assertThat(eventsCaptor.getValue()).containsExactly(event); } |
### Question:
CloudSignalReceivedProducer implements BPMNElementEventListener<BPMNSignalReceivedEvent> { @Override public void onEvent(BPMNSignalReceivedEvent event) { eventsAggregator.add(eventConverter.from(event)); } CloudSignalReceivedProducer(ToCloudProcessRuntimeEventConverter eventConverter,
ProcessEngineEventsAggregator eventsAggregator); @Override void onEvent(BPMNSignalReceivedEvent event); }### Answer:
@Test public void onEventShouldConvertEventToCloudEventAndAddToAggregator() { BPMNSignalReceivedEventImpl event = new BPMNSignalReceivedEventImpl(new BPMNSignalImpl()); CloudBPMNSignalReceivedEventImpl cloudEvent = new CloudBPMNSignalReceivedEventImpl(); given(eventConverter.from(event)).willReturn(cloudEvent); cloudSignalReceivedProducer.onEvent(event); verify(eventsAggregator).add(cloudEvent); } |
### Question:
ExecutionContextMessageBuilderAppender implements MessageBuilderAppender { @Override public <P> MessageBuilder<P> apply(MessageBuilder<P> request) { Assert.notNull(request, "request must not be null"); if(executionContext != null) { ExecutionEntity processInstance = executionContext.getProcessInstance(); ProcessDefinition processDefinition = executionContext.getProcessDefinition(); DeploymentEntity deploymentEntity = executionContext.getDeployment(); if(processInstance != null) { request.setHeader(ExecutionContextMessageHeaders.BUSINESS_KEY, processInstance.getBusinessKey()) .setHeader(ExecutionContextMessageHeaders.PROCESS_INSTANCE_ID, processInstance.getId()) .setHeader(ExecutionContextMessageHeaders.PROCESS_NAME, processInstance.getName()); applyParent(processInstance, request); } if(processDefinition != null) { request.setHeader(ExecutionContextMessageHeaders.PROCESS_DEFINITION_ID, processDefinition.getId()) .setHeader(ExecutionContextMessageHeaders.PROCESS_DEFINITION_KEY, processDefinition.getKey()) .setHeader(ExecutionContextMessageHeaders.PROCESS_DEFINITION_VERSION, processDefinition.getVersion()) .setHeader(ExecutionContextMessageHeaders.PROCESS_DEFINITION_NAME, processDefinition.getName()); } if(deploymentEntity != null) { request.setHeader(ExecutionContextMessageHeaders.DEPLOYMENT_ID, deploymentEntity.getId()) .setHeader(ExecutionContextMessageHeaders.DEPLOYMENT_NAME, deploymentEntity.getName()) .setHeader(ExecutionContextMessageHeaders.APP_VERSION, deploymentEntity.getVersion()); } } return request; } ExecutionContextMessageBuilderAppender(@Nullable ExecutionContext executionContext); @Override MessageBuilder<P> apply(MessageBuilder<P> request); }### Answer:
@Test public void testApply() { MessageBuilder<CloudRuntimeEvent<?,?>> request = MessageBuilder.withPayload(new IgnoredRuntimeEvent()); subject.apply(request); Message<CloudRuntimeEvent<?,?>> message = request.build(); assertThat(message.getHeaders()) .containsEntry(ExecutionContextMessageHeaders.BUSINESS_KEY, MOCK_BUSINESS_KEY) .containsEntry(ExecutionContextMessageHeaders.PROCESS_INSTANCE_ID, MOCK_PROCESS_INSTANCE_ID) .containsEntry(ExecutionContextMessageHeaders.PROCESS_DEFINITION_ID, MOCK_PROCESS_DEFINITION_ID) .containsEntry(ExecutionContextMessageHeaders.PROCESS_DEFINITION_KEY, MOCK_PROCESS_DEFINITION_KEY) .containsEntry(ExecutionContextMessageHeaders.PARENT_PROCESS_INSTANCE_ID, MOCK_PARENT_PROCESS_INSTANCE_ID) .containsEntry(ExecutionContextMessageHeaders.PROCESS_DEFINITION_VERSION, MOCK_PROCESS_DEFINITION_VERSION) .containsEntry(ExecutionContextMessageHeaders.PROCESS_NAME, MOCK_PROCESS_NAME) .containsEntry(ExecutionContextMessageHeaders.PARENT_PROCESS_INSTANCE_NAME, MOCK_PARENT_PROCESS_NAME) .containsEntry(ExecutionContextMessageHeaders.PROCESS_DEFINITION_NAME, MOCK_PROCESS_DEFINITION_NAME) .containsEntry(ExecutionContextMessageHeaders.DEPLOYMENT_ID, MOCK_DEPLOYMENT_ID) .containsEntry(ExecutionContextMessageHeaders.DEPLOYMENT_NAME, MOCK_DEPLOYMENT_NAME) .containsEntry(ExecutionContextMessageHeaders.APP_VERSION, MOCK_APP_VERSION); } |
### Question:
RuntimeBundleInfoMessageBuilderAppender implements MessageBuilderAppender { @Override public <P> MessageBuilder<P> apply(MessageBuilder<P> request) { Assert.notNull(request, "request must not be null"); return request.setHeader(RuntimeBundleInfoMessageHeaders.APP_NAME, properties.getAppName()) .setHeader(RuntimeBundleInfoMessageHeaders.SERVICE_NAME, properties.getServiceName()) .setHeader(RuntimeBundleInfoMessageHeaders.SERVICE_FULL_NAME, properties.getServiceFullName()) .setHeader(RuntimeBundleInfoMessageHeaders.SERVICE_TYPE, properties.getServiceType()) .setHeader(RuntimeBundleInfoMessageHeaders.SERVICE_VERSION, properties.getServiceVersion()); } RuntimeBundleInfoMessageBuilderAppender(RuntimeBundleProperties properties); @Override MessageBuilder<P> apply(MessageBuilder<P> request); }### Answer:
@Test public void testApply() { MessageBuilder<CloudRuntimeEvent<?,?>> request = MessageBuilder.withPayload(new IgnoredRuntimeEvent()); subject.apply(request); Message<CloudRuntimeEvent<?,?>> message = request.build(); assertThat(message.getHeaders()) .containsEntry(RuntimeBundleInfoMessageHeaders.APP_NAME, APP_NAME) .containsEntry(RuntimeBundleInfoMessageHeaders.SERVICE_NAME, SPRING_APP_NAME) .containsEntry(RuntimeBundleInfoMessageHeaders.SERVICE_TYPE, SERVICE_TYPE) .containsEntry(RuntimeBundleInfoMessageHeaders.SERVICE_VERSION, SERVICE_VERSION); } |
### Question:
AuditProducerRoutingKeyResolver extends AbstractMessageHeadersRoutingKeyResolver { @Override public String resolve(Map<String, Object> headers) { return build(headers, HEADER_KEYS); } @Override String resolve(Map<String, Object> headers); @Override String getPrefix(); final String ROUTING_KEY_PREFIX; final String[] HEADER_KEYS; }### Answer:
@Test public void testResolveRoutingKeyFromValidHeadersInAnyOrder() { Map<String, Object> headers = MapBuilder.<String, Object> map(RuntimeBundleInfoMessageHeaders.APP_NAME, "app-name") .with(RuntimeBundleInfoMessageHeaders.SERVICE_NAME, "service-name"); String routingKey = subject.resolve(headers); assertThat(routingKey).isEqualTo("engineEvents.service-name.app-name"); }
@Test public void testResolveRoutingKeyFromEmptyHeaders() { Map<String, Object> headers = MapBuilder.<String, Object> map(RuntimeBundleInfoMessageHeaders.APP_NAME, "") .with(RuntimeBundleInfoMessageHeaders.SERVICE_NAME, "service-name"); String routingKey = subject.resolve(headers); assertThat(routingKey).isEqualTo("engineEvents.service-name._"); }
@Test public void testResolveRoutingKeyFromNullHeaders() { Map<String, Object> headers = MapBuilder.<String, Object> map(RuntimeBundleInfoMessageHeaders.APP_NAME, null) .with(RuntimeBundleInfoMessageHeaders.SERVICE_NAME, "service-name"); String routingKey = subject.resolve(headers); assertThat(routingKey).isEqualTo("engineEvents.service-name._"); }
@Test public void testResolveRoutingKeyWithEscapedValues() { Map<String, Object> headers = MapBuilder.<String, Object> map(RuntimeBundleInfoMessageHeaders.APP_NAME, "app:na#me") .with(RuntimeBundleInfoMessageHeaders.SERVICE_NAME, "ser.vice*na me"); String routingKey = subject.resolve(headers); assertThat(routingKey).isEqualTo("engineEvents.ser-vice-na-me.app-na-me"); }
@Test public void testResolveRoutingKeyWithNonExistingHeaders() { Map<String, Object> headers = MapBuilder.<String, Object> emptyMap(); String routingKey = subject.resolve(headers); assertThat(routingKey).isEqualTo("engineEvents._._"); } |
### Question:
ToCloudProcessRuntimeEventConverter { public CloudProcessStartedEvent from(ProcessStartedEvent event) { CloudProcessStartedEventImpl cloudProcessStartedEvent = new CloudProcessStartedEventImpl(event.getEntity(), event.getNestedProcessDefinitionId(), event.getNestedProcessInstanceId()); runtimeBundleInfoAppender.appendRuntimeBundleInfoTo(cloudProcessStartedEvent); return cloudProcessStartedEvent; } ToCloudProcessRuntimeEventConverter(RuntimeBundleInfoAppender runtimeBundleInfoAppender); CloudProcessStartedEvent from(ProcessStartedEvent event); CloudProcessCreatedEvent from(ProcessCreatedEvent event); CloudProcessUpdatedEvent from(ProcessUpdatedEvent event); CloudProcessResumedEvent from(ProcessResumedEvent event); CloudProcessSuspendedEvent from(ProcessSuspendedEvent event); CloudProcessCompletedEvent from(ProcessCompletedEvent event); CloudProcessCancelledEvent from(ProcessCancelledEvent event); CloudBPMNActivityStartedEvent from(BPMNActivityStartedEvent event); CloudBPMNActivityCompletedEvent from(BPMNActivityCompletedEvent event); CloudBPMNActivityCancelledEvent from(BPMNActivityCancelledEvent event); CloudBPMNSignalReceivedEvent from(BPMNSignalReceivedEvent event); CloudSequenceFlowTakenEvent from(BPMNSequenceFlowTakenEvent event); CloudProcessDeployedEvent from(ProcessDeployedEvent event); CloudStartMessageDeployedEvent from(StartMessageDeployedEvent event); CloudMessageSubscriptionCancelledEvent from(MessageSubscriptionCancelledEvent event); CloudBPMNTimerFiredEvent from(BPMNTimerFiredEvent event); CloudBPMNTimerScheduledEvent from(BPMNTimerScheduledEvent event); CloudBPMNTimerCancelledEvent from(BPMNTimerCancelledEvent event); CloudBPMNTimerFailedEvent from(BPMNTimerFailedEvent event); CloudBPMNTimerExecutedEvent from(BPMNTimerExecutedEvent event); CloudBPMNTimerRetriesDecrementedEvent from(BPMNTimerRetriesDecrementedEvent event); CloudBPMNMessageSentEvent from(BPMNMessageSentEvent event); CloudBPMNMessageReceivedEvent from(BPMNMessageReceivedEvent event); CloudBPMNMessageWaitingEvent from(BPMNMessageWaitingEvent event); CloudBPMNErrorReceivedEvent from(BPMNErrorReceivedEvent event); }### Answer:
@Test public void fromShouldConvertInternalProcessStartedEventToExternalEvent() { ProcessInstanceImpl processInstance = new ProcessInstanceImpl(); processInstance.setId("10"); processInstance.setProcessDefinitionId("myProcessDef"); ProcessStartedEventImpl event = new ProcessStartedEventImpl(processInstance); event.setNestedProcessDefinitionId("myParentProcessDef"); event.setNestedProcessInstanceId("2"); CloudProcessStartedEvent processStarted = converter.from(event); assertThat(processStarted).isInstanceOf(CloudProcessStartedEvent.class); assertThat(processStarted.getEntity().getId()).isEqualTo("10"); assertThat(processStarted.getEntity().getProcessDefinitionId()).isEqualTo("myProcessDef"); assertThat(processStarted.getNestedProcessDefinitionId()).isEqualTo("myParentProcessDef"); assertThat(processStarted.getNestedProcessInstanceId()).isEqualTo("2"); verify(runtimeBundleInfoAppender).appendRuntimeBundleInfoTo(ArgumentMatchers.any(CloudRuntimeEventImpl.class)); }
@Test public void shouldConvertBPMNSignalReceivedEventToCloudBPMNSignalReceivedEvent() { BPMNSignalImpl signal = new BPMNSignalImpl(); signal.setProcessDefinitionId("procDefId"); signal.setProcessInstanceId("procInstId"); BPMNSignalReceivedEventImpl signalReceivedEvent = new BPMNSignalReceivedEventImpl(signal); CloudBPMNSignalReceivedEvent cloudEvent = converter.from(signalReceivedEvent); assertThat(cloudEvent.getEntity()).isEqualTo(signal); assertThat(cloudEvent.getProcessDefinitionId()).isEqualTo("procDefId"); assertThat(cloudEvent.getProcessInstanceId()).isEqualTo("procInstId"); verify(runtimeBundleInfoAppender).appendRuntimeBundleInfoTo(ArgumentMatchers.any(CloudRuntimeEventImpl.class)); } |
### Question:
MQServiceTaskBehavior extends AbstractBpmnActivityBehavior implements TriggerableActivityBehavior { @Override public void execute(DelegateExecution execution) { if (defaultServiceTaskBehavior.hasConnectorBean(execution)) { defaultServiceTaskBehavior.execute(execution); } else { IntegrationContextEntity integrationContext = storeIntegrationContext(execution); publishSpringEvent(execution, integrationContext); } } MQServiceTaskBehavior(IntegrationContextManager integrationContextManager,
ApplicationEventPublisher eventPublisher,
IntegrationContextBuilder integrationContextBuilder,
RuntimeBundleInfoAppender runtimeBundleInfoAppender,
DefaultServiceTaskBehavior defaultServiceTaskBehavior); @Override void execute(DelegateExecution execution); @Override void trigger(DelegateExecution execution,
String signalEvent,
Object signalData); }### Answer:
@Test public void executeShouldDelegateToDefaultBehaviourWhenBeanIsAvailable() { DelegateExecution execution = mock(DelegateExecution.class); given(defaultServiceTaskBehavior.hasConnectorBean(execution)).willReturn(true); behavior.execute(execution); verify(defaultServiceTaskBehavior).execute(execution); }
@Test public void executeShouldStoreTheIntegrationContextAndPublishASpringEvent() { ServiceTask serviceTask = new ServiceTask(); serviceTask.setImplementation(CONNECTOR_TYPE); DelegateExecution execution = anExecution() .withId(EXECUTION_ID) .withProcessInstanceId(PROC_INST_ID) .withProcessDefinitionId(PROC_DEF_ID) .withServiceTask(serviceTask) .withFlowNodeId(FLOW_NODE_ID) .build(); given(runtimeBundleProperties.getServiceFullName()).willReturn(APP_NAME); IntegrationContextEntityImpl entity = new IntegrationContextEntityImpl(); entity.setId(INTEGRATION_CONTEXT_ID); given(integrationContextManager.create()).willReturn(entity); given(applicationContext.containsBean(CONNECTOR_TYPE)).willReturn(false); IntegrationContext integrationContext = mock(IntegrationContext.class); given(integrationContextBuilder.from(entity, execution)).willReturn(integrationContext); behavior.execute(execution); assertThat(entity) .hasExecutionId(EXECUTION_ID) .hasProcessDefinitionId(PROC_DEF_ID) .hasProcessInstanceId(PROC_INST_ID); verify(eventPublisher).publishEvent(integrationRequestCaptor.capture()); IntegrationRequestImpl integrationRequest = integrationRequestCaptor.getValue(); assertThat(integrationRequest.getIntegrationContext()) .isEqualTo(integrationContext); verify(runtimeBundleInfoAppender).appendRuntimeBundleInfoTo(integrationRequest); } |
### Question:
MQServiceTaskBehavior extends AbstractBpmnActivityBehavior implements TriggerableActivityBehavior { @Override public void trigger(DelegateExecution execution, String signalEvent, Object signalData) { leave(execution); } MQServiceTaskBehavior(IntegrationContextManager integrationContextManager,
ApplicationEventPublisher eventPublisher,
IntegrationContextBuilder integrationContextBuilder,
RuntimeBundleInfoAppender runtimeBundleInfoAppender,
DefaultServiceTaskBehavior defaultServiceTaskBehavior); @Override void execute(DelegateExecution execution); @Override void trigger(DelegateExecution execution,
String signalEvent,
Object signalData); }### Answer:
@Test public void triggerShouldCallLeave() { DelegateExecution execution = mock(DelegateExecution.class); doNothing().when(behavior).leave(execution); behavior.trigger(execution, null, null); verify(behavior).leave(execution); } |
### Question:
IntegrationContextMessageBuilderAppender implements MessageBuilderAppender { @Override public <T> MessageBuilder<T> apply(MessageBuilder<T> request) { return request .setHeader(IntegrationContextMessageHeaders.CONNECTOR_TYPE, integrationContext.getConnectorType()) .setHeader(IntegrationContextMessageHeaders.BUSINESS_KEY, integrationContext.getBusinessKey()) .setHeader(IntegrationContextMessageHeaders.INTEGRATION_CONTEXT_ID, integrationContext.getId()) .setHeader(IntegrationContextMessageHeaders.PROCESS_INSTANCE_ID, integrationContext.getProcessInstanceId()) .setHeader(IntegrationContextMessageHeaders.PROCESS_DEFINITION_ID, integrationContext.getProcessDefinitionId()) .setHeader(IntegrationContextMessageHeaders.PROCESS_DEFINITION_KEY, integrationContext.getProcessDefinitionKey()) .setHeader(IntegrationContextMessageHeaders.PROCESS_DEFINITION_VERSION, integrationContext.getProcessDefinitionVersion()) .setHeader(IntegrationContextMessageHeaders.PARENT_PROCESS_INSTANCE_ID, integrationContext.getParentProcessInstanceId()) .setHeader(IntegrationContextMessageHeaders.APP_VERSION, integrationContext.getAppVersion()); } IntegrationContextMessageBuilderAppender(IntegrationContext integrationContext); @Override MessageBuilder<T> apply(MessageBuilder<T> request); }### Answer:
@Test public void testApply() { MessageBuilder<IntegrationRequest> request = MessageBuilder.withPayload(new IntegrationRequestImpl()); integrationBuilder.apply(request); Message<IntegrationRequest> message = request.build(); assertThat(message.getHeaders()) .containsEntry(IntegrationContextMessageHeaders.CONNECTOR_TYPE, integrationContext.getConnectorType()) .containsEntry(IntegrationContextMessageHeaders.BUSINESS_KEY, integrationContext.getBusinessKey()) .containsEntry(IntegrationContextMessageHeaders.INTEGRATION_CONTEXT_ID, integrationContext.getId()) .containsEntry(IntegrationContextMessageHeaders.PROCESS_INSTANCE_ID, integrationContext.getProcessInstanceId()) .containsEntry(IntegrationContextMessageHeaders.PROCESS_DEFINITION_ID, integrationContext.getProcessDefinitionId()) .containsEntry(IntegrationContextMessageHeaders.PROCESS_DEFINITION_KEY, integrationContext.getProcessDefinitionKey()) .containsEntry(IntegrationContextMessageHeaders.PROCESS_DEFINITION_VERSION, integrationContext.getProcessDefinitionVersion()) .containsEntry(IntegrationContextMessageHeaders.APP_VERSION, integrationContext.getAppVersion()) .containsEntry(IntegrationContextMessageHeaders.PARENT_PROCESS_INSTANCE_ID, integrationContext.getParentProcessInstanceId()); } |
### Question:
IntegrationContextRoutingKeyResolver extends AbstractMessageHeadersRoutingKeyResolver { @Override public String resolve(Map<String, Object> headers) { return build(headers, HEADER_KEYS); } @Override String resolve(Map<String, Object> headers); @Override String getPrefix(); final String[] HEADER_KEYS; }### Answer:
@Test public void testResolveRoutingKeyFromValidHeadersInAnyOrder() { Map<String, Object> headers = MapBuilder.<String, Object> map(RuntimeBundleInfoMessageHeaders.SERVICE_NAME, "service-name") .with(IntegrationContextMessageHeaders.PROCESS_INSTANCE_ID, "process-instance-id") .with(RuntimeBundleInfoMessageHeaders.APP_NAME, "app-name") .with(IntegrationContextMessageHeaders.CONNECTOR_TYPE, "connector-type") .with(IntegrationContextMessageHeaders.BUSINESS_KEY, "business-key"); String routingKey = subject.resolve(headers); assertThat(routingKey).isEqualTo("integrationContext.service-name.app-name.connector-type.process-instance-id.business-key"); } |
### Question:
IntegrationRequestSender { @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) public void sendIntegrationRequest(IntegrationRequest event) { resolver.resolveDestination(event.getIntegrationContext().getConnectorType()).send(buildIntegrationRequestMessage(event)); sendAuditEvent(event); } IntegrationRequestSender(RuntimeBundleProperties runtimeBundleProperties,
MessageChannel auditProducer,
BinderAwareChannelResolver resolver,
RuntimeBundleInfoAppender runtimeBundleInfoAppender,
IntegrationContextMessageBuilderFactory messageBuilderFactory); @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) void sendIntegrationRequest(IntegrationRequest event); static final String CONNECTOR_TYPE; }### Answer:
@Test public void shouldSendIntegrationRequestMessage() { integrationRequestSender.sendIntegrationRequest(integrationRequest); verify(integrationProducer).send(integrationRequestMessageCaptor.capture()); Message<IntegrationRequest> integrationRequestMessage = integrationRequestMessageCaptor.getValue(); IntegrationRequest sentIntegrationRequestEvent = integrationRequestMessage.getPayload(); assertThat(sentIntegrationRequestEvent).isEqualTo(integrationRequest); assertThat(integrationRequestMessage.getHeaders().get(IntegrationRequestSender.CONNECTOR_TYPE)).isEqualTo(CONNECTOR_TYPE); }
@Test public void shouldNotSendIntegrationAuditEventWhenIntegrationAuditEventsAreDisabled() { given(eventsProperties.isIntegrationAuditEventsEnabled()).willReturn(false); integrationRequestSender.sendIntegrationRequest(integrationRequest); verify(auditProducer, never()).send(ArgumentMatchers.any()); }
@Test public void shouldSendIntegrationAuditEventWhenIntegrationAuditEventsAreEnabled() { given(eventsProperties.isIntegrationAuditEventsEnabled()).willReturn(true); integrationRequestSender.sendIntegrationRequest(integrationRequest); verify(auditProducer).send(auditMessageArgumentCaptor.capture()); Message<CloudRuntimeEvent<?, ?>[]> message = auditMessageArgumentCaptor.getValue(); assertThat(message.getPayload()[0]).isInstanceOf(CloudIntegrationRequestedEventImpl.class); Assertions.assertThat(message.getHeaders()) .containsKey("routingKey") .containsKey("messagePayloadType") .containsEntry("parentProcessInstanceId",MY_PARENT_PROC_ID) .containsEntry("processDefinitionKey", MY_PROC_DEF_KEY) .containsEntry("processDefinitionVersion", PROC_DEF_VERSION) .containsEntry("businessKey", BUSINESS_KEY) .containsEntry("connectorType", PAYMENT_CONNECTOR_TYPE) .containsEntry("integrationContextId", INTEGRATION_CONTEXT_ID) .containsEntry("processInstanceId", PROC_INST_ID) .containsEntry("processDefinitionId", PROC_DEF_ID) .containsEntry("appName", APP_NAME) .containsEntry("serviceName",SPRING_APP_NAME) .containsEntry("serviceType",SERVICE_TYPE) .containsEntry("serviceVersion",SERVICE_VERSION) .containsEntry("serviceFullName",APP_NAME); CloudIntegrationRequestedEventImpl integrationRequested = (CloudIntegrationRequestedEventImpl) (message.getPayload())[0]; assertThat(integrationRequested.getEntity().getId()).isEqualTo(INTEGRATION_CONTEXT_ID); assertThat(integrationRequested.getEntity().getProcessInstanceId()).isEqualTo(PROC_INST_ID); assertThat(integrationRequested.getEntity().getProcessDefinitionId()).isEqualTo(PROC_DEF_ID); verify(runtimeBundleInfoAppender).appendRuntimeBundleInfoTo(integrationRequested); } |
### Question:
SuspendProcessInstanceCmdExecutor extends AbstractCommandExecutor<SuspendProcessPayload> { public SuspendProcessInstanceCmdExecutor(ProcessAdminRuntime processAdminRuntime) { this.processAdminRuntime = processAdminRuntime; } SuspendProcessInstanceCmdExecutor(ProcessAdminRuntime processAdminRuntime); @Override ProcessInstanceResult execute(SuspendProcessPayload suspendProcessPayload); }### Answer:
@Test public void suspendProcessInstanceCmdExecutorTest() { SuspendProcessPayload suspendProcessInstanceCmd = new SuspendProcessPayload("x"); assertThat(suspendProcessInstanceCmdExecutor.getHandledType()).isEqualTo(SuspendProcessPayload.class.getName()); suspendProcessInstanceCmdExecutor.execute(suspendProcessInstanceCmd); verify(processAdminRuntime).suspend(suspendProcessInstanceCmd); } |
### Question:
CompleteTaskCmdExecutor extends AbstractCommandExecutor<CompleteTaskPayload> { public CompleteTaskCmdExecutor(TaskAdminRuntime taskAdminRuntime) { this.taskAdminRuntime = taskAdminRuntime; } CompleteTaskCmdExecutor(TaskAdminRuntime taskAdminRuntime); @Override TaskResult execute(CompleteTaskPayload completeTaskPayload); }### Answer:
@Test public void completeTaskCmdExecutorTest() { Map<String, Object> variables = new HashMap<>(); CompleteTaskPayload completeTaskPayload = new CompleteTaskPayload("taskId", variables); assertThat(completeTaskCmdExecutor.getHandledType()).isEqualTo(CompleteTaskPayload.class.getName()); completeTaskCmdExecutor.execute(completeTaskPayload); verify(taskAdminRuntime).complete(completeTaskPayload); } |
### Question:
DeleteProcessInstanceCmdExecutor extends AbstractCommandExecutor<DeleteProcessPayload> { @Override public EmptyResult execute(DeleteProcessPayload deleteProcessPayload) { ProcessInstance processInstance = processAdminRuntime.delete(deleteProcessPayload); if (processInstance != null) { return new EmptyResult(deleteProcessPayload); } else { throw new IllegalStateException("Failed to delete processInstance"); } } DeleteProcessInstanceCmdExecutor(ProcessAdminRuntime processAdminRuntime); @Override EmptyResult execute(DeleteProcessPayload deleteProcessPayload); }### Answer:
@Test public void startProcessInstanceCmdExecutorTest() { DeleteProcessPayload payload = ProcessPayloadBuilder.delete() .withProcessInstanceId("def key") .build(); ProcessInstance fakeProcessInstance = mock(ProcessInstance.class); given(processAdminRuntime.delete(payload)).willReturn(fakeProcessInstance); assertThat(subject.getHandledType()).isEqualTo(DeleteProcessPayload.class.getName()); subject.execute(payload); verify(processAdminRuntime).delete(payload); } |
### Question:
ClaimTaskCmdExecutor extends AbstractCommandExecutor<ClaimTaskPayload> { public ClaimTaskCmdExecutor(TaskAdminRuntime taskAdminRuntime) { this.taskAdminRuntime = taskAdminRuntime; } ClaimTaskCmdExecutor(TaskAdminRuntime taskAdminRuntime); @Override TaskResult execute(ClaimTaskPayload claimTaskPayload); }### Answer:
@Test public void claimTaskCmdExecutorTest() { ClaimTaskPayload claimTaskPayload = new ClaimTaskPayload("taskId", "assignee"); assertThat(claimTaskCmdExecutor.getHandledType()).isEqualTo(ClaimTaskPayload.class.getName()); claimTaskCmdExecutor.execute(claimTaskPayload); verify(taskAdminRuntime).claim(claimTaskPayload); } |
### Question:
ReceiveMessageCmdExecutor extends AbstractCommandExecutor<ReceiveMessagePayload> { @Override public EmptyResult execute(ReceiveMessagePayload command) { processAdminRuntime.receive(command); return new EmptyResult(command); } ReceiveMessageCmdExecutor(ProcessAdminRuntime processAdminRuntime); @Override EmptyResult execute(ReceiveMessagePayload command); }### Answer:
@Test public void signalProcessInstancesCmdExecutorTest() { ReceiveMessagePayload payload = new ReceiveMessagePayload("messageName", "correlationKey", Collections.emptyMap()); assertThat(subject.getHandledType()).isEqualTo(ReceiveMessagePayload.class.getName()); subject.execute(payload); verify(processAdminRuntime).receive(payload); } |
### Question:
StartProcessInstanceCmdExecutor extends AbstractCommandExecutor<StartProcessPayload> { public StartProcessInstanceCmdExecutor(ProcessAdminRuntime processAdminRuntime) { this.processAdminRuntime = processAdminRuntime; } StartProcessInstanceCmdExecutor(ProcessAdminRuntime processAdminRuntime); @Override ProcessInstanceResult execute(StartProcessPayload startProcessPayload); }### Answer:
@Test public void startProcessInstanceCmdExecutorTest() { StartProcessPayload startProcessInstanceCmd = ProcessPayloadBuilder.start() .withProcessDefinitionKey("def key") .withName("name") .withBusinessKey("business key") .build(); ProcessInstance fakeProcessInstance = mock(ProcessInstance.class); given(processAdminRuntime.start(startProcessInstanceCmd)).willReturn(fakeProcessInstance); assertThat(startProcessInstanceCmdExecutor.getHandledType()).isEqualTo(StartProcessPayload.class.getName()); startProcessInstanceCmdExecutor.execute(startProcessInstanceCmd); verify(processAdminRuntime).start(startProcessInstanceCmd); } |
### Question:
StartMessageCmdExecutor extends AbstractCommandExecutor<StartMessagePayload> { @Override public ProcessInstanceResult execute(StartMessagePayload command) { ProcessInstance result = processAdminRuntime.start(command); return new ProcessInstanceResult(command, result); } StartMessageCmdExecutor(ProcessAdminRuntime processAdminRuntime); @Override ProcessInstanceResult execute(StartMessagePayload command); }### Answer:
@Test public void signalProcessInstancesCmdExecutorTest() { StartMessagePayload payload = new StartMessagePayload("messageName", "businessKey", Collections.emptyMap()); assertThat(subject.getHandledType()).isEqualTo(StartMessagePayload.class.getName()); subject.execute(payload); verify(processAdminRuntime).start(payload); } |
### Question:
SignalCmdExecutor extends AbstractCommandExecutor<SignalPayload> { @Override public EmptyResult execute(SignalPayload signalPayload) { processAdminRuntime.signal(signalPayload); return new EmptyResult(signalPayload); } SignalCmdExecutor(ProcessAdminRuntime processAdminRuntime); @Override EmptyResult execute(SignalPayload signalPayload); }### Answer:
@Test public void signalProcessInstancesCmdExecutorTest() { SignalPayload signalPayload = new SignalPayload("x", null); assertThat(signalCmdExecutor.getHandledType()).isEqualTo(SignalPayload.class.getName()); signalCmdExecutor.execute(signalPayload); verify(processAdminRuntime).signal(signalPayload); } |
### Question:
ReleaseTaskCmdExecutor extends AbstractCommandExecutor<ReleaseTaskPayload> { public ReleaseTaskCmdExecutor(TaskAdminRuntime taskAdminRuntime) { this.taskAdminRuntime = taskAdminRuntime; } ReleaseTaskCmdExecutor(TaskAdminRuntime taskAdminRuntime); @Override TaskResult execute(ReleaseTaskPayload releaseTaskPayload); }### Answer:
@Test public void releaseTaskCmdExecutorTest() { ReleaseTaskPayload releaseTaskPayload = new ReleaseTaskPayload("taskId"); assertThat(releaseTaskCmdExecutor.getHandledType()).isEqualTo(ReleaseTaskPayload.class.getName()); releaseTaskCmdExecutor.execute(releaseTaskPayload); verify(taskAdminRuntime).release(releaseTaskPayload); } |
### Question:
BasicAuthenticationProvider implements AuthenticationProvider { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String name = authentication.getName(); String password = authentication.getCredentials().toString(); UserDetails userDetails = userDetailsService.loadUserByUsername(name); boolean authenticated = userDetails.getPassword().equals(password) && userDetails.isAccountNonExpired() && userDetails.isEnabled() && userDetails.isCredentialsNonExpired(); if (authenticated) { org.activiti.engine.impl.identity.Authentication.setAuthenticatedUserId(name); return new UsernamePasswordAuthenticationToken(name, password, userDetails.getAuthorities()); } else { throw new BadCredentialsException("Authentication failed for this username and password"); } } @Autowired BasicAuthenticationProvider(UserDetailsService userDetailsService); @Override Authentication authenticate(Authentication authentication); @Override boolean supports(Class<?> authentication); }### Answer:
@Test public void testAuthenticate() { Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("testrole")); User user = new User("test", "pass", authorities); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("test", "pass", authorities); when(userDetailsService.loadUserByUsername("test")) .thenReturn(user); assertThat(basicAuthenticationProvider.authenticate(authentication)).isNotNull(); }
@Test public void testAuthenticationFailure() { Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("testrole")); User user = new User("test", "pass", authorities); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("differentuser", "differentpass", authorities); when(userDetailsService.loadUserByUsername("differentuser")) .thenReturn(user); assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> basicAuthenticationProvider.authenticate(authentication)); } |
### Question:
BasicAuthenticationProvider implements AuthenticationProvider { @Override public boolean supports(Class<?> authentication) { return authentication.equals(UsernamePasswordAuthenticationToken.class); } @Autowired BasicAuthenticationProvider(UserDetailsService userDetailsService); @Override Authentication authenticate(Authentication authentication); @Override boolean supports(Class<?> authentication); }### Answer:
@Test public void testSupports() { assertThat(basicAuthenticationProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue(); assertThat(basicAuthenticationProvider.supports(Integer.class)).isFalse(); } |
### Question:
ToCandidateUserConverter { public List<CandidateUser> from (List<String> users){ List<CandidateUser> list = new ArrayList<>(); users.forEach(user -> list.add(new CandidateUser(user))); return list; } List<CandidateUser> from(List<String> users); }### Answer:
@Test public void shouldConvertStringUsersToCanidateUsers(){ String user = "user1"; List<String> userList = new ArrayList<>(); userList.add(user); List<CandidateUser> convertedUserList = toCandidateUserConverter.from(userList); assertThat(convertedUserList.get(0)).isInstanceOf(CandidateUser.class); assertThat(convertedUserList.get(0).getUser()).isEqualTo(user); } |
### Question:
TaskResourceAssembler implements ResourceAssembler<Task, Resource<CloudTask>> { @Override public Resource<CloudTask> toResource(Task task) { CloudTask cloudTask = converter.from(task); List<Link> links = new ArrayList<>(); links.add(linkTo(methodOn(TaskControllerImpl.class).getTaskById(cloudTask.getId())).withSelfRel()); if (ASSIGNED != cloudTask.getStatus()) { links.add(linkTo(methodOn(TaskControllerImpl.class).claimTask(cloudTask.getId())).withRel("claim")); } else { links.add(linkTo(methodOn(TaskControllerImpl.class).releaseTask(cloudTask.getId())).withRel("release")); links.add(linkTo(methodOn(TaskControllerImpl.class).completeTask(cloudTask.getId(), null)).withRel("complete")); } if (cloudTask.getProcessInstanceId() != null && !cloudTask.getProcessInstanceId().isEmpty()) { links.add(linkTo(methodOn(ProcessInstanceControllerImpl.class).getProcessInstanceById(cloudTask.getProcessInstanceId())).withRel("processInstance")); } if (cloudTask.getParentTaskId() != null && !cloudTask.getParentTaskId().isEmpty()) { links.add(linkTo(methodOn(TaskControllerImpl.class).getTaskById(cloudTask.getParentTaskId())).withRel("parent")); } links.add(linkTo(HomeControllerImpl.class).withRel("home")); return new Resource<>(cloudTask, links); } TaskResourceAssembler(ToCloudTaskConverter converter); @Override Resource<CloudTask> toResource(Task task); }### Answer:
@Test public void toResourceShouldReturnResourceWithSelfLinkContainingResourceId() { Task model = new TaskImpl("my-identifier", "myTask", CREATED); given(converter.from(model)).willReturn(new CloudTaskImpl(model)); Resource<CloudTask> resource = resourceAssembler.toResource(model); Link selfResourceLink = resource.getLink("self"); assertThat(selfResourceLink).isNotNull(); assertThat(selfResourceLink.getHref()).contains("my-identifier"); }
@Test public void toResourceShouldReturnResourceWithReleaseAndCompleteLinksWhenStatusIsAssigned() { Task model = new TaskImpl("my-identifier", "myTask", CREATED); given(converter.from(model)).willReturn(new CloudTaskImpl(model)); Resource<CloudTask> resource = resourceAssembler.toResource(model); assertThat(resource.getLink("claim")).isNotNull(); assertThat(resource.getLink("release")).isNull(); assertThat(resource.getLink("complete")).isNull(); }
@Test public void toResourceShouldReturnResourceWithClaimLinkWhenStatusIsNotAssigned() { Task model = new TaskImpl("my-identifier", "myTask", ASSIGNED); given(converter.from(model)).willReturn(new CloudTaskImpl(model)); Resource<CloudTask> resource = resourceAssembler.toResource(model); assertThat(resource.getLink("claim")).isNull(); assertThat(resource.getLink("release")).isNotNull(); assertThat(resource.getLink("complete")).isNotNull(); }
@Test public void toResourceShouldNotReturnResourceWithProcessInstanceLinkWhenNewTaskIsCreated() { Task model = new TaskImpl("my-identifier", "myTask", CREATED); given(converter.from(model)).willReturn(new CloudTaskImpl(model)); Resource<CloudTask> resource = resourceAssembler.toResource(model); assertThat(resource.getLink("processInstance")).isNull(); }
@Test public void toResourceShouldReturnResourceWithProcessInstanceLinkForProcessInstanceTask() { Task model = new TaskImpl("my-identifier", "myTask", CREATED); ((TaskImpl) model).setProcessInstanceId("processInstanceId"); given(converter.from(model)).willReturn(new CloudTaskImpl(model)); Resource<CloudTask> resource = resourceAssembler.toResource(model); assertThat(resource.getLink("processInstance")).isNotNull(); } |
### Question:
CloudProcessDeployedProducer { @EventListener public void sendProcessDeployedEvents(ProcessDeployedEvents processDeployedEvents) { producer.auditProducer().send( runtimeBundleMessageBuilderFactory.create() .withPayload( processDeployedEvents.getProcessDeployedEvents() .stream() .map(processDeployedEvent -> { CloudProcessDeployedEventImpl cloudProcessDeployedEvent = new CloudProcessDeployedEventImpl(processDeployedEvent.getEntity()); cloudProcessDeployedEvent.setProcessModelContent(processDeployedEvent.getProcessModelContent()); runtimeBundleInfoAppender.appendRuntimeBundleInfoTo(cloudProcessDeployedEvent); return cloudProcessDeployedEvent; }) .toArray(CloudRuntimeEvent<?, ?>[]::new)) .build()); } CloudProcessDeployedProducer(RuntimeBundleInfoAppender runtimeBundleInfoAppender,
ProcessEngineChannels producer,
RuntimeBundleMessageBuilderFactory runtimeBundleMessageBuilderFactory); @EventListener void sendProcessDeployedEvents(ProcessDeployedEvents processDeployedEvents); }### Answer:
@Test public void shouldSendMessageWithDeployedProcessesWhenWebApplicationTypeIsServlet() { ProcessDefinition def1 = mock(ProcessDefinition.class); ProcessDefinition def2 = mock(ProcessDefinition.class); List<ProcessDeployedEvent> processDeployedEventList = Arrays.asList(new ProcessDeployedEventImpl(def1, "content1"), new ProcessDeployedEventImpl(def2, "content2")); given(messageBuilderAppenderChain.withPayload(ArgumentMatchers.<CloudRuntimeEvent<?, ?>[]>any())).willReturn(MessageBuilder.withPayload(new CloudRuntimeEvent<?, ?>[2])); processDeployedProducer.sendProcessDeployedEvents(new ProcessDeployedEvents(processDeployedEventList)); verify(runtimeBundleInfoAppender, times(2)).appendRuntimeBundleInfoTo(any(CloudRuntimeEventImpl.class)); verify(auditProducer).send(any()); verify(messageBuilderAppenderChain).withPayload(messagePayloadCaptor.capture()); List<CloudProcessDeployedEvent> cloudProcessDeployedEvents = Arrays.stream(messagePayloadCaptor.getValue()) .map(CloudProcessDeployedEvent.class::cast) .collect(Collectors.toList()); assertThat(cloudProcessDeployedEvents) .extracting(CloudProcessDeployedEvent::getEntity, CloudProcessDeployedEvent::getProcessModelContent) .containsOnly(tuple(def1, "content1"), tuple(def2, "content2")); } |
### Question:
ToCandidateGroupConverter { public List<CandidateGroup> from (List<String> users){ List<CandidateGroup> list = new ArrayList<>(); users.forEach(user -> list.add(new CandidateGroup(user))); return list; } List<CandidateGroup> from(List<String> users); }### Answer:
@Test public void shouldConvertStringGroupsToCanidateGroups(){ String group = "group1"; List<String> groupList = new ArrayList<>(); groupList.add(group); List<CandidateGroup> convertedGroupList = toCandidateGroupConverter.from(groupList); assertThat(convertedGroupList.get(0)).isInstanceOf(CandidateGroup.class); assertThat(convertedGroupList.get(0).getGroup()).isEqualTo(group); } |
### Question:
ProcessInstanceResourceAssembler implements ResourceAssembler<ProcessInstance, Resource<CloudProcessInstance>> { @Override public Resource<CloudProcessInstance> toResource(ProcessInstance processInstance) { CloudProcessInstance cloudProcessInstance = toCloudProcessInstanceConverter.from(processInstance); Link processInstancesRel = linkTo(methodOn(ProcessInstanceControllerImpl.class).getProcessInstances(null)) .withRel("processInstances"); Link selfLink = linkTo(methodOn(ProcessInstanceControllerImpl.class).getProcessInstanceById(cloudProcessInstance.getId())).withSelfRel(); Link variablesLink = linkTo(methodOn(ProcessInstanceVariableControllerImpl.class).getVariables(cloudProcessInstance.getId())).withRel("variables"); Link homeLink = linkTo(HomeControllerImpl.class).withRel("home"); return new Resource<>(cloudProcessInstance, selfLink, variablesLink, processInstancesRel, homeLink); } ProcessInstanceResourceAssembler(ToCloudProcessInstanceConverter toCloudProcessInstanceConverter); @Override Resource<CloudProcessInstance> toResource(ProcessInstance processInstance); }### Answer:
@Test public void toResourceShouldReturnResourceWithSelfLinkContainingResourceId() { CloudProcessInstance cloudModel = mock(CloudProcessInstance.class); given(cloudModel.getId()).willReturn("my-identifier"); ProcessInstance model = mock(ProcessInstance.class); given(toCloudProcessInstanceConverter.from(model)).willReturn(cloudModel); Resource<CloudProcessInstance> resource = resourceAssembler.toResource(model); Link selfResourceLink = resource.getLink("self"); assertThat(selfResourceLink).isNotNull(); assertThat(selfResourceLink.getHref()).contains("my-identifier"); } |
### Question:
ProcessDefinitionResourceAssembler implements ResourceAssembler<ProcessDefinition, Resource<CloudProcessDefinition>> { @Override public Resource<CloudProcessDefinition> toResource(ProcessDefinition processDefinition) { CloudProcessDefinition cloudProcessDefinition = converter.from(processDefinition); Link selfRel = linkTo(methodOn(ProcessDefinitionControllerImpl.class).getProcessDefinition(cloudProcessDefinition.getId())).withSelfRel(); Link startProcessLink = linkTo(methodOn(ProcessInstanceControllerImpl.class).startProcess(null)).withRel("startProcess"); Link homeLink = linkTo(HomeControllerImpl.class).withRel("home"); return new Resource<>(cloudProcessDefinition, selfRel, startProcessLink, homeLink); } ProcessDefinitionResourceAssembler(ToCloudProcessDefinitionConverter converter); @Override Resource<CloudProcessDefinition> toResource(ProcessDefinition processDefinition); }### Answer:
@Test public void toResourceShouldReturnResourceWithSelfLinkContainingResourceId() { ProcessDefinitionImpl processDefinition = new ProcessDefinitionImpl(); processDefinition.setId("my-identifier"); given(converter.from(processDefinition)).willReturn(new CloudProcessDefinitionImpl(processDefinition)); Resource<CloudProcessDefinition> processDefinitionResource = resourceAssembler.toResource(processDefinition); Link selfResourceLink = processDefinitionResource.getLink("self"); assertThat(selfResourceLink).isNotNull(); assertThat(selfResourceLink.getHref()).contains("my-identifier"); } |
### Question:
ProcessDefinitionMetaResourceAssembler implements ResourceAssembler<ProcessDefinitionMeta, Resource<ProcessDefinitionMeta>> { @Override public Resource<ProcessDefinitionMeta> toResource(ProcessDefinitionMeta processDefinitionMeta) { Link metadata = linkTo(methodOn(ProcessDefinitionMetaControllerImpl.class).getProcessDefinitionMetadata(processDefinitionMeta.getId())).withRel("meta"); Link selfRel = linkTo(methodOn(ProcessDefinitionControllerImpl.class).getProcessDefinition(processDefinitionMeta.getId())).withSelfRel(); Link startProcessLink = linkTo(methodOn(ProcessInstanceControllerImpl.class).startProcess(null)).withRel("startProcess"); Link homeLink = linkTo(HomeControllerImpl.class).withRel("home"); return new Resource<>(processDefinitionMeta, metadata, selfRel, startProcessLink, homeLink); } @Override Resource<ProcessDefinitionMeta> toResource(ProcessDefinitionMeta processDefinitionMeta); }### Answer:
@Test public void toResourceShouldReturnResourceWithSelfLinkContainingResourceId() { ProcessDefinitionMeta model = mock(ProcessDefinitionMeta.class); when(model.getId()).thenReturn("my-identifier"); Resource<ProcessDefinitionMeta> resource = resourceAssembler.toResource(model); Link selfResourceLink = resource.getLink("self"); assertThat(selfResourceLink).isNotNull(); assertThat(selfResourceLink.getHref()).contains("my-identifier"); Link metaResourceLink = resource.getLink("meta"); assertThat(metaResourceLink).isNotNull(); assertThat(metaResourceLink.getHref()).contains("my-identifier"); } |
### Question:
ProcessEngineEventsAggregator extends BaseCommandContextEventsAggregator<CloudRuntimeEvent<?,?>, MessageProducerCommandContextCloseListener> { @Override protected Class<MessageProducerCommandContextCloseListener> getCloseListenerClass() { return MessageProducerCommandContextCloseListener.class; } ProcessEngineEventsAggregator(MessageProducerCommandContextCloseListener closeListener); @Override void add(CloudRuntimeEvent<?, ?> element); }### Answer:
@Test public void getCloseListenerClassShouldReturnMessageProducerCommandContextCloseListenerClass() { Class<MessageProducerCommandContextCloseListener> listenerClass = eventsAggregator.getCloseListenerClass(); assertThat(listenerClass).isEqualTo(MessageProducerCommandContextCloseListener.class); } |
### Question:
ProcessEngineEventsAggregator extends BaseCommandContextEventsAggregator<CloudRuntimeEvent<?,?>, MessageProducerCommandContextCloseListener> { @Override protected MessageProducerCommandContextCloseListener getCloseListener() { return closeListener; } ProcessEngineEventsAggregator(MessageProducerCommandContextCloseListener closeListener); @Override void add(CloudRuntimeEvent<?, ?> element); }### Answer:
@Test public void getCloseListenerShouldReturnTheCloserListenerPassedInTheConstructor() { MessageProducerCommandContextCloseListener retrievedCloseListener = eventsAggregator.getCloseListener(); assertThat(retrievedCloseListener).isEqualTo(closeListener); } |
### Question:
ProcessEngineEventsAggregator extends BaseCommandContextEventsAggregator<CloudRuntimeEvent<?,?>, MessageProducerCommandContextCloseListener> { @Override protected String getAttributeKey() { return MessageProducerCommandContextCloseListener.PROCESS_ENGINE_EVENTS; } ProcessEngineEventsAggregator(MessageProducerCommandContextCloseListener closeListener); @Override void add(CloudRuntimeEvent<?, ?> element); }### Answer:
@Test public void getAttributeKeyShouldReturnProcessEngineEvents() { String attributeKey = eventsAggregator.getAttributeKey(); assertThat(attributeKey).isEqualTo(MessageProducerCommandContextCloseListener.PROCESS_ENGINE_EVENTS); } |
### Question:
Score { public static void main(String[] args) throws IOException { if (args.length != 2) { System.out.println("Usage java " + Score.class.getName() + " <FILENAME>.csv <SCORE.csv>"); return; } final String csvFileName = args[0]; File csvFile = new File(csvFileName); if (!csvFile.exists()) { System.err.println("File " + csvFileName + " was not found"); return; } final String csvScoreFileName = args[1]; File csvScoreFile = new File(csvScoreFileName); if (csvScoreFile.exists()) { log("Deleting existing " + csvScoreFileName); csvScoreFile.delete(); } Map<ToolBudgetKey, Double> scoreMap = computeScore(csvFile); PrintStream writer = new PrintStream(csvScoreFile); log("Writing results to new file " + csvScoreFileName); printScore(writer, scoreMap); } static void log(String msg); static void main(String[] args); static Map<ToolBudgetKey, Double> aggregateScorePerTool(
Map<ToolBudgetBenchmarkKey, Double> scorePerBenchmark); }### Answer:
@Test public void testOutputFile() throws FileNotFoundException, IOException { final String csvFileName = System.getProperty("user.dir") + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + BLANK_LINE_CSV; final String outFileName = System.getProperty("user.dir") + File.separator + "out.csv"; File csvFile = new File(csvFileName); Assume.assumeTrue(csvFile.exists()); File outFile = new File(outFileName); try { if (outFile.exists()) { outFile.delete(); } Score.main(new String[] { csvFileName, outFileName }); assertTrue(outFile.exists()); } finally { outFile.delete(); } } |
### Question:
CheckerMain extends AbstractMojo implements PluginBase { void setExcludes(final String[] excludes) { this.excludes = excludes; } @Override void execute(); @Override PrettyPrintValidationResults.PluginLogger getPluginLogger(); @Override List<String> getExcludeList(); @Override List<String> getSearchPathList(); @Override String[] getValidatorPackages(); @Override String[] getValidatorClasses(); void loadProjectclasspath(); }### Answer:
@Test void shouldSkipFileIfItsExcluded() { final String ignoredFilename = "empty-as-well.dmn"; testee.setExcludes(new String[] { ignoredFilename }); final List<File> filesToTest = testee.fetchFilesToTestFromSearchPaths(Collections.singletonList(Paths.get(""))); Assertions.assertTrue(filesToTest.stream().noneMatch(file -> file.getName().equals(ignoredFilename))); } |
### Question:
FeelExpression { public boolean containsVariable(final String name) { return FeelExpressions.caseOf(this) .Empty_(false) .Null_(false) .BooleanLiteral_(false) .DateLiteral_(false) .DoubleLiteral_(false) .IntegerLiteral_(false) .StringLiteral_(false) .VariableLiteral(variableName -> variableName.equals(name)) .RangeExpression((__, lowerBound, upperBound, ___) -> lowerBound.containsVariable(name) || upperBound.containsVariable(name)) .UnaryExpression((__, expression) -> expression.containsVariable(name)) .BinaryExpression((left, __, right) -> left.containsVariable(name) || right.containsVariable(name)) .DisjunctionExpression((head, tail) -> head.containsVariable(name) || tail.containsVariable(name)); } abstract R match(Cases<R> cases); Optional<Boolean> subsumes(final FeelExpression expression); boolean containsVariable(final String name); boolean isLiteral(); boolean containsNot(); @Override abstract int hashCode(); @Override abstract boolean equals(@Nullable Object obj); @Override abstract String toString(); }### Answer:
@Test void variableThatDoesNotContainVariable() { assertFalse(FeelExpressions.VariableLiteral("y").containsVariable("x")); }
@Test void rangeContainsVariable() { assertTrue(FeelExpressions.RangeExpression(true, FeelExpressions.VariableLiteral("x"), FeelExpressions.Empty(), false) .containsVariable("x")); }
@Test void rangeDoesNotContainVariable() { assertFalse(FeelExpressions.RangeExpression(true, FeelExpressions.VariableLiteral("y"), FeelExpressions.Empty(), false) .containsVariable("x")); }
@Test void unaryContainsVariable() { assertTrue(FeelExpressions.UnaryExpression(Operator.GT, FeelExpressions.VariableLiteral("x")).containsVariable("x")); }
@Test void unaryDoesNotContainVariable() { assertFalse(FeelExpressions.UnaryExpression(Operator.GT, FeelExpressions.VariableLiteral("y")).containsVariable("x")); }
@Test void binaryContainsVariable() { assertTrue(FeelExpressions.BinaryExpression(FeelExpressions.Empty(), Operator.GT, FeelExpressions.VariableLiteral("x")).containsVariable("x")); }
@Test void binaryDosNotContainVariable() { assertFalse(FeelExpressions.BinaryExpression(FeelExpressions.Empty(), Operator.GT, FeelExpressions.VariableLiteral("y")).containsVariable("x")); }
@Test void disjunctionContainsVariableInTail() { assertTrue(FeelExpressions.DisjunctionExpression(FeelExpressions.Empty(), FeelExpressions.VariableLiteral("x")).containsVariable("x")); }
@Test void disjunctionContainsVariableInHead() { assertTrue(FeelExpressions.DisjunctionExpression(FeelExpressions.VariableLiteral("x"), FeelExpressions.Empty()).containsVariable("x")); }
@Test void disjunctionDosNotContainVariableInTail() { assertFalse(FeelExpressions.DisjunctionExpression(FeelExpressions.Empty(), FeelExpressions.VariableLiteral("y")).containsVariable("x")); }
@Test void disjunctionDoesNotContainVariableInHead() { assertFalse(FeelExpressions.DisjunctionExpression(FeelExpressions.VariableLiteral("y"), FeelExpressions.Empty()).containsVariable("x")); }
@Test void emptyNeverContainsVariable() { assertFalse(FeelExpressions.Empty().containsVariable("x")); }
@Test void boolNeverContainsVariable() { assertFalse(FeelExpressions.BooleanLiteral(true).containsVariable("x")); }
@Test void dateNeverContainsVariable() { assertFalse(FeelExpressions.DateLiteral(LocalDateTime.MIN).containsVariable("x")); }
@Test void doubleNeverContainsVariable() { assertFalse(FeelExpressions.DoubleLiteral(0.0).containsVariable("x")); }
@Test void intNeverContainsVariable() { assertFalse(FeelExpressions.IntegerLiteral(1).containsVariable("x")); }
@Test void stringNeverContainsVariable() { assertFalse(FeelExpressions.StringLiteral("foobar").containsVariable("x")); }
@Test void variableThatContainsVariable() { assertTrue(FeelExpressions.VariableLiteral("x").containsVariable("x")); } |
### Question:
CheckerMain extends AbstractMojo implements PluginBase { void setSearchPaths(final String[] searchPaths) { this.searchPaths = searchPaths; } @Override void execute(); @Override PrettyPrintValidationResults.PluginLogger getPluginLogger(); @Override List<String> getExcludeList(); @Override List<String> getSearchPathList(); @Override String[] getValidatorPackages(); @Override String[] getValidatorClasses(); void loadProjectclasspath(); }### Answer:
@Test void shouldDetectIfFileIsOnSearchPath() { testee.setSearchPaths(new String[] {"src/"}); final MojoExecutionException assertionError = Assertions.assertThrows(MojoExecutionException.class, testee::execute); Assertions.assertTrue(assertionError.getMessage().contains("Some files are not valid, see previous logs.")); }
@Test void shouldDetectIfFileIsOnSearchPathWithMultiplePaths() { testee.setSearchPaths(new String[] {"src/main/java","src/"}); final MojoExecutionException assertionError = Assertions.assertThrows(MojoExecutionException.class, testee::execute); Assertions.assertTrue(assertionError.getMessage().contains("Some files are not valid, see previous logs.")); } |
### Question:
Subsumption { static Optional<Boolean> subsumes(final FeelExpression expression, final FeelExpression otherExpression, final Comparison comparison) { return FeelExpressions.caseOf(expression) .Empty_(Optional.of(true)) .Null_(FeelExpressions.caseOf(otherExpression).Null_(Optional.of(true)).otherwise_(Optional.of(false))) .BooleanLiteral((aBool) -> compareLiterals(aBool, FeelExpressions::getABoolean, otherExpression, comparison)) .DateLiteral((dateTime) -> compareLiterals(dateTime, FeelExpressions::getDateTime, otherExpression, comparison)) .DoubleLiteral((aDouble) -> compareLiterals(aDouble, FeelExpressions::getADouble, otherExpression, comparison)) .IntegerLiteral((integer) -> compareLiterals(integer, FeelExpressions::getAInteger, otherExpression, comparison)) .StringLiteral((string) -> compareLiterals(string, FeelExpressions::getString, otherExpression, eq)) .VariableLiteral((name) -> subsumesVariableLiteral(name, otherExpression, comparison)) .RangeExpression((leftInc, lowerBound, upperBound, rightInc) -> subsumesRangeExpression(leftInc, lowerBound, upperBound, rightInc, otherExpression)) .UnaryExpression((operator, operand) -> subsumesUnaryExpression(operator, operand, otherExpression)) .otherwise_(Optional.empty()); } }### Answer:
@Test void emptySubsumesEmpty() { final FeelExpression emptyExpression = FeelExpressions.Empty(); assertEquals(Optional.of(true), Subsumption.subsumes(emptyExpression, emptyExpression, Subsumption.eq)); }
@Test void nullSubsumesNull() { final FeelExpression nullExpression = FeelExpressions.Null(); assertEquals(Optional.of(true), Subsumption.subsumes(nullExpression, nullExpression, Subsumption.eq)); }
@Test void identicalStringsSubsumeEachOther() { final FeelExpression stringExpression = FeelParser.PARSER.parse("\"somestring\""); assertEquals(Optional.of(true), Subsumption.subsumes(stringExpression, stringExpression, Subsumption.eq)); }
@Test void differentStringsDoNotSubsumeEachOther() { final FeelExpression stringExpression = FeelParser.PARSER.parse("\"somestring\""); final FeelExpression otherStringExpression = FeelParser.PARSER.parse("\"otherstring\""); assertEquals(Optional.of(false), Subsumption.subsumes(stringExpression, otherStringExpression, Subsumption.eq)); } |
### Question:
RequirementGraph extends DirectedAcyclicGraph<DrgElement, DefaultEdge> { public static RequirementGraph from(final DmnModelInstance dmnModelInstance) throws IllegalArgumentException { final Collection<Decision> decisions = dmnModelInstance.getModelElementsByType(Decision.class); final Collection<KnowledgeSource> knowledgeSources = dmnModelInstance.getModelElementsByType(KnowledgeSource.class); final Collection<InputData> inputData = dmnModelInstance.getModelElementsByType(InputData.class); final RequirementGraph drg = new RequirementGraph(DefaultEdge.class, dmnModelInstance.getDefinitions()); Stream.of(decisions, knowledgeSources, inputData).flatMap(Collection::stream).forEach(drg::addVertex); for (Decision decision : decisions) { decision.getInformationRequirements().stream() .flatMap(RequirementGraph::collectDrgElements) .forEach(drgElement -> drg.addEdge(drgElement, decision)); decision.getAuthorityRequirements().stream() .flatMap(RequirementGraph::collectDrgElements) .forEach(drgElement -> drg.addEdge(drgElement, decision)); } for (KnowledgeSource knowledgeSource : knowledgeSources) { knowledgeSource.getAuthorityRequirement().stream() .flatMap(RequirementGraph::collectDrgElements) .forEach(drgElement -> drg.addEdge(drgElement, knowledgeSource)); } return drg; } RequirementGraph(Class<? extends DefaultEdge> edgeClass, Definitions definitions); Definitions getDefinitions(); static RequirementGraph from(final DmnModelInstance dmnModelInstance); }### Answer:
@Test void emptyGraphFromEmptyModel() { final DmnModelInstance emptyModel = Dmn.createEmptyModel(); final RequirementGraph requirementGraph = RequirementGraph.from(emptyModel); assertTrue(requirementGraph.vertexSet().isEmpty()); assertTrue(requirementGraph.edgeSet().isEmpty()); } |
### Question:
AggregateTrustManager implements X509TrustManager { public static void initialize(KeyStore... keyStores) throws Exception { TrustManager[] trustManagers = new TrustManager[] { new AggregateTrustManager(keyStores) }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustManagers, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } private AggregateTrustManager(KeyStore... keyStores); static void initialize(KeyStore... keyStores); @Override void checkClientTrusted(X509Certificate[] chain, String authType); @Override void checkServerTrusted(X509Certificate[] chain, String authType); @Override X509Certificate[] getAcceptedIssuers(); }### Answer:
@Test public void testWithDefault_usingBothCacertsAndRioKeyStore() throws Exception { AggregateTrustManager.initialize(keyStore); URL locationURL = new URL("https: URLConnection urlConnection = locationURL.openConnection(); urlConnection.connect(); }
@Test(expected= SSLHandshakeException.class) public void testWithJustRioKeystore_shouldFail() throws Exception { System.setProperty("javax.net.ssl.trustStore", keyStoreFile.getPath()); AggregateTrustManager.initialize(keyStore); URL locationURL = new URL("https: URLConnection urlConnection = locationURL.openConnection(); urlConnection.connect(); } |
### Question:
IdleServiceManager { public IdleServiceManager(final Long maxIdleTime, final ServiceElement serviceElement) { this.maxIdleTime = maxIdleTime; this.serviceElement = serviceElement; long delay = TimeUtil.computeLeaseRenewalTime(maxIdleTime); if(logger.isDebugEnabled()) { logger.debug("Service [{}] idle time: {}, computed delay time for checking idle status: {}.", LoggingUtil.getLoggingName(serviceElement), TimeUtil.format(maxIdleTime), TimeUtil.format(delay)); } scheduledExecutorService.scheduleWithFixedDelay(new IdleChecker(delay), delay, delay, TimeUnit.MILLISECONDS); } IdleServiceManager(final Long maxIdleTime, final ServiceElement serviceElement); void addService(final ServiceActivityProvider service); void removeService(final ServiceActivityProvider service); void terminate(); }### Answer:
@Test public void testIdleServiceManager() throws InterruptedException { ServiceElement serviceElement = TestUtil.makeServiceElement("bar", "foo", 2); IdleServiceManager idleServiceManager = new IdleServiceManager(3000L, serviceElement); TestServiceActivityProvider sap1 = new TestServiceActivityProvider(); TestServiceActivityProvider sap2 = new TestServiceActivityProvider(); idleServiceManager.addService(sap1); Listener l = new Listener(); ServiceChannel.getInstance().subscribe(l, serviceElement, ServiceChannelEvent.Type.IDLE); Thread.sleep(1000); idleServiceManager.addService(sap2); sap1.active = false; Thread.sleep(1000); sap2.active = false; int i = 0; long t0 = System.currentTimeMillis(); while(l.notified==0 && i<10) { Thread.sleep(500); i++; } System.out.println("Waited "+(System.currentTimeMillis()-t0)+" millis"); Assert.assertTrue(l.notified == 1); } |
### Question:
ServiceChannel { public void subscribe(final ServiceChannelListener listener, final AssociationDescriptor associationDescriptor, final ServiceChannelEvent.Type type) { subscribe(listener, associationDescriptor.getName(), associationDescriptor.getInterfaceNames(), associationDescriptor.getOperationalStringName(), type); } static ServiceChannel getInstance(); void subscribe(final ServiceChannelListener listener,
final AssociationDescriptor associationDescriptor,
final ServiceChannelEvent.Type type); void subscribe(final ServiceChannelListener listener,
final ServiceElement serviceElement,
final ServiceChannelEvent.Type type); void unsubscribe(final ServiceChannelListener listener); void broadcast(final ServiceChannelEvent event); }### Answer:
@Test public void testSubscribe() { ServiceChannel serviceChannel = ServiceChannel.getInstance(); ServiceElement serviceElement = TestUtil.makeServiceElement("bar", "foo"); Listener l1 = new Listener(); serviceChannel.subscribe(l1, serviceElement, ServiceChannelEvent.Type.PROVISIONED); Listener l2 = new Listener(); serviceChannel.subscribe(l2, serviceElement, ServiceChannelEvent.Type.FAILED); Listener l3 = new Listener(); serviceChannel.subscribe(l3, serviceElement, ServiceChannelEvent.Type.IDLE); serviceChannel.broadcast(new ServiceChannelEvent(new Object(), serviceElement, ServiceChannelEvent.Type.PROVISIONED)); Assert.assertTrue(l1.notified); Assert.assertFalse(l2.notified); Assert.assertFalse(l3.notified); l1.notified = false; serviceChannel.broadcast(new ServiceChannelEvent(new Object(), serviceElement, ServiceChannelEvent.Type.FAILED)); Assert.assertFalse(l1.notified); Assert.assertTrue(l2.notified); Assert.assertFalse(l3.notified); l2.notified = false; serviceChannel.broadcast(new ServiceChannelEvent(new Object(), serviceElement, ServiceChannelEvent.Type.IDLE)); Assert.assertFalse(l1.notified); Assert.assertFalse(l2.notified); Assert.assertTrue(l3.notified); l3.notified = false; } |
### Question:
DeploymentVerifier { RemoteRepository[] mergeRepositories(final RemoteRepository[] r1, final RemoteRepository[] r2) { Set<RemoteRepository> remoteRepositories = new HashSet<>(); Collections.addAll(remoteRepositories, r1); Collections.addAll(remoteRepositories, r2); return remoteRepositories.toArray(new RemoteRepository[0]); } DeploymentVerifier(final Configuration config, final DiscoveryManagement discoveryManagement); void verifyDeploymentRequest(final DeployRequest request); void verifyOperationalString(final OperationalString opString, final RemoteRepository[] repositories); void verifyOperationalStringService(final ServiceElement service,
final Resolver resolver,
final RemoteRepository[] repositories); }### Answer:
@Test public void testMergeRepositories() throws Exception { RemoteRepository[] r1 = new RemoteRepository[]{createRR("http: createRR("http: RemoteRepository[] r2 = new RemoteRepository[]{createRR("http: createRR("http: RemoteRepository[] repositories = deploymentVerifier.mergeRepositories(r1, r2); Assert.assertTrue(repositories.length==3); } |
### Question:
DeploymentVerifier { void ensureGroups(final ServiceElement serviceElement) throws IOException { if (serviceElement.getServiceBeanConfig().getGroups()==DiscoveryGroupManagement.ALL_GROUPS) { throw new IOException(String.format("Service %s has been declared for ALL_GROUPS", serviceElement.getName())); } for(ServiceRegistrar registrar : discoveryManagement.getRegistrars()) { try { List<String> toAdd = new ArrayList<>(); DiscoveryAdmin admin = (DiscoveryAdmin) ((Administrable)registrar).getAdmin(); String[] knownGroups = admin.getMemberGroups(); for(String serviceGroup : serviceElement.getServiceBeanConfig().getGroups()) { boolean found = false; for(String known : knownGroups) { if (serviceGroup.equals(known)) { found = true; break; } } if (!found) { toAdd.add(serviceGroup); } } if (!toAdd.isEmpty()) { admin.addMemberGroups(toAdd.toArray(new String[0])); if (logger.isDebugEnabled()) { logger.debug("Added {} to ServiceRegistrar at {}:{}", toAdd, registrar.getLocator().getHost(), registrar.getLocator().getPort()); } } } catch (RemoteException e) { logger.warn("While trying to ensure groups", e); } } } DeploymentVerifier(final Configuration config, final DiscoveryManagement discoveryManagement); void verifyDeploymentRequest(final DeployRequest request); void verifyOperationalString(final OperationalString opString, final RemoteRepository[] repositories); void verifyOperationalStringService(final ServiceElement service,
final Resolver resolver,
final RemoteRepository[] repositories); }### Answer:
@Test public void testEnsureGroups() throws Exception { startLookup("foo"); Assert.assertFalse(hasGroup(registrar, "gack")); ServiceElement service = createSE("gack"); Assert.assertTrue(waitForDiscovery(listener)); Assert.assertTrue(listener.discovered.get()); DL newDiscoListener = new DL(); new LookupDiscoveryManager(new String[]{"gack"}, null, newDiscoListener); deploymentVerifier.ensureGroups(service); Assert.assertTrue(waitForDiscovery(newDiscoListener)); Assert.assertTrue(hasGroup(registrar, "gack")); }
@Test public void testEnsureMultiGroups() throws Exception { startLookup("foo"); Assert.assertTrue(waitForDiscovery(listener)); Assert.assertFalse(hasGroup(registrar, "gack")); Assert.assertFalse(hasGroup(registrar, "blutarsky")); ServiceElement service = createSE("gack", "blutarsky"); Assert.assertTrue(listener.discovered.get()); DL newDiscoListener = new DL(); new LookupDiscoveryManager(new String[]{"gack"}, null, newDiscoListener); deploymentVerifier.ensureGroups(service); Assert.assertTrue(waitForDiscovery(newDiscoListener)); Assert.assertTrue(hasGroup(registrar, "gack")); Assert.assertTrue(hasGroup(registrar, "blutarsky")); }
@Test(expected = IOException.class) public void testAllGroupsFail() throws Exception { ServiceElement service = new ServiceElement(); ServiceBeanConfig serviceBeanConfig = new ServiceBeanConfig(); serviceBeanConfig.setGroups("all"); service.setServiceBeanConfig(serviceBeanConfig); deploymentVerifier.ensureGroups(service); } |
### Question:
TransientServiceStatementManager implements ServiceStatementManager { public void terminate() { statementMap.clear(); } TransientServiceStatementManager(Configuration config); void terminate(); ServiceStatement[] get(); ServiceStatement get(ServiceElement sElem); void record(ServiceStatement statement); }### Answer:
@Test public void testTerminate() throws Exception { serviceStatementManager.terminate(); Assert.assertTrue(serviceStatementManager.get().length==0); } |
### Question:
TransientServiceStatementManager implements ServiceStatementManager { public ServiceStatement[] get() { ServiceStatement[] statements; synchronized (statementMap) { statements = statementMap.values().toArray(new ServiceStatement[statementMap.values().size()]); } return statements; } TransientServiceStatementManager(Configuration config); void terminate(); ServiceStatement[] get(); ServiceStatement get(ServiceElement sElem); void record(ServiceStatement statement); }### Answer:
@Test public void testGetActiveServiceStatements() throws Exception { ServiceStatement[] statements = serviceStatementManager.get(); List<ServiceRecord> list = new ArrayList<ServiceRecord>(); for (ServiceStatement statement : statements) { ServiceRecord[] records = statement.getServiceRecords(recordingUuid, ServiceRecord.ACTIVE_SERVICE_RECORD); list.addAll(Arrays.asList(records)); } Assert.assertEquals(names.length, list.size()); }
@Test public void testRecordAndRetrieve() throws Exception { Assert.assertEquals(statements.size(), serviceStatementManager.get().length); for(ServiceStatement statement : statements) { ServiceStatement s = serviceStatementManager.get(statement.getServiceElement()); Assert.assertEquals(statement, s); Assert.assertEquals(1, s.getServiceRecords(ServiceRecord.ACTIVE_SERVICE_RECORD).length); Assert.assertEquals(0, s.getServiceRecords(ServiceRecord.INACTIVE_SERVICE_RECORD).length); } } |
### Question:
SettingsUtil { public static String getLocalRepositoryLocation(final Settings settings) { if(settings==null) throw new IllegalArgumentException("settings must not be null"); String localRepositoryLocation = settings.getLocalRepository(); if (localRepositoryLocation == null) { StringBuilder locationBuilder = new StringBuilder(); locationBuilder.append(System.getProperty("user.home")).append(File.separator); locationBuilder.append(".m2").append(File.separator); locationBuilder.append("repository"); localRepositoryLocation = locationBuilder.toString(); } return localRepositoryLocation; } private SettingsUtil(); static Settings getSettings(); static String getLocalRepositoryLocation(final Settings settings); }### Answer:
@Test public void testGetLocalRepositoryLocation() throws Exception { Settings settings = SettingsUtil.getSettings(); String localRepositoryLocation = SettingsUtil.getLocalRepositoryLocation(settings); Assert.assertNotNull(localRepositoryLocation); } |
### Question:
LocalRepositoryWorkspaceReader implements WorkspaceReader { public LocalRepositoryWorkspaceReader() throws SettingsBuildingException { localRepositoryDir = SettingsUtil.getLocalRepositoryLocation(SettingsUtil.getSettings()); } LocalRepositoryWorkspaceReader(); WorkspaceRepository getRepository(); File findArtifact(Artifact artifact); List<String> findVersions(Artifact artifact); }### Answer:
@Test public void testLocalRepositoryWorkspaceReader() throws SettingsBuildingException { LocalRepositoryWorkspaceReader workspaceReader = new LocalRepositoryWorkspaceReader(); Artifact a = new DefaultArtifact("something.something:darkside-deathstar:pom:2.1"); String path = workspaceReader.getArtifactPath(a); System.out.println(path); assertEquals(getArtifactPath(a, workspaceReader), path); } |
### Question:
TCPConnectivity extends ConnectivityCapability { @Override public boolean supports(final SystemComponent requirement) { boolean supports = hasBasicSupport(requirement.getName(), requirement.getClassName()); if(supports) { String hostAddress = (String) requirement.getAttributes().get(HOST_ADDRESS); String hostName = (String) requirement.getAttributes().get(HOST_NAME); if(hostAddress!=null) { supports = hostAddress.equals(getValue(HOST_ADDRESS)); } else { supports = hostName.equalsIgnoreCase((String) getValue(HOST_NAME)); } } return supports; } TCPConnectivity(); TCPConnectivity(final String description); @Override boolean supports(final SystemComponent requirement); static final String IPv6_NIC; static final String IPv4_NIC; static final String HOST_ADDRESS; static final String HOST_NAME; static final String ID; }### Answer:
@Test public void testDoesNotSupportHostAddress() throws Exception { SystemComponent requirement = new SystemComponent(TCPConnectivity.ID); requirement.put(TCPConnectivity.HOST_ADDRESS, "127.0.0.1"); TCPConnectivity tcpConnectivity = new TCPConnectivity(); tcpConnectivity.define(TCPConnectivity.HOST_ADDRESS, "10.0.1.1"); Assert.assertFalse(tcpConnectivity.supports(requirement)); System.out.println(tcpConnectivity); System.out.println(requirement); }
@Test public void testSupportsHostAddress() throws Exception { SystemComponent requirement = new SystemComponent(TCPConnectivity.ID); requirement.put(TCPConnectivity.HOST_ADDRESS, "127.0.0.1"); TCPConnectivity tcpConnectivity = new TCPConnectivity(); tcpConnectivity.define(TCPConnectivity.HOST_ADDRESS, "127.0.0.1"); Assert.assertTrue(tcpConnectivity.supports(requirement)); }
@Test public void testSupportsHostName() throws Exception { SystemComponent requirement = new SystemComponent(TCPConnectivity.ID); requirement.put(TCPConnectivity.HOST_NAME, "mixed.case.name.net"); TCPConnectivity tcpConnectivity = new TCPConnectivity(); tcpConnectivity.define(TCPConnectivity.HOST_NAME, "MiXed.Case.Name.Net"); Assert.assertTrue(tcpConnectivity.supports(requirement)); }
@Test public void testDoesNotSupportHostName() throws Exception { SystemComponent requirement = new SystemComponent(TCPConnectivity.ID); requirement.put(TCPConnectivity.HOST_NAME, "some.name.net"); TCPConnectivity tcpConnectivity = new TCPConnectivity(); tcpConnectivity.define(TCPConnectivity.HOST_NAME, "some.other.name.net"); Assert.assertFalse(tcpConnectivity.supports(requirement)); } |
### Question:
StagedData implements Serializable { public long getDownloadSize() throws IOException { getLocationURL(); return locationURL.openConnection().getContentLengthLong(); } long getDownloadSize(); URL getLocationURL(); String getLocation(); void setLocation(String location); String getInstallRoot(); void setInstallRoot(String installRoot); void setUnarchive(boolean unarchive); void setRemoveOnDestroy(boolean removeOnDestroy); void setOverwrite(boolean overwrite); void setPerms(String perms); boolean unarchive(); boolean removeOnDestroy(); boolean overwrite(); String getPerms(); String toString(); }### Answer:
@Test public void testGetDownloadSize() throws IOException { StagedData stagedData = new StagedData(); stagedData.setLocation("https: long size = stagedData.getDownloadSize(); assertTrue(size != -1); } |
### Question:
ServiceStatement implements Serializable { public String getOrganization() { String organization = sElem.getServiceBeanConfig().getOrganization(); organization = (organization==null ? "" : organization); return (organization); } ServiceStatement(final ServiceElement sElem); ServiceElement getServiceElement(); String getOrganization(); boolean hasActiveServiceRecords(); void putServiceRecord(final Uuid instantiatorID, final ServiceRecord record); ServiceRecord[] getServiceRecords(); ServiceRecord[] getServiceRecords(final int type); ServiceRecord[] getServiceRecords(final Uuid instantiatorID, final int type); ServiceRecord[] getServiceRecords(final Uuid sbid); ServiceRecord[] getServiceRecords(final Uuid sbid, final Uuid instantiatorID); }### Answer:
@Test public void testGetOrganization() { ServiceElement element = makeServiceElement("Foo"); Uuid uuid = UuidFactory.generate(); ServiceRecord record = new ServiceRecord(uuid, element, "hostname"); ServiceStatement statement = new ServiceStatement(element); statement.putServiceRecord(recordingUuid, record); String organization = statement.getOrganization(); Assert.assertNotNull(organization); } |
### Question:
JMXConnectionUtil { public static String getPlatformMBeanServerAgentId() throws Exception { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); final String SERVER_DELEGATE = "JMImplementation:type=MBeanServerDelegate"; final String MBEAN_SERVER_ID_KEY = "MBeanServerId"; ObjectName delegateObjName = new ObjectName(SERVER_DELEGATE); return (String) mbs.getAttribute(delegateObjName, MBEAN_SERVER_ID_KEY ); } static String getPlatformMBeanServerAgentId(); static MBeanServerConnection attach(final String id); }### Answer:
@Test public void testGetPlatformMBeanAgentID() throws Exception { String agentID = JMXConnectionUtil.getPlatformMBeanServerAgentId(); Assert.assertNotNull(agentID); } |
### Question:
OpStringLoader { public OpStringLoader() { this(null); } OpStringLoader(); OpStringLoader(ClassLoader loader); void setDefaultGroups(String... groups); OperationalString[] parseOperationalString(File file); OperationalString[] parseOperationalString(URL url); static final String DEFAULT_FDH; }### Answer:
@Test public void testOpStringLoader() throws Exception { OpStringLoader opStringLoader = new OpStringLoader(); opStringLoader.setDefaultGroups("banjo"); String baseDir = System.getProperty("user.dir"); File calculator = new File(baseDir, "src/test/resources/opstrings/opstringloadertest.groovy"); OperationalString[] opStrings = opStringLoader.parseOperationalString(calculator); Assert.assertNotNull(opStrings); Assert.assertEquals("Should have only 1 opstring", 1, opStrings.length); Assert.assertEquals("Should have 1 service", 1, opStrings[0].getServices().length); Assert.assertEquals(1, opStrings[0].getServices()[0].getServiceBeanConfig().getGroups().length); Assert.assertEquals("banjo", opStrings[0].getServices()[0].getServiceBeanConfig().getGroups()[0]); } |
### Question:
StopWatch extends ThresholdWatch implements StopWatchMBean { public void setElapsedTime(long elapsed) { setElapsedTime(elapsed, System.currentTimeMillis()); } StopWatch(String id); StopWatch(String id, Configuration config); @SuppressWarnings("unused") StopWatch(WatchDataSource watchDataSource, String id); void startTiming(); void stopTiming(); void stopTiming(String detail); void setElapsedTime(long elapsed); void setElapsedTime(long elapsed, String detail); void setElapsedTime(long elapsed, long now); void setElapsedTime(long elapsed, long now, String detail); long getStartTime(); void setStartTime(long startTime); static final String VIEW; }### Answer:
@Test public void testSetElapsedTime1() throws RemoteException { StopWatch watch = new StopWatch("watch"); List<Long> expected = new ArrayList<Long>(); checkData(expected, watch); for (int i = 0; i < 10; i++) { long value = Math.round(Math.random() * 100); watch.setElapsedTime(value); expected.add(value); checkData(expected, watch); } Utils.close(watch.getWatchDataSource()); }
@Test public void testSetElapsedTime2() throws RemoteException { StopWatch watch = new StopWatch("watch"); List<Long> expectedValues = new ArrayList<Long>(); List<Long> expectedStamps = new ArrayList<Long>(); checkData(expectedValues, expectedStamps, watch); for (int i = 0; i < 10; i++) { long value = Math.round(Math.random() * 100); long stamp = Math.round(Math.random() * 100); watch.setElapsedTime(value, stamp); expectedValues.add(value); expectedStamps.add(stamp); checkData(expectedValues, expectedStamps, watch); } Utils.close(watch.getWatchDataSource()); } |
### Question:
StopWatch extends ThresholdWatch implements StopWatchMBean { public void startTiming() { setStartTime(System.currentTimeMillis()); } StopWatch(String id); StopWatch(String id, Configuration config); @SuppressWarnings("unused") StopWatch(WatchDataSource watchDataSource, String id); void startTiming(); void stopTiming(); void stopTiming(String detail); void setElapsedTime(long elapsed); void setElapsedTime(long elapsed, String detail); void setElapsedTime(long elapsed, long now); void setElapsedTime(long elapsed, long now, String detail); long getStartTime(); void setStartTime(long startTime); static final String VIEW; }### Answer:
@Test public void testStartTiming() throws RemoteException { StopWatch watch = new StopWatch("watch"); Assert.assertEquals(0, watch.getStartTime()); long prevStartTime = -1; for (int i = 0; i < 10; i++) { Utils.sleep(100); watch.startTiming(); long startTime = watch.getStartTime(); Assert.assertTrue(startTime >= 0); if (prevStartTime != -1) { Assert.assertTrue(startTime > prevStartTime); } prevStartTime = startTime; } checkData(0, watch); for (int i = 0; i < 10; i++) { watch.startTiming(); Utils.sleep(100); watch.stopTiming(); checkData(i + 1, watch); } Utils.close(watch.getWatchDataSource()); } |
### Question:
StopWatch extends ThresholdWatch implements StopWatchMBean { public void stopTiming() { long now = System.currentTimeMillis(); long startTime = getStartTime(); long elapsed = now - startTime; setElapsedTime(elapsed, now); } StopWatch(String id); StopWatch(String id, Configuration config); @SuppressWarnings("unused") StopWatch(WatchDataSource watchDataSource, String id); void startTiming(); void stopTiming(); void stopTiming(String detail); void setElapsedTime(long elapsed); void setElapsedTime(long elapsed, String detail); void setElapsedTime(long elapsed, long now); void setElapsedTime(long elapsed, long now, String detail); long getStartTime(); void setStartTime(long startTime); static final String VIEW; }### Answer:
@Test public void testStopTiming() throws RemoteException { StopWatch watch = new StopWatch("watch"); DataSourceMonitor mon = new DataSourceMonitor(watch); checkData(0, watch); for (int i = 0; i < 10; i++) { Utils.sleep(100); watch.stopTiming(); mon.waitFor(i + 1); Calculable[] calcs = watch.getWatchDataSource().getCalculable(); Assert.assertEquals(i + 1, calcs.length); Assert.assertTrue(calcs[0].getValue() > 0); for (int j = 1; j < calcs.length; j++) { Assert.assertTrue(calcs[j].getValue() >= calcs[j - 1].getValue()); } } for (int i = 0; i < 10; i++) { watch.startTiming(); Utils.sleep(100); watch.stopTiming(); checkData(10 + i + 1, watch); } Utils.close(watch.getWatchDataSource()); } |
### Question:
Statistics { public void clearAll() { v.clear(); } Statistics(); Statistics(Iterable<Double> values); void clearAll(); int count(); double max(); double min(); double mean(); double median(); double mode(); int modeOccurrenceCount(); double range(); double standardDeviation(); Vector getValues(); void addValue(Double double1); void addValue(double d); void setValues(Iterable<Double> vals); void setValues(Calculable[] calcs); void removeValues(double d, boolean removeAll); void removeValues(Double double1, boolean removeAll); void removeValue(int location); void removeValues(Double low, Double high); void removeValues(double low, double high); double sum(); }### Answer:
@Test public void testClearAll() { Statistics stat = new Statistics(); for (int i = 0; i < 5; i++) { stat.clearAll(); assertClean(stat); } List<Double> list = new ArrayList<>(); list.add((double) 0); list.add((double) 1); list.add((double) 2); stat.setValues(list); assertCorrect(list, stat); for (int i = 0; i < 5; i++) { stat.clearAll(); assertClean(stat); } } |
### Question:
WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { public WatchDataSource export() throws RemoteException { if(exported && proxy!=null) return(proxy); if(config != null) { try { exporter = ExporterConfig.getExporter(config, COMPONENT, "watchDataSourceExporter"); } catch(Exception e) { logger.error("Getting watchDataSourceExporter", e); } } proxy = (WatchDataSource)exporter.export(this); exported = true; return (proxy); } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer:
@Test public void testExport() throws Exception { final int N = 3; Integer[] counts = new Integer[N]; for (int i = 0; i < N; i++) { counts[i] = i; } Object[][] combinations = ArrayUtils.combinations(new Object[][] { counts, counts, booleanAxis}); int i = 0; while (i < combinations.length) { int exportCount = (Integer) combinations[i][0]; int unexportCount = (Integer) combinations[i][1]; boolean force = (Boolean) combinations[i][2]; LoggingWatchDataSourceImpl impl = new LoggingWatchDataSourceImpl( "watch", null, EmptyConfiguration.INSTANCE); List<WatchDataSource> proxies = new ArrayList<WatchDataSource>(); for (int j = 0; j < exportCount; j++) { proxies.add(impl.export()); } for (int j = 0; j < unexportCount; j++) { impl.unexport(force); } if (exportCount > 0 && unexportCount == 0 ) { Assert.assertNotNull(impl.getProxy()); } else { Assert.assertNull(impl.getProxy()); } WatchDataSource proxy = impl.export(); Assert.assertNotNull(proxy); assertValidProxy(proxy, impl); Assert.assertSame(proxy, impl.getProxy()); if (proxies.size() > 0) { assertAllSame(proxies); if (unexportCount == 0) { Assert.assertSame(proxies.get(0), proxy); } else { Assert.assertNotSame(proxies.get(0), proxy); } } assertAddCalculableWorks(impl, 10, true); impl.close(); i++; } } |
### Question:
WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { public void unexport(boolean force) { if(!exported) return; try { exporter.unexport(force); exported = false; proxy = null; } catch(IllegalStateException e) { } } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer:
@Test public void testUnexport() throws Exception { final int N = 3; Integer[] counts = new Integer[N]; for (int i = 0; i < N; i++) { counts[i] = i; } Object[][] combinations = ArrayUtils.combinations(new Object[][] { counts, counts, booleanAxis}); for (Object[] combination : combinations) { int exportCount = (Integer) combination[0]; int unexportCount = (Integer) combination[1]; boolean force = (Boolean) combination[2]; LoggingWatchDataSourceImpl impl = new LoggingWatchDataSourceImpl( "watch", null, EmptyConfiguration.INSTANCE); List<WatchDataSource> proxies = new ArrayList<WatchDataSource>(); for (int j = 0; j < exportCount; j++) { proxies.add(impl.export()); } for (int j = 0; j < unexportCount; j++) { impl.unexport(force); } if (exportCount > 0 && unexportCount == 0) { Assert.assertNotNull(impl.getProxy()); } else { Assert.assertNull(impl.getProxy()); } impl.unexport(force); Assert.assertNull(impl.getProxy()); if (proxies.size() > 0) { assertAllSame(proxies); assertInvalidProxy(proxies.get(0), impl); } assertAddCalculableWorks(impl, 10, true); impl.close(); } } |
### Question:
WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { public WatchDataSource getProxy() { return (proxy); } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer:
@Test public void testGetProxy() throws Exception { final int N = 5; Integer[] counts = new Integer[N]; for (int i = 0; i < N; i++) { counts[i] = i; } Object[][] combinations = ArrayUtils.combinations(new Object[][] { counts, counts, booleanAxis}); for (Object[] combination : combinations) { int exportCount = (Integer) combination[0]; int unexportCount = (Integer) combination[1]; boolean force = (Boolean) combination[2]; LoggingWatchDataSourceImpl impl = new LoggingWatchDataSourceImpl( "watch", null, EmptyConfiguration.INSTANCE); for (int j = 0; j < exportCount; j++) { impl.export(); } for (int j = 0; j < unexportCount; j++) { impl.unexport(force); } if (exportCount > 0 && unexportCount == 0) { Assert.assertNotNull(impl.getProxy()); assertValidProxy(impl.getProxy(), impl); } else { Assert.assertNull(impl.getProxy()); } impl.close(); } } |
### Question:
WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { public String getID() { return (id); } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer:
@Test public void testGetID() throws Exception { WatchDataSourceImpl impl = new WatchDataSourceImpl(); impl.setID("watch"); Assert.assertEquals("watch", impl.getID()); impl.setID("aaa"); Assert.assertEquals("aaa", impl.getID()); impl.close(); } |
### Question:
WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { public void setID(String id) { if(id==null) throw new IllegalArgumentException("id is null"); this.id = id; } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer:
@Test public void testSetID() throws Exception { WatchDataSourceImpl impl = new WatchDataSourceImpl(); impl.setID("aaa"); Assert.assertEquals("aaa", impl.getID()); impl.setID(""); Assert.assertEquals("", impl.getID()); try { impl.setID("bbb"); impl.setID(null); Assert.fail("IllegalArgumentException expected but not thrown"); } catch (IllegalArgumentException e) { } Assert.assertEquals("bbb", impl.getID()); impl.close(); } |
### Question:
WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { public void clear() { synchronized(history) { history.clear(); } } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer:
@Test public void testClear() throws Exception { final int DCS = WatchDataSourceImpl.DEFAULT_COLLECTION_SIZE; WatchDataSourceImpl impl = new WatchDataSourceImpl(); impl.setID("watch"); impl.setConfiguration(EmptyConfiguration.INSTANCE); for (int j = 0; j < DCS; j++) { impl.addCalculable(new Calculable()); } DataSourceMonitor mon = new DataSourceMonitor(impl); mon.waitFor(DCS); int expected = Math.min(DCS, DCS); Assert.assertEquals(expected, impl.getCalculable().length); impl.clear(); Assert.assertEquals(0, impl.getCalculable().length); impl.close(); } |
### Question:
WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { public int getCurrentSize() { int size; synchronized(history) { size = history.size(); } return (size); } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer:
@Test public void testGetCurrentSize() throws Exception { final int DCS = WatchDataSourceImpl.DEFAULT_COLLECTION_SIZE; WatchDataSourceImpl impl = new WatchDataSourceImpl(); impl.setID("watch"); impl.setConfiguration(EmptyConfiguration.INSTANCE); for (int j = 0; j < DCS; j++) { impl.addCalculable(new Calculable()); } DataSourceMonitor mon = new DataSourceMonitor(impl); mon.waitFor(DCS); int expected = Math.min(DCS, DCS); Assert.assertEquals(expected, impl.getCurrentSize()); impl.close(); } |
### Question:
WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { @SuppressWarnings("unchecked") public void addCalculable(Calculable calculable) { if(calculable==null) throw new IllegalArgumentException("calculable is null"); if(!closed) { addToHistory(calculable); for(WatchDataReplicator replicator : getWatchDataReplicators()) { if(logger.isTraceEnabled()) logger.trace("Replicating [{}] to {} {}", calculable.toString(), replicator, replicator.getClass().getName()); replicator.addCalculable(calculable); } } } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer:
@Test public void testAddCalculable() throws Exception { doTestAddCalculable(LoggingWatchDataReplicator.class.getName()); doTestAddCalculable(RemoteWDR.class.getName()); } |
### Question:
WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { public boolean addWatchDataReplicator(WatchDataReplicator replicator) { boolean added = false; if(replicator==null) return added; synchronized(replicators) { if(!replicators.contains(replicator)) added = replicators.add(replicator); } return added; } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer:
@Test public void testAddWatchDataReplicator() throws Exception { WatchDataSourceImpl impl = new WatchDataSourceImpl(); impl.setID("watch"); impl.setConfiguration(new DynamicConfiguration()); WatchDataReplicator wdr1 = new LoggingWatchDataReplicator(); impl.addWatchDataReplicator(wdr1); Assert.assertSame(wdr1, impl.getWatchDataReplicators()[0]); WatchDataReplicator wdr2 = new LoggingWatchDataReplicator(); impl.addWatchDataReplicator(wdr2); Assert.assertSame(wdr2, impl.getWatchDataReplicators()[1]); impl.addWatchDataReplicator(null); Assert.assertNotNull(impl.getWatchDataReplicators()); Assert.assertTrue(impl.getWatchDataReplicators().length==2); impl.close(); } |
### Question:
Statistics { public Vector getValues() { return (Vector)v.clone(); } Statistics(); Statistics(Iterable<Double> values); void clearAll(); int count(); double max(); double min(); double mean(); double median(); double mode(); int modeOccurrenceCount(); double range(); double standardDeviation(); Vector getValues(); void addValue(Double double1); void addValue(double d); void setValues(Iterable<Double> vals); void setValues(Calculable[] calcs); void removeValues(double d, boolean removeAll); void removeValues(Double double1, boolean removeAll); void removeValue(int location); void removeValues(Double low, Double high); void removeValues(double low, double high); double sum(); }### Answer:
@Test public void testGetValues() { Statistics stat = new Statistics(); Assert.assertEquals(new Vector(), stat.getValues()); for (int i = 0; i < 10; i++) { Vector<Double> v = new Vector<>(); int count = (int) (Math.random() * 1000); for (int j = 0; j < count; j++) { double d = Math.random(); stat.addValue(d); v.add(d); } Assert.assertEquals(v, stat.getValues()); stat.clearAll(); Assert.assertEquals(new Vector(), stat.getValues()); } Vector<Double> v = new Vector<>(); stat.setValues(v); Assert.assertEquals(v, stat.getValues()); Assert.assertNotSame(v, stat.getValues()); } |
### Question:
WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { public ThresholdValues getThresholdValues() { ThresholdValues thresholdValues; if(thresholdManager!=null) thresholdValues = thresholdManager.getThresholdValues(); else thresholdValues = new ThresholdValues(); return thresholdValues; } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer:
@Test public void testGetThresholdValues() throws Exception { WatchDataSourceImpl impl = new WatchDataSourceImpl(); impl.setThresholdManager(new BoundedThresholdManager("watch")); impl.setID("watch"); impl.setConfiguration(EmptyConfiguration.INSTANCE); ThresholdValues tv = impl.getThresholdValues(); Assert.assertNotNull(tv); tv = new ThresholdValues(); impl.setThresholdValues(tv); Assert.assertSame(tv, impl.getThresholdValues()); impl.close(); } |
### Question:
WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { public void setThresholdValues(ThresholdValues tValues) { if(thresholdManager!=null) thresholdManager.setThresholdValues(tValues); } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer:
@Test public void testSetThresholdValues() throws Exception { WatchDataSourceImpl impl = new WatchDataSourceImpl(); impl.setID("watch"); impl.setThresholdManager(new BoundedThresholdManager("watch")); impl.setConfiguration(EmptyConfiguration.INSTANCE); ThresholdValues tv = new ThresholdValues(); impl.setThresholdValues(tv); Assert.assertSame(tv, impl.getThresholdValues()); impl.setThresholdValues(null); Assert.assertSame(tv, impl.getThresholdValues()); impl.close(); } |
### Question:
WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { public void close() { for(WatchDataReplicator replicator : getWatchDataReplicators()) replicator.close(); synchronized(replicators) { replicators.clear(); } closed = true; unexport(true); } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer:
@Test public void testClose() throws Exception { final int N = 3; Integer[] counts = new Integer[N]; for (int i = 0; i < N; i++) { counts[i] = i; } Object[][] combinations = ArrayUtils.combinations(new Object[][] { counts, counts, counts}); for (Object[] combination : combinations) { int exportCount = (Integer) combination[0]; int unexportCount = (Integer) combination[1]; int closeCount = (Integer) combination[2]; LoggingWatchDataReplicator watchDataReplicator = new LoggingWatchDataReplicator(); LoggingWatchDataSourceImpl impl = new LoggingWatchDataSourceImpl( "watch", watchDataReplicator, EmptyConfiguration.INSTANCE); Utils.sleep(200); WatchDataSource proxy = null; for (int j = 0; j < exportCount; j++) { proxy = impl.export(); } for (int j = 0; j < unexportCount; j++) { impl.unexport(true); } for (int j = 0; j < closeCount; j++) { impl.close(); } impl.close(); if (proxy != null) { assertInvalidProxy(proxy, impl); } Assert.assertNull(impl.getProxy()); assertAddCalculableWorks(impl, 10, false); Assert.assertEquals(0, impl.getWatchDataReplicators().length); checkLog(watchDataReplicator.log(), "close()"); } } |
### Question:
WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { public String getView() { return (viewClass); } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer:
@Test public void testGetView() throws Exception { WatchDataSourceImpl impl = new WatchDataSourceImpl(); impl.setID("watch"); impl.setConfiguration(EmptyConfiguration.INSTANCE); Assert.assertEquals(null, impl.getView()); impl.setView("abcd"); Assert.assertEquals("abcd", impl.getView()); impl.close(); } |
### Question:
WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { public void setView(String viewClass) { this.viewClass = viewClass; } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer:
@Test public void testSetView() throws Exception { WatchDataSourceImpl impl = new WatchDataSourceImpl(); impl.setID("watch"); impl.setConfiguration(EmptyConfiguration.INSTANCE); impl.setView("abcd"); Assert.assertEquals("abcd", impl.getView()); impl.setView(""); Assert.assertEquals("", impl.getView()); impl.setView(null); Assert.assertEquals(null, impl.getView()); impl.close(); } |
### Question:
WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { public TrustVerifier getProxyVerifier() { return (new BasicProxyTrustVerifier(proxy)); } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer:
@Test public void testGetProxyVerifier() throws Exception { final int N = 3; Integer[] counts = new Integer[N]; for (int i = 0; i < N; i++) { counts[i] = i; } Object[][] combinations = ArrayUtils.combinations(new Object[][] { counts, counts}); for (Object[] combination : combinations) { int exportCount = (Integer) combination[0]; int unexportCount = (Integer) combination[1]; WatchDataSourceImpl impl = new WatchDataSourceImpl(); impl.setID("watch"); impl.setConfiguration(EmptyConfiguration.INSTANCE); for (int j = 0; j < exportCount; j++) { impl.export(); } for (int j = 0; j < unexportCount; j++) { impl.unexport(true); } if (exportCount == 0 || unexportCount > 0) { try { impl.getProxyVerifier(); Assert.fail("IllegalArgumentException expected" + " but not thrown"); } catch (IllegalArgumentException e) { } } else { Assert.assertNotNull(impl.getProxyVerifier()); } impl.close(); } } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.