method2testcases
stringlengths
118
6.63k
### Question: ResendFailedMessageServiceBeanDefinitionFactory { public AbstractBeanDefinition create(String brokerName, String messageSenderBeanName) { return genericBeanDefinition(ResendFailedMessageService.class) .addConstructorArgValue(brokerName) .addConstructorArgReference("failedMessageSearchService") .addConstructorArgReference(messageSenderBeanName) .addConstructorArgValue(historicStatusPredicate) .getBeanDefinition(); } ResendFailedMessageServiceBeanDefinitionFactory(HistoricStatusPredicate historicStatusPredicate); AbstractBeanDefinition create(String brokerName, String messageSenderBeanName); String createBeanName(String brokerName); }### Answer: @Test public void createResendFailedMessageServiceBeanDefinition() throws Exception { AbstractBeanDefinition abstractBeanDefinition = underTest.create(BROKER_NAME, "messageSender"); assertThat(abstractBeanDefinition.getBeanClass(), typeCompatibleWith(ResendFailedMessageService.class)); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getIndexedArgumentValues().size(), is(4)); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getArgumentValue(0, String.class).getValue(), is(BROKER_NAME)); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getArgumentValue(1, FailedMessageSearchService.class).getValue(), is(equalTo(new RuntimeBeanReference("failedMessageSearchService")))); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getArgumentValue(2, MessageSender.class).getValue(), is(equalTo(new RuntimeBeanReference("messageSender")))); assertThat(abstractBeanDefinition.getConstructorArgumentValues().getArgumentValue(3, HistoricStatusPredicate.class).getValue(), is(historicStatusPredicate)); }
### Question: ResendFailedMessageServiceBeanDefinitionFactory { public String createBeanName(String brokerName) { return RESEND_FAILED_MESSAGE_SERVICE_BEAN_NAME_PREFIX + brokerName; } ResendFailedMessageServiceBeanDefinitionFactory(HistoricStatusPredicate historicStatusPredicate); AbstractBeanDefinition create(String brokerName, String messageSenderBeanName); String createBeanName(String brokerName); }### Answer: @Test public void createBeanName() throws Exception { assertThat(underTest.createBeanName(BROKER_NAME), is(equalTo(RESEND_FAILED_MESSAGE_SERVICE_BEAN_NAME_PREFIX + BROKER_NAME))); }
### Question: ResendFailedMessageService { public void resendMessages() { LOGGER.debug("Resending FailedMessages to: {}", brokerName); failedMessageSearchService .search(searchMatchingAllCriteria() .withBroker(brokerName) .withStatus(RESENDING) .build()) .stream() .filter(historicStatusPredicate::test) .forEach(messageSender::send); } ResendFailedMessageService(String brokerName, FailedMessageSearchService failedMessageSearchService, MessageSender messageSender, HistoricStatusPredicate historicStatusPredicate); void resendMessages(); String getBrokerName(); }### Answer: @Test public void successfullyResendFailedMessages() throws Exception { SearchFailedMessageRequest searchRequest = argThat(new HamcrestArgumentMatcher<>(aSearchRequestMatchingAllCriteria() .withBroker(equalTo(Optional.of(BROKER_NAME))) .withStatusMatcher(contains(RESENDING)))); when(failedMessageSearchService.search(searchRequest)).thenReturn(asList(failedMessage, anotherFailedMessage)); when(historicStatusPredicate.test(failedMessage)).thenReturn(true); when(historicStatusPredicate.test(anotherFailedMessage)).thenReturn(false); underTest.resendMessages(); verify(messageSender).send(failedMessage); verifyNoMoreInteractions(messageSender); }
### Question: VaultApiFactory { Vault createVaultAPI(VaultProperties vaultProperties) throws VaultException { return new Vault(buildConfiguration(vaultProperties)); } }### Answer: @Test public void throwsExceptionWhenTokenFileNotFound() throws Exception { VaultProperties vaultProperties = createVaultPropertiesWithTokenFileAt(FILE_LOCATION_THAT_DOES_NOT_EXIST); expectedException.expect(VaultException.class); expectedException.expectCause(isA(NoSuchFileException.class)); expectedException.expectMessage(is("java.nio.file.NoSuchFileException: /tmp/file-does-not-exist")); underTest.createVaultAPI(vaultProperties); } @Test public void readsTokenFileWhenItExists() throws Exception { String tokenFileLocation = ensureTokenFileExists(); VaultProperties vaultProperties = createVaultPropertiesWithTokenFileAt(tokenFileLocation); Vault vaultAPI = underTest.createVaultAPI(vaultProperties); assertThat(new File(tokenFileLocation).exists(), is(true)); assertThat(vaultAPI, is(notNullValue())); } @Test public void readsTokenFileWhenItIsAFileUri() throws Exception { String tokenFileLocation = ensureTokenFileExists(); VaultProperties vaultProperties = createVaultPropertiesWithTokenFileAt("file:" + tokenFileLocation); Vault vaultAPI = underTest.createVaultAPI(vaultProperties); assertThat(vaultAPI, is(notNullValue())); } @Test public void readsTokenFileWhenItIsAClasspathFile() throws Exception { VaultProperties vaultProperties = createVaultPropertiesWithTokenFileAt("classpath:test-token-value-file"); Vault vaultAPI = underTest.createVaultAPI(vaultProperties); assertThat(vaultAPI, is(notNullValue())); }
### Question: FailedMessageId implements Id { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return id.equals(((FailedMessageId) o).id); } private FailedMessageId(UUID id); static FailedMessageId newFailedMessageId(); static FailedMessageId fromUUID(UUID uuid); @JsonCreator static FailedMessageId fromString(String uuid); @Override UUID getId(); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); static final String FAILED_MESSAGE_ID; }### Answer: @Test public void equalsTest() { assertFalse(FAILED_MESSAGE_ID.equals(null)); assertFalse(FailedMessageId.fromUUID(A_UUID).equals(A_UUID)); assertFalse(FailedMessageId.newFailedMessageId().equals(FAILED_MESSAGE_ID)); assertTrue(FAILED_MESSAGE_ID.equals(FAILED_MESSAGE_ID)); assertTrue(FailedMessageId.fromUUID(A_UUID).equals(FailedMessageId.fromUUID(A_UUID))); }
### Question: SingleValueVaultLookupStrategy implements SensitiveConfigValueLookupStrategy { @Override public boolean matches(String secret) { return isVaultEnabledAndPatternMatches(secret); } SingleValueVaultLookupStrategy(VaultProperties vaultProperties, VaultApiFactory vaultApiFactory); @Override boolean matches(String secret); @Override DecryptedValue retrieveSecret(String secretPath); }### Answer: @Test public void matchesWhenConfiguredAndCorrectPath() throws Exception { assertThat(underTest.matches(MATCHING_PATH), is(true)); } @Test public void secretPathDoesNotMatch() throws Exception { assertThat(underTest.matches(NON_MATCHING_PATH), is(false)); }
### Question: SingleValueVaultLookupStrategy implements SensitiveConfigValueLookupStrategy { @Override public DecryptedValue retrieveSecret(String secretPath) { Matcher matcher = PATTERN.matcher(secretPath); if (matcher.matches()) { String vaultPath = matcher.group(1); try { String value = vaultAPI().logical().read(vaultPath).getData().get(VALUE_KEY); return new DecryptedValue(value.toCharArray()); } catch (VaultException e) { int httpStatusCode = e.getHttpStatusCode(); switch (httpStatusCode) { case 0: throw new RuntimeException("Unable to connect to vault at:'" + vaultProperties.getAddress() + "', looking up the path '" + secretPath + "'", e); case 404: case 403: throw new RuntimeException("Connected to '" + vaultProperties.getAddress() + "': unable to read secret at path '" + secretPath + "'", e); default: throw new RuntimeException("HTTP status " + httpStatusCode + ". Could not retrieve from Vault '" + vaultProperties.getAddress() + "': the path '" + secretPath + "'", e); } } } else { throw new IllegalStateException("Secret: '" + secretPath + "' did not match pattern did you call matches(secret) first?"); } } SingleValueVaultLookupStrategy(VaultProperties vaultProperties, VaultApiFactory vaultApiFactory); @Override boolean matches(String secret); @Override DecryptedValue retrieveSecret(String secretPath); }### Answer: @Test public void unableToRetrieveIfNotAVaultSecretPath() throws Exception { expectedException.expect(IllegalStateException.class); underTest.retrieveSecret(NON_MATCHING_PATH); } @Test public void readsSecretFromVault() throws Exception { DecryptedValue decryptedPassword = underTest.retrieveSecret(MATCHING_PATH); assertThat(decryptedPassword.getClearText(), is(SECRET_VALUE.toCharArray())); } @Test public void wrapsVaultException() throws Exception { doAnswer(invocation -> { throw new VaultException("expected"); }).when(vault).logical(); expectedException.expect(RuntimeException.class); expectedException.expectMessage("Unable to connect to vault at:'null', looking up the path 'VAULT(/some/secret/path)'"); underTest.retrieveSecret(MATCHING_PATH); } @Test public void ensureThatARuntimeExceptionIsThrownWhenVaultKeyIsNotFound() throws Exception { expectedException.expect(RuntimeException.class); expectedException.expectMessage(is("Connected to '" + VAULT_PROPERTIES.getAddress() + "': unable to read secret at path '" + MATCHING_PATH + "'")); Logical logical = mock(Logical.class); when(vault.logical()).thenReturn(logical); when(logical.read(SOME_PATH)).thenThrow(new VaultException("Oops", 404)); underTest.retrieveSecret(MATCHING_PATH); }
### Question: SensitiveConfigValueLookupRegistry { public DecryptedValue retrieveSecret(String secretPath) { return resolutionStrategies .stream() .filter(service -> service.matches(secretPath)) .findFirst() .map(service -> service.retrieveSecret(secretPath)) .orElseThrow(() -> new IllegalArgumentException("No relevant strategy could be found to resolve vault path for: " + secretPath)); } SensitiveConfigValueLookupRegistry(List<SensitiveConfigValueLookupStrategy> resolutionStrategies); DecryptedValue retrieveSecret(String secretPath); }### Answer: @Test public void ensureThatIfNoResolutionStrategyForAVaultKeyCanBeFound_thenThrowAnIllegalArgumentException() throws Exception { SensitiveConfigValueLookupRegistry registry = new SensitiveConfigValueLookupRegistry(emptyList()); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(is("No relevant strategy could be found to resolve vault path for: bogus/path")); registry.retrieveSecret("bogus/path"); } @Test public void ensureThatIfResolutionStrategyIsFoundButItReturnsNull_thenThrowAnIllegalArgumentException() throws Exception { List<SensitiveConfigValueLookupStrategy> listOfStrategies = new ArrayList<>(); listOfStrategies.add(new SensitiveConfigValueLookupStrategy() { @Override public DecryptedValue retrieveSecret(String secret) { return null; } @Override public boolean matches(String secret) { return true; } }); SensitiveConfigValueLookupRegistry registry = new SensitiveConfigValueLookupRegistry(listOfStrategies); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(is("No relevant strategy could be found to resolve vault path for: bogus/path")); registry.retrieveSecret("bogus/path"); }
### Question: VaultPropertySource extends MapPropertySource { @Override public char[] getProperty(String name) { if (containsProperty(name)) { LOGGER.trace("Attempting to lookup property key = {}", name); return sensitiveConfigValueLookupRegistry.retrieveSecret(super.getProperty(name).toString()).getClearText(); } return null; } VaultPropertySource(Map<String, Object> source, SensitiveConfigValueLookupRegistry registry); @Override char[] getProperty(String name); }### Answer: @Test public void ensureThatPropertyKeyThatRequiresResolutionFromVault_isDelegatedToTheUnderlyingRegistry() throws Exception { Map<String, Object> mapOfKeys = new HashMap<>(); String expectedTestKey = "expected.test.key"; String vaultConfigValue = "VAULT(my/secret/path)"; char[] expectedResolvedValue = new char[]{'p', 'a', 's', 's'}; mapOfKeys.put(expectedTestKey, vaultConfigValue); when(registry.retrieveSecret(vaultConfigValue)).thenReturn(new DecryptedValue(expectedResolvedValue)); VaultPropertySource vaultPropertySource = new VaultPropertySource(mapOfKeys, registry); char[] actualResolverKey = vaultPropertySource.getProperty(expectedTestKey); assertTrue(Arrays.equals(actualResolverKey, expectedResolvedValue)); } @Test public void ensureThatIfAttemptingToRetriveAKeyThatIsNotInTheListOfResovableKeys_thenReturnNull() throws Exception { VaultPropertySource vaultPropertySource = new VaultPropertySource(new HashMap<>(), registry); char[] property = vaultPropertySource.getProperty("non-existent-key"); assertNull(property); verifyZeroInteractions(registry); }
### Question: FailedMessageId implements Id { @Override public int hashCode() { return id.hashCode(); } private FailedMessageId(UUID id); static FailedMessageId newFailedMessageId(); static FailedMessageId fromUUID(UUID uuid); @JsonCreator static FailedMessageId fromString(String uuid); @Override UUID getId(); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); static final String FAILED_MESSAGE_ID; }### Answer: @Test public void hashCodeTest() { assertNotEquals(FAILED_MESSAGE_ID.hashCode(), FailedMessageId.newFailedMessageId().hashCode()); assertEquals(FAILED_MESSAGE_ID.getId().hashCode(), FAILED_MESSAGE_ID.hashCode()); }
### Question: FailedMessageBuilderFactory { public FailedMessageBuilder create(FailedMessageId failedMessageId) { return failedMessageDao.findById(failedMessageId) .filter(IS_DELETED.negate()) .map(createFailedMessageBuilder()) .orElseThrow(failedMessageNotFound(failedMessageId)) .withUpdateRequestAdapterRegistry(updateRequestAdapterRegistry); } FailedMessageBuilderFactory(UpdateRequestAdapterRegistry updateRequestAdapterRegistry, FailedMessageDao failedMessageDao); FailedMessageBuilder create(FailedMessageId failedMessageId); }### Answer: @Test public void failedMessageNotFoundExceptionThrownWhenFailedMessageEmpty() { expectedException.expect(FailedMessageNotFoundException.class); expectedException.expectMessage("Failed Message: " + FAILED_MESSAGE_ID + " not found"); when(failedMessageDao.findById(FAILED_MESSAGE_ID)).thenReturn(Optional.empty()); underTest.create(FAILED_MESSAGE_ID); verifyZeroInteractions(failedMessageBuilder); } @Test public void failedMessageNotFoundExceptionThrownIfStatusIsDeleted() { expectedException.expect(FailedMessageNotFoundException.class); expectedException.expectMessage("Failed Message: " + FAILED_MESSAGE_ID + " not found"); when(failedMessageDao.findById(FAILED_MESSAGE_ID)).thenReturn(Optional.of(failedMessage)); when(failedMessage.getStatus()).thenReturn(DELETED); underTest.create(FAILED_MESSAGE_ID); verifyZeroInteractions(failedMessageBuilder); } @Test public void successfullyCreateAFailedMessageBuilder() { when(failedMessageDao.findById(FAILED_MESSAGE_ID)).thenReturn(Optional.of(failedMessage)); when(failedMessage.getStatus()).thenReturn(FAILED); when(failedMessageBuilder.withUpdateRequestAdapterRegistry(updateRequestAdapterRegistry)).thenReturn(failedMessageBuilder); assertThat(underTest.create(FAILED_MESSAGE_ID), is(failedMessageBuilder)); verify(failedMessageBuilder).withUpdateRequestAdapterRegistry(updateRequestAdapterRegistry); }
### Question: FailedMessageLabelService { public void addLabel(FailedMessageId failedMessageId, String label) { LOGGER.debug("Adding label '{}' to FailedMessage: {}", label, failedMessageId); failedMessageDao.addLabel(failedMessageId, label); } FailedMessageLabelService(FailedMessageDao failedMessageDao); void addLabel(FailedMessageId failedMessageId, String label); void removeLabel(FailedMessageId failedMessageId, String label); void setLabels(FailedMessageId failedMessageId, Set<String> labels); }### Answer: @Test public void addLabelDelegatesToDao() throws Exception { underTest.addLabel(FAILED_MESSAGE_ID, LABEL); verify(failedMessageDao).addLabel(FAILED_MESSAGE_ID, LABEL); }
### Question: FailedMessageLabelService { public void removeLabel(FailedMessageId failedMessageId, String label) { LOGGER.debug("Removing label '{}' from FailedMessage: {}", label, failedMessageId); failedMessageDao.removeLabel(failedMessageId, label); } FailedMessageLabelService(FailedMessageDao failedMessageDao); void addLabel(FailedMessageId failedMessageId, String label); void removeLabel(FailedMessageId failedMessageId, String label); void setLabels(FailedMessageId failedMessageId, Set<String> labels); }### Answer: @Test public void removeLabelDelegatesToDao() throws Exception { underTest.removeLabel(FAILED_MESSAGE_ID, LABEL); verify(failedMessageDao).removeLabel(FAILED_MESSAGE_ID, LABEL); }
### Question: FailedMessageLabelService { public void setLabels(FailedMessageId failedMessageId, Set<String> labels) { LOGGER.debug("Replacing all labels on FailedMessage: {}", failedMessageId); failedMessageDao.setLabels(failedMessageId, labels); } FailedMessageLabelService(FailedMessageDao failedMessageDao); void addLabel(FailedMessageId failedMessageId, String label); void removeLabel(FailedMessageId failedMessageId, String label); void setLabels(FailedMessageId failedMessageId, Set<String> labels); }### Answer: @Test public void setLabelsDelegatesToDao() { underTest.setLabels(FAILED_MESSAGE_ID, singleton(LABEL)); verify(failedMessageDao).setLabels(FAILED_MESSAGE_ID, singleton(LABEL)); }
### Question: FailedMessageService { public void create(FailedMessage failedMessage) { failedMessageDao.insert(failedMessage); } FailedMessageService(FailedMessageDao failedMessageDao, FailedMessageBuilderFactory failedMessageBuilderFactory); void create(FailedMessage failedMessage); void delete(FailedMessageId failedMessageId); void update(FailedMessageId failedMessageId, T updateRequest); void update(FailedMessageId failedMessageId, List<? extends UpdateRequest> updateRequests); }### Answer: @Test public void createFailedMessageDelegatesToDao() { underTest.create(failedMessage); Mockito.verify(failedMessageDao).insert(failedMessage); }
### Question: FailedMessageService { public <T extends UpdateRequest> void update(FailedMessageId failedMessageId, T updateRequest) { update(failedMessageId, Collections.singletonList(updateRequest)); } FailedMessageService(FailedMessageDao failedMessageDao, FailedMessageBuilderFactory failedMessageBuilderFactory); void create(FailedMessage failedMessage); void delete(FailedMessageId failedMessageId); void update(FailedMessageId failedMessageId, T updateRequest); void update(FailedMessageId failedMessageId, List<? extends UpdateRequest> updateRequests); }### Answer: @Test public void noUpdatesArePerformedIfTheUpdateRequestListIsEmpty() { underTest.update(FAILED_MESSAGE_ID, Collections.emptyList()); verifyZeroInteractions(failedMessageDao); verifyZeroInteractions(failedMessageBuilderFactory); }
### Question: PredicateOutcomeFailedMessageProcessor implements FailedMessageProcessor { @Override public void process(FailedMessage failedMessage) { if (predicate.test(failedMessage)) { positiveOutcomeFailedMessageProcessor.process(failedMessage); } else { negativeOutcomeFailedMessageProcessor.process(failedMessage); } } PredicateOutcomeFailedMessageProcessor(Predicate<FailedMessage> predicate, FailedMessageProcessor positiveOutcomeFailedMessageProcessor, FailedMessageProcessor negativeOutcomeFailedMessageProcessor); @Override void process(FailedMessage failedMessage); }### Answer: @Test public void messageIsADuplicate() { duplicate = true; underTest.process(failedMessage); verify(duplicateFailedMessageProcessor).process(failedMessage); verifyZeroInteractions(newFailedMessageProcessor); } @Test public void messageIsNotADuplicate() { duplicate = false; underTest.process(failedMessage); verify(newFailedMessageProcessor).process(failedMessage); verifyZeroInteractions(duplicateFailedMessageProcessor); }
### Question: FailedMessageId implements Id { @Override public String toString() { return id.toString(); } private FailedMessageId(UUID id); static FailedMessageId newFailedMessageId(); static FailedMessageId fromUUID(UUID uuid); @JsonCreator static FailedMessageId fromString(String uuid); @Override UUID getId(); @Override int hashCode(); @Override boolean equals(Object o); @Override String toString(); static final String FAILED_MESSAGE_ID; }### Answer: @Test public void toStringTest() { assertEquals(FAILED_MESSAGE_ID.getId().toString(), FAILED_MESSAGE_ID.toString()); }
### Question: NewFailedMessageProcessor implements FailedMessageProcessor { @Override public void process(FailedMessage failedMessage) { failedMessageService.create(failedMessage); } NewFailedMessageProcessor(FailedMessageService failedMessageService); @Override void process(FailedMessage failedMessage); }### Answer: @Test public void delegatesToFailedMessageService() { underTest.process(failedMessage); }
### Question: UniqueFailedMessageIdPredicate implements Predicate<FailedMessage> { @Override public boolean test(FailedMessage failedMessage) { return !failedMessageDao.findById(failedMessage.getFailedMessageId()).isPresent(); } UniqueFailedMessageIdPredicate(FailedMessageDao failedMessageDao); @Override boolean test(FailedMessage failedMessage); }### Answer: @Test public void predicateReturnsTrueWhenFailedMesageWithIdDoesNotExist() { when(failedMessage.getFailedMessageId()).thenReturn(FAILED_MESSAGE_ID); when(failedMessageDao.findById(FAILED_MESSAGE_ID)).thenReturn(Optional.empty()); assertThat(underTest.test(failedMessage), is(true)); } @Test public void predicateReturnsFalseWhenFailedMessageWithIdExists() { when(failedMessage.getFailedMessageId()).thenReturn(FAILED_MESSAGE_ID); when(failedMessageDao.findById(FAILED_MESSAGE_ID)).thenReturn(Optional.of(failedMessage)); assertThat(underTest.test(failedMessage), is(false)); }
### Question: ExistingFailedMessageProcessor implements FailedMessageProcessor { @Override public void process(FailedMessage failedMessage) { failedMessageDao.update(failedMessage); } ExistingFailedMessageProcessor(FailedMessageDao failedMessageDao); @Override void process(FailedMessage failedMessage); }### Answer: @Test public void successfullyProcessExistingFailedMessage() { underTest.process(failedMessage); verify(failedMessageDao).update(failedMessage); }
### Question: UniqueJmsMessageIdPredicate implements Predicate<FailedMessage> { @Override public boolean test(FailedMessage failedMessage) { return failedMessageSearchService.search(searchMatchingAllCriteria() .withBroker(failedMessage.getDestination().getBrokerName()) .withJmsMessageId(failedMessage.getJmsMessageId()) .build() ).isEmpty(); } UniqueJmsMessageIdPredicate(FailedMessageSearchService failedMessageSearchService); @Override boolean test(FailedMessage failedMessage); }### Answer: @Test public void predicateReturnsTrueIfSearchFindsAResult() { when(destination.getBrokerName()).thenReturn(BROKER_NAME); when(failedMessage.getDestination()).thenReturn(destination); when(failedMessage.getJmsMessageId()).thenReturn(JMS_MESSAGE_ID); when(failedMessageSearchService.search(any(SearchFailedMessageRequest.class))).thenReturn(Collections.emptySet()); assertThat(underTest.test(failedMessage), is(true)); verify(failedMessageSearchService).search(argThat(aSearchRequestMatchingAllCriteria() .withBroker(BROKER_NAME) .withJmsMessageId(JMS_MESSAGE_ID))); } @Test public void predicateReturnsFalseIfSearchFindsAResult() { when(destination.getBrokerName()).thenReturn(BROKER_NAME); when(failedMessage.getDestination()).thenReturn(destination); when(failedMessage.getJmsMessageId()).thenReturn(JMS_MESSAGE_ID); when(failedMessageSearchService.search(any(SearchFailedMessageRequest.class))).thenReturn(singleton(mock(FailedMessage.class))); assertThat(underTest.test(failedMessage), is(false)); verify(failedMessageSearchService).search(argThat(aSearchRequestMatchingAllCriteria() .withBroker(BROKER_NAME) .withJmsMessageId(JMS_MESSAGE_ID))); }
### Question: PropertiesConverter implements ObjectConverter<Map<String, Object>, String> { @Override public Map<String, Object> convertToObject(String value) { if (value == null) { return Collections.emptyMap(); } try { return objectMapper.readValue(value, new TypeReference<Map<String, Object>>() {}); } catch (IOException e) { LOGGER.error("Could read the following properties: " + value, e); } return Collections.emptyMap(); } PropertiesConverter(ObjectMapper objectMapper); @Override Map<String, Object> convertToObject(String value); @Override String convertFromObject(Map<String, Object> item); }### Answer: @Test public void nullPropertiesReturnsANewHashMap() { assertThat(underTest.convertToObject(null), is(equalTo(new HashMap<>()))); } @Test public void nullValueIsReturnedIfTheJsonCannotBeRead() throws IOException { when(objectMapper.readValue(any(String.class), any(TypeReference.class))).thenThrow(IOException.class); assertThat(new PropertiesConverter(objectMapper).convertToObject("foo"), is(Collections.emptyMap())); }
### Question: PropertiesConverter implements ObjectConverter<Map<String, Object>, String> { @Override public String convertFromObject(Map<String, Object> item) { if (item == null) { return null; } try { return objectMapper.writeValueAsString(item); } catch (JsonProcessingException e) { LOGGER.error("Could not convert the following Map: " + item, e); } return null; } PropertiesConverter(ObjectMapper objectMapper); @Override Map<String, Object> convertToObject(String value); @Override String convertFromObject(Map<String, Object> item); }### Answer: @Test public void convertingNullMapToStringReturnsNull() { assertThat(underTest.convertFromObject(null), is(nullValue())); } @Test public void nullValueIsReturnedIfTheMapCannotBeParsed() throws Exception { when(objectMapper.writeValueAsString(singletonMap("foo", "bar"))).thenThrow(JsonProcessingException.class); assertThat(new PropertiesConverter(objectMapper).convertFromObject(singletonMap("foo", "bar")), is(nullValue())); }
### Question: InstantAsDateTimeCodec implements Codec<Instant> { @Override public void encode(BsonWriter writer, Instant value, EncoderContext encoderContext) { writer.writeDateTime(value.toEpochMilli()); } @Override void encode(BsonWriter writer, Instant value, EncoderContext encoderContext); @Override Instant decode(BsonReader reader, DecoderContext decoderContext); @Override Class<Instant> getEncoderClass(); }### Answer: @Test public void encode() { underTest.encode(bsonWriter, AN_INSTANT, encoderContext); verify(bsonWriter).writeDateTime(EPOCH_MILLI); }
### Question: StatusHistoryResponse { public StatusHistoryResponse(@JsonProperty("status") FailedMessageStatus status, @JsonProperty("effectiveDateTime") Instant effectiveDateTime) { this.status = status; this.effectiveDateTime = effectiveDateTime; } StatusHistoryResponse(@JsonProperty("status") FailedMessageStatus status, @JsonProperty("effectiveDateTime") Instant effectiveDateTime); FailedMessageStatus getStatus(); Instant getEffectiveDateTime(); @Override String toString(); }### Answer: @Test public void statusHistoryResponseTest() { assertThat(underTest, is(statusHistoryResponse().withStatus(FAILED).withEffectiveDateTime(NOW))); } @Test public void serialiseAndDeserialiseObject() throws IOException { final String json = OBJECT_MAPPER.writeValueAsString(underTest); assertThat(OBJECT_MAPPER.readValue(json, StatusHistoryResponse.class), is(statusHistoryResponse().withStatus(FAILED).withEffectiveDateTime(NOW))); }
### Question: CreateFailedMessageRequest { CreateFailedMessageRequest(@JsonProperty("failedMessageId") FailedMessageId failedMessageId, @JsonProperty("brokerName") String brokerName, @JsonProperty("destinationName") String destination, @JsonProperty("sentAt") Instant sentAt, @JsonProperty("failedAt") Instant failedAt, @JsonProperty("content") String content, @JsonProperty("properties") Map<String, Object> properties, @JsonProperty("labels") Set<String> labels) { this.failedMessageId = failedMessageId; this.brokerName = brokerName; this.destination = destination; this.sentAt = sentAt; this.failedAt = failedAt; this.content = content; this.properties = properties; this.labels = labels; } CreateFailedMessageRequest(@JsonProperty("failedMessageId") FailedMessageId failedMessageId, @JsonProperty("brokerName") String brokerName, @JsonProperty("destinationName") String destination, @JsonProperty("sentAt") Instant sentAt, @JsonProperty("failedAt") Instant failedAt, @JsonProperty("content") String content, @JsonProperty("properties") Map<String, Object> properties, @JsonProperty("labels") Set<String> labels); static CreateFailedMessageRequestBuilder newCreateFailedMessageRequest(); FailedMessageId getFailedMessageId(); String getBrokerName(); String getDestinationName(); Instant getSentAt(); Instant getFailedAt(); String getContent(); Map<String, Object> getProperties(); Set<String> getLabels(); }### Answer: @Test public void attemptingToSetNullPropertiesCreatesAnEmptyMap() { final CreateFailedMessageRequest createFailedMessageRequest = createFailedMessageRequestBuilder .withProperties(null) .build(); assertThat(createFailedMessageRequest, is(createFailedMessageRequest().withProperties(equalTo(emptyMap())))); } @Test public void attemptingToSetNullLabelsCreatesAnEmptySet() { final CreateFailedMessageRequest createFailedMessageRequest = createFailedMessageRequestBuilder .withLabels(null) .build(); assertThat(createFailedMessageRequest, is(createFailedMessageRequest().withLabels(emptyIterable()))); } @Test public void addProperties() { final CreateFailedMessageRequest createFailedMessageRequest = createFailedMessageRequestBuilder .withProperties(Collections.singletonMap("foo", "bar")) .withProperty("ham", "eggs") .build(); assertThat(createFailedMessageRequest, is(createFailedMessageRequest() .withProperties(allOf(Matchers.hasEntry("foo", "bar"), Matchers.hasEntry("ham", "eggs"))))); } @Test public void addLabels() { final CreateFailedMessageRequest createFailedMessageRequest = createFailedMessageRequestBuilder .withLabels(Collections.singleton("foo")) .withLabel("bar") .build(); assertThat(createFailedMessageRequest, is(createFailedMessageRequest() .withLabels(containsInAnyOrder("foo", "bar")))); }
### Question: SearchFailedMessageRequest { public static SearchFailedMessageRequestBuilder searchMatchingAllCriteria() { return new SearchFailedMessageRequestBuilder(AND); } private SearchFailedMessageRequest(@JsonProperty("broker") Optional<String> broker, @JsonProperty("destination") Optional<String> destination, @JsonProperty("statuses") Set<FailedMessageStatus> statuses, @JsonProperty("content") Optional<String> content, @JsonProperty("jmsMessageId") Optional<String> jmsMessageId, @JsonProperty("operator") Operator operator); static SearchFailedMessageRequestBuilder searchMatchingAllCriteria(); static SearchFailedMessageRequestBuilder searchMatchingAnyCriteria(); Optional<String> getBroker(); Optional<String> getDestination(); Set<FailedMessageStatus> getStatuses(); Optional<String> getContent(); Optional<String> getJmsMessageId(); Operator getOperator(); @Override String toString(); }### Answer: @Test public void serialiseAndDeserialiseWithOptionalFieldsMissing() throws Exception { String json = OBJECT_MAPPER.writeValueAsString( SearchFailedMessageRequest.searchMatchingAllCriteria() .withStatus(FAILED) .build()); assertThat(OBJECT_MAPPER.readValue(json, SearchFailedMessageRequest.class), is( aSearchRequestMatchingAllCriteria() .withBroker(equalTo(Optional.empty())) .withDestination(equalTo(Optional.empty())) .withStatusMatcher(contains(FAILED)) .withNoJmsMessageId() )); } @Test public void serialiseAndDeserialiseWithAllFieldsPopulated() throws Exception { String json = OBJECT_MAPPER.writeValueAsString( SearchFailedMessageRequest.searchMatchingAllCriteria() .withBroker("broker") .withDestination("queue") .withStatus(FAILED) .withJmsMessageId("ID:localhost.localdomain-46765-1518703251379-5:1:1:1:1") .build()); assertThat(OBJECT_MAPPER.readValue(json, SearchFailedMessageRequest.class), is( aSearchRequestMatchingAllCriteria() .withBroker(equalTo(Optional.of("broker"))) .withDestination(equalTo(Optional.of("queue"))) .withStatusMatcher(contains(FAILED)) .withJmsMessageId("ID:localhost.localdomain-46765-1518703251379-5:1:1:1:1") )); }
### Question: RemoveFailedMessageService { public void removeFailedMessages() { try { logger.info("Attempting to remove FailedMessages"); final long count = failedMessageDao.removeFailedMessages(); logger.info("Successfully removed {} messages", count); } catch (Exception e) { logger.error("Could not remove messages", e); } } RemoveFailedMessageService(FailedMessageDao failedMessageDao); RemoveFailedMessageService(FailedMessageDao failedMessageDao, Logger logger); void removeFailedMessages(); }### Answer: @Test public void removeDelegatesToTheDao() { when(failedMessageDao.removeFailedMessages()).thenReturn(NUMBER_OF_MESSAGES_REMOVED); underTest.removeFailedMessages(); verify(failedMessageDao).removeFailedMessages(); } @Test public void exceptionsAreSwallowedAndLogged() { when(failedMessageDao.removeFailedMessages()).thenThrow(exception); underTest.removeFailedMessages(); verify(logger).error("Could not remove messages", exception); }
### Question: InstantAsDateTimeCodec implements Codec<Instant> { @Override public Instant decode(BsonReader reader, DecoderContext decoderContext) { return Instant.ofEpochMilli(reader.readDateTime()); } @Override void encode(BsonWriter writer, Instant value, EncoderContext encoderContext); @Override Instant decode(BsonReader reader, DecoderContext decoderContext); @Override Class<Instant> getEncoderClass(); }### Answer: @Test public void decode() { when(bsonReader.readDateTime()).thenReturn(EPOCH_MILLI); assertThat(underTest.decode(bsonReader, decoderContext), equalTo(AN_INSTANT)); }
### Question: ResendFailedMessageResource implements ResendFailedMessageClient { @Override public void resendFailedMessage(FailedMessageId failedMessageId) { failedMessageService.update(failedMessageId, statusUpdateRequest(RESEND)); } ResendFailedMessageResource(FailedMessageService failedMessageService, Clock clock); @Override void resendFailedMessage(FailedMessageId failedMessageId); @Override void resendFailedMessageWithDelay(FailedMessageId failedMessageId, Duration duration); }### Answer: @Test public void successfullyMarkAMessageForResending() { underTest.resendFailedMessage(FAILED_MESSAGE_ID); verify(failedMessageService).update(eq(FAILED_MESSAGE_ID), statusUpdateRequest.capture()); assertThat(statusUpdateRequest.getValue(), aStatusUpdateRequest(RESEND)); }
### Question: ResendFailedMessageResource implements ResendFailedMessageClient { @Override public void resendFailedMessageWithDelay(FailedMessageId failedMessageId, Duration duration) { failedMessageService.update(failedMessageId, new StatusUpdateRequest(RESEND, Instant.now(clock).plus(duration))); } ResendFailedMessageResource(FailedMessageService failedMessageService, Clock clock); @Override void resendFailedMessage(FailedMessageId failedMessageId); @Override void resendFailedMessageWithDelay(FailedMessageId failedMessageId, Duration duration); }### Answer: @Test public void successfullyMarkAMessageForResendingInTheFuture() { underTest.resendFailedMessageWithDelay(FAILED_MESSAGE_ID, Duration.ofSeconds(100)); verify(failedMessageService).update(eq(FAILED_MESSAGE_ID), statusUpdateRequest.capture()); assertThat(statusUpdateRequest.getValue(), aStatusUpdateRequest(RESEND) .withUpdatedDateTime(Matchers.equalTo(NOW.plus(100, SECONDS)))); }
### Question: FailedMessageStatusHistoryResource implements FailedMessageStatusHistoryClient { @Override public List<StatusHistoryResponse> getStatusHistory(FailedMessageId failedMessageId) { final List<StatusHistoryResponse> statusHistoryResponses = new ArrayList<>(); final List<StatusHistoryEvent> statusHistory = failedMessageDao.getStatusHistory(failedMessageId); for (int i=0; i<statusHistory.size(); i++) { final FailedMessageStatus failedMessageStatus = toFailedMessageStatus(statusHistory.get(i).getStatus()); if (i+1<statusHistory.size() && failedMessageStatus.equals(toFailedMessageStatus(statusHistory.get(i+1).getStatus()))) { i++; } statusHistoryResponses.add(new StatusHistoryResponse(failedMessageStatus, statusHistory.get(i).getEffectiveDateTime())); } return statusHistoryResponses; } FailedMessageStatusHistoryResource(FailedMessageDao failedMessageDao); @Override List<StatusHistoryResponse> getStatusHistory(FailedMessageId failedMessageId); }### Answer: @Test public void failedMessageWithStatusHistoryEntries() { when(failedMessageDao.getStatusHistory(FAILED_MESSAGE_ID)).thenReturn(Arrays.asList( new StatusHistoryEvent(StatusHistoryEvent.Status.FAILED, NOW), new StatusHistoryEvent(StatusHistoryEvent.Status.SENT, NOW.plusSeconds(1)) )); assertThat(underTest.getStatusHistory(FAILED_MESSAGE_ID), contains( statusHistoryResponse().withStatus(FAILED).withEffectiveDateTime(NOW), statusHistoryResponse().withStatus(SENT).withEffectiveDateTime(NOW.plusSeconds(1)) )); } @Test public void responseOnlyContainsASingleEntryWhenFailedAndClassifiedStatusAreConcurrent() { when(failedMessageDao.getStatusHistory(FAILED_MESSAGE_ID)).thenReturn(Arrays.asList( new StatusHistoryEvent(StatusHistoryEvent.Status.FAILED, NOW), new StatusHistoryEvent(StatusHistoryEvent.Status.CLASSIFIED, NOW.plusSeconds(1)) )); assertThat(underTest.getStatusHistory(FAILED_MESSAGE_ID), contains( statusHistoryResponse().withStatus(FAILED).withEffectiveDateTime(NOW.plusSeconds(1)) )); } @Test public void singleStatusHistoryEntry() { when(failedMessageDao.getStatusHistory(FAILED_MESSAGE_ID)).thenReturn(Collections.singletonList( new StatusHistoryEvent(StatusHistoryEvent.Status.CLASSIFIED, NOW) )); assertThat(underTest.getStatusHistory(FAILED_MESSAGE_ID), contains( statusHistoryResponse().withStatus(FAILED).withEffectiveDateTime(NOW) )); }
### Question: CreateFailedMessageResource implements CreateFailedMessageClient { public void create(CreateFailedMessageRequest failedMessageRequest) { failedMessageDao.insert(failedMessageFactory.create(failedMessageRequest)); } CreateFailedMessageResource(FailedMessageFactory failedMessageFactory, FailedMessageDao failedMessageDao); void create(CreateFailedMessageRequest failedMessageRequest); }### Answer: @Test public void createFailedMessage() throws Exception { when(failedMessageFactory.create(request)).thenReturn(failedMessage); underTest.create(request); verify(failedMessageDao).insert(failedMessage); }
### Question: FailedMessageFactory { public FailedMessage create(CreateFailedMessageRequest request) { return FailedMessageBuilder.newFailedMessage() .withFailedMessageId(request.getFailedMessageId()) .withContent(request.getContent()) .withDestination(new Destination(request.getBrokerName(), ofNullable(request.getDestinationName()))) .withFailedDateTime(request.getFailedAt()) .withProperties(request.getProperties()) .withSentDateTime(request.getSentAt()) .withLabels(request.getLabels()) .build(); } FailedMessage create(CreateFailedMessageRequest request); }### Answer: @Test public void createFailedMessageFromRequest() throws Exception { FailedMessage failedMessage = underTest.create(newCreateFailedMessageRequest() .withContent("Hello World") .withBrokerName("broker") .withDestinationName("queue") .withFailedDateTime(NOW) .withFailedMessageId(FAILED_MESSAGE_ID) .withProperties(Collections.singletonMap("foo", "bar")) .withSentDateTime(NOW) .build()); assertThat(failedMessage, aFailedMessage() .withContent(equalTo("Hello World")) .withDestination(DestinationMatcher.aDestination().withBrokerName("broker").withName("queue")) .withFailedAt(equalTo(NOW)) .withFailedMessageId(equalTo(FAILED_MESSAGE_ID)) .withProperties(Matchers.hasEntry("foo", "bar")) .withSentAt(equalTo(NOW)) ); }
### Question: FailedMessageSearchResource implements SearchFailedMessageClient { @Override public FailedMessageResponse getFailedMessage(FailedMessageId failedMessageId) { return failedMessageDao.findById(failedMessageId) .filter(failedMessage -> !DELETED.equals(failedMessage.getStatus())) .map(failedMessageResponseFactory::create) .orElseThrow(() -> new NotFoundException(format("Failed Message: %s not found", failedMessageId))); } FailedMessageSearchResource(FailedMessageDao failedMessageDao, FailedMessageResponseFactory failedMessageResponseFactory, FailedMessageSearchService failedMessageSearchService, SearchFailedMessageResponseAdapter searchFailedMessageResponseAdapter); @Override FailedMessageResponse getFailedMessage(FailedMessageId failedMessageId); @Override Collection<SearchFailedMessageResponse> search(SearchFailedMessageRequest request); }### Answer: @Test public void findMessageById() { when(failedMessageDao.findById(FAILED_MESSAGE_ID)).thenReturn(Optional.of(failedMessage)); when(failedMessage.getStatus()).thenReturn(FAILED); when(failedMessageResponseFactory.create(failedMessage)).thenReturn(failedMessageResponse); assertThat(underTest.getFailedMessage(FAILED_MESSAGE_ID), is(failedMessageResponse)); } @Test public void findMessageByIdThrowsNotFoundExceptionWhenMessageDoesNotExist() { expectedException.expect(NotFoundException.class); expectedException.expectMessage("Failed Message: " + FAILED_MESSAGE_ID + " not found"); when(failedMessageDao.findById(FAILED_MESSAGE_ID)).thenReturn(Optional.empty()); underTest.getFailedMessage(FAILED_MESSAGE_ID); verifyZeroInteractions(failedMessageResponseFactory); } @Test public void findMessageByIdThrowsNotFoundExceptionWhenMessageIsDeleted() { expectedException.expect(NotFoundException.class); expectedException.expectMessage("Failed Message: " + FAILED_MESSAGE_ID + " not found"); when(failedMessageDao.findById(FAILED_MESSAGE_ID)).thenReturn(Optional.of(failedMessage)); when(failedMessage.getStatus()).thenReturn(DELETED); underTest.getFailedMessage(FAILED_MESSAGE_ID); verifyZeroInteractions(failedMessageResponseFactory); }
### Question: RemoveRecordsQueryFactory { public Document create() { return new Document() .append(STATUS_HISTORY + ".0." + STATUS, DELETED.name()) .append(STATUS_HISTORY + ".0." + EFFECTIVE_DATE_TIME, new Document(QueryOperators.LT, now().minus(7, DAYS))); } Document create(); }### Answer: @Test public void removeRecordsQueryCreatedSuccessfully() { assertThat(underTest.create(), allOf( hasField(STATUS_HISTORY + ".0." + STATUS, equalTo(StatusHistoryEvent.Status.DELETED.name())), hasField(STATUS_HISTORY + ".0." + EFFECTIVE_DATE_TIME, hasField(QueryOperators.LT, notNullValue(Instant.class))) )); }
### Question: FailedMessageSearchResource implements SearchFailedMessageClient { @Override public Collection<SearchFailedMessageResponse> search(SearchFailedMessageRequest request) { return failedMessageSearchService.search(request) .stream() .map(searchFailedMessageResponseAdapter::toResponse) .collect(Collectors.toList()); } FailedMessageSearchResource(FailedMessageDao failedMessageDao, FailedMessageResponseFactory failedMessageResponseFactory, FailedMessageSearchService failedMessageSearchService, SearchFailedMessageResponseAdapter searchFailedMessageResponseAdapter); @Override FailedMessageResponse getFailedMessage(FailedMessageId failedMessageId); @Override Collection<SearchFailedMessageResponse> search(SearchFailedMessageRequest request); }### Answer: @Test public void validSearch() { FailedMessage failedMessage = mock(FailedMessage.class); SearchFailedMessageResponse searchFailedMessageResponse = mock(SearchFailedMessageResponse.class); SearchFailedMessageRequest searchFailedMessageRequest = mock(SearchFailedMessageRequest.class); when(searchFailedMessageRequest.getBroker()).thenReturn(Optional.of("broker")); when(failedMessageSearchService.search(searchFailedMessageRequest)).thenReturn(singletonList(failedMessage)); when(searchFailedMessageResponseAdapter.toResponse(failedMessage)).thenReturn(searchFailedMessageResponse); final Collection<SearchFailedMessageResponse> results = underTest.search(searchFailedMessageRequest); assertThat(results, contains(searchFailedMessageResponse)); verify(failedMessageSearchService).search(Mockito.refEq(searchFailedMessageRequest)); }
### Question: UpdateFailedMessageResource implements UpdateFailedMessageClient { @Override public void update(FailedMessageId failedMessageId, FailedMessageUpdateRequest failedMessageUpdateRequest) { failedMessageService.update(failedMessageId, failedMessageUpdateRequest.getUpdateRequests()); } UpdateFailedMessageResource(FailedMessageService failedMessageService); @Override void update(FailedMessageId failedMessageId, FailedMessageUpdateRequest failedMessageUpdateRequest); }### Answer: @Test public void resourceDelegatesToTheFailedMessageService() { underTest.update(FAILED_MESSAGE_ID, FailedMessageUpdateRequest.aNewFailedMessageUpdateRequest().withUpdateRequest(updateRequest).build()); verify(failedMessageService).update(FAILED_MESSAGE_ID, Collections.singletonList(updateRequest)); }
### Question: MessageTextExtractor { public String extractText(Message message) { if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; try { return textMessage.getText(); } catch (JMSException e) { String errorMsg = String.format("Failed to extract the text from TextMessage: %s", textMessage.toString()); LOGGER.error(errorMsg, e); throw new RuntimeException(errorMsg, e); } } else { String errorMsg = String.format("Expected TextMessage received: %s", message.getClass().getName()); LOGGER.error(errorMsg); throw new RuntimeException(errorMsg); } } String extractText(Message message); }### Answer: @Test public void extractTextFromMessage() throws Exception { TextMessage textMessage = mock(TextMessage.class); when(textMessage.getText()).thenReturn("Text"); assertThat(underTest.extractText(textMessage), is("Text")); } @Test public void throwsExceptionIfNotTextMessage() throws Exception { expectedException.expect(RuntimeException.class); expectedException.expectMessage(allOf(startsWith("Expected TextMessage received:"), containsString("javax.jms.BytesMessage"))); underTest.extractText(mock(BytesMessage.class)); }
### Question: FailedMessageTransformer implements JmsMessageTransformer<TextMessage, FailedMessage> { @Override public void transform(TextMessage textMessage, FailedMessage data) throws JMSException { textMessage.setText(data.getContent()); Map<String, Object> properties = data.getProperties(); properties.keySet().forEach(key -> { try { textMessage.setObjectProperty(key, properties.get(key)); } catch (JMSException ignore) { LOGGER.warn("Could not add property: '{}' when sending FailedMessage: {}", key, data.getFailedMessageId()); } }); textMessage.setStringProperty(FailedMessageId.FAILED_MESSAGE_ID, data.getFailedMessageId().toString()); } @Override void transform(TextMessage textMessage, FailedMessage data); }### Answer: @Test public void processingContinuesObjectPropertyCannotBeWritten() throws JMSException { when(failedMessage.getContent()).thenReturn("content"); when(failedMessage.getProperties()).thenReturn(ImmutableMap.of("foo", "bar", "ham", "eggs")); when(failedMessage.getFailedMessageId()).thenReturn(FAILED_MESSAGE_ID); doThrow(new JMSException("Arrrghhhhh")).when(textMessage).setObjectProperty("foo", "bar"); underTest.transform(textMessage, failedMessage); verify(textMessage).setText("content"); verify(textMessage).setObjectProperty("foo", "bar"); verify(textMessage).setObjectProperty("ham", "eggs"); verify(textMessage).setStringProperty(FailedMessageId.FAILED_MESSAGE_ID, FAILED_MESSAGE_ID.toString()); }
### Question: FailedMessageListener implements MessageListener { @Override public void onMessage(Message message) { try { LOGGER.debug("Received message: {} with CorrelationId: {}", message.getJMSMessageID(), message.getJMSCorrelationID()); failedMessageProcessor.process(failedMessageFactory.createFailedMessage(message)); } catch (JMSException e) { LOGGER.error("Could not read jmsMessageId or correlationId", e); } } FailedMessageListener(FailedMessageFactory failedMessageFactory, FailedMessageProcessor failedMessageProcessor); @Override void onMessage(Message message); }### Answer: @Test public void processMessageSuccessfully() throws Exception { when(failedMessageFactory.createFailedMessage(message)).thenReturn(failedMessage); underTest.onMessage(message); verify(failedMessageProcessor).process(failedMessage); } @Test public void exceptionIsThrownRetrievingTheJMSMessageId() throws JMSException { when(message.getJMSMessageID()).thenThrow(JMSException.class); underTest.onMessage(message); verifyZeroInteractions(failedMessageProcessor); }
### Question: FailedMessageConverter implements DocumentWithIdConverter<FailedMessage, FailedMessageId> { @Override public Document createId(FailedMessageId failedMessageId) { return new Document("_id", failedMessageId.getId().toString()); } FailedMessageConverter(DocumentConverter<Destination> destinationDocumentConverter, DocumentConverter<StatusHistoryEvent> statusHistoryEventDocumentConverter, ObjectConverter<Map<String, Object>, String> propertiesMongoMapper); @Override FailedMessage convertToObject(Document document); StatusHistoryEvent getStatusHistoryEvent(Document document); FailedMessageId getFailedMessageId(Document document); Destination getDestination(Document document); String getContent(Document document); Instant getFailedDateTime(Document document); Instant getSentDateTime(Document document); @Override Document convertFromObject(FailedMessage item); Document convertForUpdate(FailedMessage item); @Override Document createId(FailedMessageId failedMessageId); static final String DESTINATION; static final String SENT_DATE_TIME; static final String FAILED_DATE_TIME; static final String CONTENT; static final String PROPERTIES; static final String STATUS_HISTORY; static final String LABELS; static final String JMS_MESSAGE_ID; }### Answer: @Test public void createId() { assertThat(underTest.createId(FAILED_MESSAGE_ID), equalTo(new Document("_id", FAILED_MESSAGE_ID_AS_STRING))); }
### Question: CircularBuffer { public int size() { return currentSize; } CircularBuffer(int size); void enqueue(T item); int size(); @SuppressWarnings("unchecked") T getItem(int index); }### Answer: @Test public void size() { CircularBuffer<Integer> queue = new CircularBuffer<>(2); assertEquals(0, queue.size()); queue.enqueue(0); queue.enqueue(1); assertEquals(2, queue.size()); queue.enqueue(3); assertEquals(2, queue.size()); }
### Question: CircularBuffer { @SuppressWarnings("unchecked") public T getItem(int index) { int target = head - index; if (target < 0) target = queue.length + target; return (T) queue[target]; } CircularBuffer(int size); void enqueue(T item); int size(); @SuppressWarnings("unchecked") T getItem(int index); }### Answer: @Test public void getItem() { CircularBuffer<Integer> queue = new CircularBuffer<>(3); queue.enqueue(0); assertEquals((Integer) 0, queue.getItem(0)); queue.enqueue(1); assertEquals((Integer) 1, queue.getItem(0)); assertEquals((Integer) 0, queue.getItem(1)); queue.enqueue(2); assertEquals((Integer) 2, queue.getItem(0)); assertEquals((Integer) 1, queue.getItem(1)); assertEquals((Integer) 0, queue.getItem(2)); queue.enqueue(3); assertEquals((Integer) 3, queue.getItem(0)); assertEquals((Integer) 2, queue.getItem(1)); assertEquals((Integer) 1, queue.getItem(2)); }
### Question: KubeCloudInstanceImpl implements KubeCloudInstance { @NotNull @Override public Date getStartedTime() { final PodStatus podStatus = myPod.getStatus(); if(podStatus == null) return myCreationTime; try { final List<PodCondition> podConditions = podStatus.getConditions(); if (podConditions != null && !podConditions.isEmpty()) { for (PodCondition podCondition : podConditions) { if (PodConditionType.valueOf(podCondition.getType()) == PodConditionType.Ready) return myPodTransitionTimeFormat.parse(podCondition.getLastTransitionTime()); } } String startTime = podStatus.getStartTime(); return !StringUtil.isEmpty(startTime) ? myPodStartTimeFormat.parse(startTime) : myCreationTime; } catch (ParseException e) { throw new KubeCloudException("Failed to get instance start date", e); } } KubeCloudInstanceImpl(@NotNull KubeCloudImage kubeCloudImage, @NotNull Pod pod); @NotNull @Override String getInstanceId(); @NotNull @Override String getName(); @NotNull @Override String getImageId(); @NotNull @Override KubeCloudImage getImage(); @Override void setStatus(final InstanceStatus status); @NotNull @Override Date getStartedTime(); @Nullable @Override String getNetworkIdentity(); @NotNull @Override InstanceStatus getStatus(); @Nullable @Override CloudErrorInfo getErrorInfo(); @Override boolean containsAgent(@NotNull AgentDescription agentDescription); void updateState(@NotNull Pod actualPod); @Override void setError(@Nullable final CloudErrorInfo errorInfo); @Override @Nullable String getPVCName(); }### Answer: @Test public void testGetStartedTime() throws Exception { KubeCloudImage image = m.mock(KubeCloudImage.class); ObjectMeta metadata = new ObjectMeta(); metadata.setName("foo"); Pod pod = new Pod("1.0", "kind", metadata, new PodSpec(), new PodStatusBuilder().withStartTime("2017-06-12T22:59Z").build()); m.checking(new Expectations(){{ allowing(myApi).getPodStatus(with("foo")); will(returnValue(pod.getStatus())); }}); KubeCloudInstanceImpl instance = new KubeCloudInstanceImpl(image, pod); Date startedTime = instance.getStartedTime(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); assertEquals("2017-06-12T22:59Z", dateFormat.format(startedTime)); }
### Question: KubeCloudClient implements CloudClientEx { @Override public boolean isInitialized() { return true; } KubeCloudClient(@NotNull KubeApiConnector apiConnector, @Nullable String serverUuid, @NotNull String cloudProfileId, @NotNull List<KubeCloudImage> images, @NotNull KubeCloudClientParametersImpl kubeClientParams, @NotNull KubeBackgroundUpdater updater, @NotNull BuildAgentPodTemplateProviders podTemplateProviders, @Nullable ExecutorService executorService, @NotNull KubePodNameGenerator nameGenerator); @Override boolean isInitialized(); @Override void dispose(); @NotNull @Override CloudInstance startNewInstance(@NotNull CloudImage cloudImage, @NotNull CloudInstanceUserData cloudInstanceUserData); @Override void restartInstance(@NotNull CloudInstance cloudInstance); @Override void terminateInstance(@NotNull CloudInstance cloudInstance); @Nullable @Override CloudImage findImageById(@NotNull String imageId); @Nullable @Override CloudInstance findInstanceByAgent(@NotNull AgentDescription agentDescription); @NotNull @Override Collection<? extends CloudImage> getImages(); @Nullable @Override CloudErrorInfo getErrorInfo(); @Override boolean canStartNewInstance(@NotNull CloudImage cloudImage); @Nullable @Override String generateAgentName(@NotNull AgentDescription agentDescription); String getProfileId(); }### Answer: @Test public void testIsInitialized() throws Exception { assertTrue(createClient(Collections.emptyList()).isInitialized()); }
### Question: BoltOptions implements AutoCloseable { @Override public void close() { BoltNative.BoltDBOptions_Free(objectId); } BoltOptions(); BoltOptions(long timeout); BoltOptions(long timeout, boolean noGrowSync, boolean readOnly, int mmapFlags, int initialMmapSize); @Override void close(); }### Answer: @Test public void create_and_free() { BoltOptions boltOptions = new BoltOptions(); boltOptions.close(); }
### Question: BoltBucket implements AutoCloseable { public void delete(byte[] key) { Error.ByValue error = BoltNative.BoltDBBucket_Delete(objectId, key, key.length); error.checkError(); } BoltBucket(long objectId); @Override void close(); byte[] get(byte[] key); void put(byte[] key, byte[] value); void delete(byte[] key); BoltBucket createBucket(byte[] name); BoltBucket createBucketIfNotExists(byte[] name); void deleteBucket(byte[] name); BoltBucket getBucket(byte[] name); BoltCursor createCursor(); long nextSequenceId(); BoltBucketStats getStats(); }### Answer: @Test public void delete() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try(BoltBucket bucket = boltTransaction.createBucket("test".getBytes())) { byte[] key = "foo".getBytes(); byte[] value = "bar".getBytes(); bucket.put(key, value); bucket.delete(key); byte[] getValue = bucket.get(key); Assert.assertNull(getValue); } }); } }
### Question: BoltBucket implements AutoCloseable { public BoltBucket createBucket(byte[] name) { Result.ByValue result = BoltNative.BoltDBBucket_CreateBucket(objectId, name, name.length); result.checkError(); return new BoltBucket(result.objectId); } BoltBucket(long objectId); @Override void close(); byte[] get(byte[] key); void put(byte[] key, byte[] value); void delete(byte[] key); BoltBucket createBucket(byte[] name); BoltBucket createBucketIfNotExists(byte[] name); void deleteBucket(byte[] name); BoltBucket getBucket(byte[] name); BoltCursor createCursor(); long nextSequenceId(); BoltBucketStats getStats(); }### Answer: @Test @SuppressWarnings("EmptyTryBlock") public void create_bucket() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try(BoltBucket parentBucket = boltTransaction.createBucket("parent".getBytes())) { try(BoltBucket ignored = parentBucket.createBucket("test".getBytes())) {} } }); } } @Test(expected = BoltException.class) public void create_bucket_with_empty_name() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltBucket parentBucket = boltTransaction.createBucket("parent".getBytes())) { parentBucket.createBucket("".getBytes()); } }); } } @Test(expected = BoltException.class) @SuppressWarnings("EmptyTryBlock") public void create_bucket_twice() throws IOException { byte[] bucketName = "test".getBytes(); try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltBucket parentBucket = boltTransaction.createBucket("parent".getBytes())) { try (BoltBucket ignored = parentBucket.createBucket(bucketName)) {} parentBucket.createBucket(bucketName); } }); } }
### Question: BoltTransaction { public void commit() { Error.ByValue error = BoltNative.BoltDBTransaction_Commit(objectId); error.checkError(); } BoltTransaction(long objectId); void commit(); void rollback(); int getId(); long getDatabaseSize(); BoltBucket createBucket(byte[] name); BoltBucket createBucketIfNotExists(byte[] name); void deleteBucket(byte[] name); BoltBucket getBucket(byte[] name); BoltCursor createCursor(); BoltTransactionStats getStats(); }### Answer: @Test public void commit_transaction() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { BoltTransaction boltTransaction = bolt.begin(true); boltTransaction.commit(); } }
### Question: BoltTransaction { public void rollback() { Error.ByValue error = BoltNative.BoltDBTransaction_Rollback(objectId); error.checkError(); } BoltTransaction(long objectId); void commit(); void rollback(); int getId(); long getDatabaseSize(); BoltBucket createBucket(byte[] name); BoltBucket createBucketIfNotExists(byte[] name); void deleteBucket(byte[] name); BoltBucket getBucket(byte[] name); BoltCursor createCursor(); BoltTransactionStats getStats(); }### Answer: @Test public void rollback_transaction() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { BoltTransaction boltTransaction = bolt.begin(true); boltTransaction.rollback(); } }
### Question: BoltTransaction { public int getId() { return BoltNative.BoltDBTransaction_GetId(objectId); } BoltTransaction(long objectId); void commit(); void rollback(); int getId(); long getDatabaseSize(); BoltBucket createBucket(byte[] name); BoltBucket createBucketIfNotExists(byte[] name); void deleteBucket(byte[] name); BoltBucket getBucket(byte[] name); BoltCursor createCursor(); BoltTransactionStats getStats(); }### Answer: @Test public void get_transaction_id() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> Assert.assertTrue(boltTransaction.getId() > 0)); } }
### Question: BoltTransaction { public long getDatabaseSize() { return BoltNative.BoltDBTransaction_Size(objectId); } BoltTransaction(long objectId); void commit(); void rollback(); int getId(); long getDatabaseSize(); BoltBucket createBucket(byte[] name); BoltBucket createBucketIfNotExists(byte[] name); void deleteBucket(byte[] name); BoltBucket getBucket(byte[] name); BoltCursor createCursor(); BoltTransactionStats getStats(); }### Answer: @Test public void get_database_size() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> Assert.assertTrue(boltTransaction.getDatabaseSize() > 0)); } }
### Question: BoltTransaction { public BoltBucket createBucket(byte[] name) { Result.ByValue result = BoltNative.BoltDBTransaction_CreateBucket(objectId, name, name.length); result.checkError(); return new BoltBucket(result.objectId); } BoltTransaction(long objectId); void commit(); void rollback(); int getId(); long getDatabaseSize(); BoltBucket createBucket(byte[] name); BoltBucket createBucketIfNotExists(byte[] name); void deleteBucket(byte[] name); BoltBucket getBucket(byte[] name); BoltCursor createCursor(); BoltTransactionStats getStats(); }### Answer: @Test @SuppressWarnings("EmptyTryBlock") public void create_bucket() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltBucket ignored = boltTransaction.createBucket("test".getBytes())) {} }); } } @Test(expected = BoltException.class) public void create_bucket_with_empty_name() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> boltTransaction.createBucket("".getBytes())); } } @Test(expected = BoltException.class) @SuppressWarnings("EmptyTryBlock") public void create_bucket_twice() throws IOException { byte[] bucketName = "test".getBytes(); try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltBucket ignored = boltTransaction.createBucket(bucketName)) {} boltTransaction.createBucket(bucketName); }); } }
### Question: BoltCursor implements AutoCloseable { public BoltKeyValue first() { try(KeyValue.ByValue keyValue = BoltNative.BoltDBCursor_First(objectId)) { return keyValue.hasKeyValue() ? new BoltKeyValue(keyValue.getKey(), keyValue.getValue()) : null; } } BoltCursor(long objectId); @Override void close(); BoltKeyValue first(); BoltKeyValue last(); BoltKeyValue next(); BoltKeyValue prev(); BoltKeyValue seek(byte[] seek); void delete(); }### Answer: @Test public void move_first() throws IOException { byte[] bucketName = "test".getBytes(); try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltBucket ignored = boltTransaction.createBucket(bucketName)) { try (BoltCursor cursor = boltTransaction.createCursor()) { BoltKeyValue first = cursor.first(); Assert.assertNotNull(first); Assert.assertArrayEquals(bucketName, first.getKey()); Assert.assertNull(first.getValue()); } } }); } } @Test public void move_first_when_not_exists() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltCursor cursor = boltTransaction.createCursor()) { BoltKeyValue first = cursor.first(); Assert.assertNull(first); } }); } }
### Question: BoltTransaction { public BoltBucket createBucketIfNotExists(byte[] name) { Result.ByValue result = BoltNative.BoltDBTransaction_CreateBucketIfNotExists(objectId, name, name.length); result.checkError(); return new BoltBucket(result.objectId); } BoltTransaction(long objectId); void commit(); void rollback(); int getId(); long getDatabaseSize(); BoltBucket createBucket(byte[] name); BoltBucket createBucketIfNotExists(byte[] name); void deleteBucket(byte[] name); BoltBucket getBucket(byte[] name); BoltCursor createCursor(); BoltTransactionStats getStats(); }### Answer: @Test @SuppressWarnings("EmptyTryBlock") public void create_bucket_if_not_exists() throws IOException { byte[] bucketName = "test".getBytes(); try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltBucket ignored = boltTransaction.createBucketIfNotExists(bucketName)) {} }); } } @Test(expected = BoltException.class) public void create_bucket_if_not_exists_with_empty_name() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> boltTransaction.createBucketIfNotExists("".getBytes())); } } @Test @SuppressWarnings("EmptyTryBlock") public void create_bucket_if_not_exists_twice() throws IOException { byte[] bucketName = "test".getBytes(); try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltBucket ignored = boltTransaction.createBucketIfNotExists(bucketName)) {} try (BoltBucket ignored = boltTransaction.createBucketIfNotExists(bucketName)) {} }); } }
### Question: BoltTransaction { public void deleteBucket(byte[] name) { Error.ByValue error = BoltNative.BoltDBTransaction_DeleteBucket(objectId, name, name.length); error.checkError(); } BoltTransaction(long objectId); void commit(); void rollback(); int getId(); long getDatabaseSize(); BoltBucket createBucket(byte[] name); BoltBucket createBucketIfNotExists(byte[] name); void deleteBucket(byte[] name); BoltBucket getBucket(byte[] name); BoltCursor createCursor(); BoltTransactionStats getStats(); }### Answer: @Test(expected = BoltException.class) public void delete_bucket_with_empty_name() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> boltTransaction.deleteBucket("".getBytes())); } }
### Question: BoltTransaction { public BoltBucket getBucket(byte[] name) { Result.ByValue result = BoltNative.BoltDBTransaction_Bucket(objectId, name, name.length); result.checkError(); return new BoltBucket(result.objectId); } BoltTransaction(long objectId); void commit(); void rollback(); int getId(); long getDatabaseSize(); BoltBucket createBucket(byte[] name); BoltBucket createBucketIfNotExists(byte[] name); void deleteBucket(byte[] name); BoltBucket getBucket(byte[] name); BoltCursor createCursor(); BoltTransactionStats getStats(); }### Answer: @Test(expected = BoltException.class) public void get_bucket_with_empty_name() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> boltTransaction.getBucket("".getBytes())); } }
### Question: BoltTransaction { public BoltCursor createCursor() { long cursorObjectId = BoltNative.BoltDBTransaction_Cursor(objectId); return new BoltCursor(cursorObjectId); } BoltTransaction(long objectId); void commit(); void rollback(); int getId(); long getDatabaseSize(); BoltBucket createBucket(byte[] name); BoltBucket createBucketIfNotExists(byte[] name); void deleteBucket(byte[] name); BoltBucket getBucket(byte[] name); BoltCursor createCursor(); BoltTransactionStats getStats(); }### Answer: @Test @SuppressWarnings("EmptyTryBlock") public void create_cursor() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltCursor ignored = boltTransaction.createCursor()) {} }); } }
### Question: Bolt implements AutoCloseable { public void close() { BoltNative.BoltDB_Close(objectId); } Bolt(String databaseFileName); Bolt(String databaseFileName, EnumSet<BoltFileMode> fileMode); Bolt(String databaseFileName, EnumSet<BoltFileMode> fileMode, BoltOptions options); void close(); BoltTransaction begin(boolean writeable); void update(Consumer<BoltTransaction> callback); void view(Consumer<BoltTransaction> callback); BoltStats getStats(); static void init(); }### Answer: @Test public void open_and_close() throws IOException { Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath()); bolt.close(); } @Test public void open_from_other_thread() { Thread thread = new Thread(() -> { try { Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath()); bolt.close(); } catch (Throwable e) { Assert.fail("Bolt adapter can't be created in other thread."); } }); thread.run(); } @Test @Ignore public void open_and_close_with_file_mode() throws IOException { Path databaseFileName = Paths.get(testFolder.getRoot().getAbsolutePath(), "bd.bolt"); EnumSet<BoltFileMode> fileMode = EnumSet.of(BoltFileMode.USER_READ, BoltFileMode.USER_WRITE, BoltFileMode.GROUP_READ, BoltFileMode.GROUP_WRITE); Bolt bolt = new Bolt(databaseFileName.toString(), fileMode); bolt.close(); Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(databaseFileName); Assert.assertEquals(4, permissions.size()); Assert.assertTrue(permissions.containsAll(Arrays.asList(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, PosixFilePermission.GROUP_READ, PosixFilePermission.GROUP_WRITE))); } @Test public void open_and_close_with_options() throws IOException { try(BoltOptions boltOptions = new BoltOptions()) { Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath(), BoltFileMode.DEFAULT, boltOptions); bolt.close(); } }
### Question: Bolt implements AutoCloseable { public void update(Consumer<BoltTransaction> callback) { BoltTransaction transaction = begin(true); try { callback.accept(transaction); transaction.commit(); } catch (Throwable ex) { transaction.rollback(); throw ex; } } Bolt(String databaseFileName); Bolt(String databaseFileName, EnumSet<BoltFileMode> fileMode); Bolt(String databaseFileName, EnumSet<BoltFileMode> fileMode, BoltOptions options); void close(); BoltTransaction begin(boolean writeable); void update(Consumer<BoltTransaction> callback); void view(Consumer<BoltTransaction> callback); BoltStats getStats(); static void init(); }### Answer: @Test public void open_update_transaction() throws IOException { String databaseFileName = testFolder.newFile().getAbsolutePath(); try(Bolt bolt = new Bolt(databaseFileName)) { final boolean[] wasInTransaction = {false}; bolt.update(boltTransaction -> { Assert.assertNotNull(boltTransaction); wasInTransaction[0] = true; }); Assert.assertTrue(wasInTransaction[0]); } }
### Question: Bolt implements AutoCloseable { public void view(Consumer<BoltTransaction> callback) { BoltTransaction transaction = begin(false); try { callback.accept(transaction); } finally { transaction.rollback(); } } Bolt(String databaseFileName); Bolt(String databaseFileName, EnumSet<BoltFileMode> fileMode); Bolt(String databaseFileName, EnumSet<BoltFileMode> fileMode, BoltOptions options); void close(); BoltTransaction begin(boolean writeable); void update(Consumer<BoltTransaction> callback); void view(Consumer<BoltTransaction> callback); BoltStats getStats(); static void init(); }### Answer: @Test public void open_view_transaction() throws IOException { String databaseFileName = testFolder.newFile().getAbsolutePath(); try(Bolt bolt = new Bolt(databaseFileName)) { final boolean[] wasInTransaction = {false}; bolt.view(boltTransaction -> { Assert.assertNotNull(boltTransaction); wasInTransaction[0] = true; }); Assert.assertTrue(wasInTransaction[0]); } }
### Question: BoltCursor implements AutoCloseable { public BoltKeyValue last() { try(KeyValue.ByValue keyValue = BoltNative.BoltDBCursor_Last(objectId)) { return keyValue.hasKeyValue() ? new BoltKeyValue(keyValue.getKey(), keyValue.getValue()) : null; } } BoltCursor(long objectId); @Override void close(); BoltKeyValue first(); BoltKeyValue last(); BoltKeyValue next(); BoltKeyValue prev(); BoltKeyValue seek(byte[] seek); void delete(); }### Answer: @Test public void move_last() throws IOException { byte[] bucketName = "test".getBytes(); try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltBucket ignored = boltTransaction.createBucket(bucketName)) { try (BoltCursor cursor = boltTransaction.createCursor()) { BoltKeyValue last = cursor.last(); Assert.assertNotNull(last); Assert.assertArrayEquals(bucketName, last.getKey()); Assert.assertNull(last.getValue()); } } }); } } @Test public void move_last_when_not_exists() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltCursor cursor = boltTransaction.createCursor()) { BoltKeyValue last = cursor.last(); Assert.assertNull(last); } }); } }
### Question: BoltCursor implements AutoCloseable { public BoltKeyValue next() { try(KeyValue.ByValue keyValue = BoltNative.BoltDBCursor_Next(objectId)) { return keyValue.hasKeyValue() ? new BoltKeyValue(keyValue.getKey(), keyValue.getValue()) : null; } } BoltCursor(long objectId); @Override void close(); BoltKeyValue first(); BoltKeyValue last(); BoltKeyValue next(); BoltKeyValue prev(); BoltKeyValue seek(byte[] seek); void delete(); }### Answer: @Test public void move_next() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltBucket ignored1 = boltTransaction.createBucket("test1".getBytes())) { try (BoltBucket ignored2 = boltTransaction.createBucket("test2".getBytes())) { try (BoltCursor cursor = boltTransaction.createCursor()) { BoltKeyValue next = cursor.next(); Assert.assertNull(next); } } } }); } }
### Question: BoltCursor implements AutoCloseable { public BoltKeyValue prev() { try(KeyValue.ByValue keyValue = BoltNative.BoltDBCursor_Prev(objectId)) { return keyValue.hasKeyValue() ? new BoltKeyValue(keyValue.getKey(), keyValue.getValue()) : null; } } BoltCursor(long objectId); @Override void close(); BoltKeyValue first(); BoltKeyValue last(); BoltKeyValue next(); BoltKeyValue prev(); BoltKeyValue seek(byte[] seek); void delete(); }### Answer: @Test public void move_prev() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltBucket ignored1 = boltTransaction.createBucket("test1".getBytes())) { try (BoltBucket ignored2 = boltTransaction.createBucket("test2".getBytes())) { try (BoltCursor cursor = boltTransaction.createCursor()) { BoltKeyValue prev = cursor.prev(); Assert.assertNull(prev); } } } }); } }
### Question: BoltCursor implements AutoCloseable { public BoltKeyValue seek(byte[] seek) { try(KeyValue.ByValue keyValue = BoltNative.BoltDBCursor_Seek(objectId, seek, seek.length)) { return keyValue.hasKeyValue() ? new BoltKeyValue(keyValue.getKey(), keyValue.getValue()) : null; } } BoltCursor(long objectId); @Override void close(); BoltKeyValue first(); BoltKeyValue last(); BoltKeyValue next(); BoltKeyValue prev(); BoltKeyValue seek(byte[] seek); void delete(); }### Answer: @Test public void seek() throws IOException { byte[] bucketName1 = "test1".getBytes(); byte[] bucketName2 = "test2".getBytes(); byte[] bucketName3 = "test3".getBytes(); try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try(BoltBucket ignored1 = boltTransaction.createBucket(bucketName1)) { try(BoltBucket ignored2 = boltTransaction.createBucket(bucketName2)) { try(BoltBucket ignored3 = boltTransaction.createBucket(bucketName3)) { try (BoltCursor cursor = boltTransaction.createCursor()) { BoltKeyValue seek = cursor.seek(bucketName2); Assert.assertNotNull(seek); Assert.assertArrayEquals(bucketName2, seek.getKey()); } } } } }); } } @Test public void seek_to_unknown_position() throws IOException { byte[] bucketName1 = "test1".getBytes(); byte[] bucketName2 = "test2".getBytes(); try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try(BoltBucket ignored = boltTransaction.createBucket(bucketName1)) { try (BoltCursor cursor = boltTransaction.createCursor()) { BoltKeyValue seek = cursor.seek(bucketName2); Assert.assertNull(seek); } } }); } }
### Question: BoltCursor implements AutoCloseable { public void delete() { Error.ByValue error = BoltNative.BoltDBCursor_Delete(objectId); error.checkError(); } BoltCursor(long objectId); @Override void close(); BoltKeyValue first(); BoltKeyValue last(); BoltKeyValue next(); BoltKeyValue prev(); BoltKeyValue seek(byte[] seek); void delete(); }### Answer: @Test public void delete() throws IOException { byte[] bucketName = "test".getBytes(); try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try(BoltBucket bucket = boltTransaction.createBucket(bucketName)) { byte[] key = "key".getBytes(); byte[] value = "value".getBytes(); bucket.put(key, value); try (BoltCursor cursor = bucket.createCursor()) { cursor.first(); cursor.delete(); } } }); } }
### Question: FlowsApi { public Flow create(CreateFlowRequest body) throws ApiException { ApiResponse<Flow> resp = createWithHttpInfo(body); return resp.getData(); } FlowsApi(); FlowsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); Flow create(CreateFlowRequest body); ApiResponse<Flow> createWithHttpInfo(CreateFlowRequest body); com.squareup.okhttp.Call createAsync(CreateFlowRequest body, final ApiCallback<Flow> callback); String delete(String id); ApiResponse<String> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<String> callback); Flow deploy(String id); ApiResponse<Flow> deployWithHttpInfo(String id); com.squareup.okhttp.Call deployAsync(String id, final ApiCallback<Flow> callback); Flow get(String id); ApiResponse<Flow> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<Flow> callback); DAGStepRef getModel(String id); ApiResponse<DAGStepRef> getModelWithHttpInfo(String id); com.squareup.okhttp.Call getModelAsync(String id, final ApiCallback<DAGStepRef> callback); List<Flow> list(); ApiResponse<List<Flow>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<Flow>> callback); String saveModel(String id, Object body); ApiResponse<String> saveModelWithHttpInfo(String id, Object body); com.squareup.okhttp.Call saveModelAsync(String id, Object body, final ApiCallback<String> callback); String validate(Object body); ApiResponse<String> validateWithHttpInfo(Object body); com.squareup.okhttp.Call validateAsync(Object body, final ApiCallback<String> callback); }### Answer: @Test public void createTest() throws ApiException { CreateFlowRequest body = null; Flow response = api.create(body); }
### Question: FunctionsApi { public KFFunction create(CreateFunctionRequest body) throws ApiException { ApiResponse<KFFunction> resp = createWithHttpInfo(body); return resp.getData(); } FunctionsApi(); FunctionsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); KFFunction create(CreateFunctionRequest body); ApiResponse<KFFunction> createWithHttpInfo(CreateFunctionRequest body); com.squareup.okhttp.Call createAsync(CreateFunctionRequest body, final ApiCallback<KFFunction> callback); void delete(String id); ApiResponse<Void> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<Void> callback); KFFunction get(String id); ApiResponse<KFFunction> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<KFFunction> callback); Service getService(String id); ApiResponse<Service> getServiceWithHttpInfo(String id); com.squareup.okhttp.Call getServiceAsync(String id, final ApiCallback<Service> callback); Version getVersion(String id, String versionId); ApiResponse<Version> getVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call getVersionAsync(String id, String versionId, final ApiCallback<Version> callback); List<Version> getVersions(String id); ApiResponse<List<Version>> getVersionsWithHttpInfo(String id); com.squareup.okhttp.Call getVersionsAsync(String id, final ApiCallback<List<Version>> callback); List<KFFunction> list(); ApiResponse<List<KFFunction>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<KFFunction>> callback); ProxyResponse proxy(String id, String body); ApiResponse<ProxyResponse> proxyWithHttpInfo(String id, String body); com.squareup.okhttp.Call proxyAsync(String id, String body, final ApiCallback<ProxyResponse> callback); Map<String, String> setVersion(String id, String versionId); ApiResponse<Map<String, String>> setVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call setVersionAsync(String id, String versionId, final ApiCallback<Map<String, String>> callback); }### Answer: @Test public void createTest() throws ApiException { CreateFunctionRequest body = null; KFFunction response = api.create(body); }
### Question: FunctionsApi { public void delete(String id) throws ApiException { deleteWithHttpInfo(id); } FunctionsApi(); FunctionsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); KFFunction create(CreateFunctionRequest body); ApiResponse<KFFunction> createWithHttpInfo(CreateFunctionRequest body); com.squareup.okhttp.Call createAsync(CreateFunctionRequest body, final ApiCallback<KFFunction> callback); void delete(String id); ApiResponse<Void> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<Void> callback); KFFunction get(String id); ApiResponse<KFFunction> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<KFFunction> callback); Service getService(String id); ApiResponse<Service> getServiceWithHttpInfo(String id); com.squareup.okhttp.Call getServiceAsync(String id, final ApiCallback<Service> callback); Version getVersion(String id, String versionId); ApiResponse<Version> getVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call getVersionAsync(String id, String versionId, final ApiCallback<Version> callback); List<Version> getVersions(String id); ApiResponse<List<Version>> getVersionsWithHttpInfo(String id); com.squareup.okhttp.Call getVersionsAsync(String id, final ApiCallback<List<Version>> callback); List<KFFunction> list(); ApiResponse<List<KFFunction>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<KFFunction>> callback); ProxyResponse proxy(String id, String body); ApiResponse<ProxyResponse> proxyWithHttpInfo(String id, String body); com.squareup.okhttp.Call proxyAsync(String id, String body, final ApiCallback<ProxyResponse> callback); Map<String, String> setVersion(String id, String versionId); ApiResponse<Map<String, String>> setVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call setVersionAsync(String id, String versionId, final ApiCallback<Map<String, String>> callback); }### Answer: @Test public void deleteTest() throws ApiException { String id = null; api.delete(id); }
### Question: FunctionsApi { public KFFunction get(String id) throws ApiException { ApiResponse<KFFunction> resp = getWithHttpInfo(id); return resp.getData(); } FunctionsApi(); FunctionsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); KFFunction create(CreateFunctionRequest body); ApiResponse<KFFunction> createWithHttpInfo(CreateFunctionRequest body); com.squareup.okhttp.Call createAsync(CreateFunctionRequest body, final ApiCallback<KFFunction> callback); void delete(String id); ApiResponse<Void> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<Void> callback); KFFunction get(String id); ApiResponse<KFFunction> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<KFFunction> callback); Service getService(String id); ApiResponse<Service> getServiceWithHttpInfo(String id); com.squareup.okhttp.Call getServiceAsync(String id, final ApiCallback<Service> callback); Version getVersion(String id, String versionId); ApiResponse<Version> getVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call getVersionAsync(String id, String versionId, final ApiCallback<Version> callback); List<Version> getVersions(String id); ApiResponse<List<Version>> getVersionsWithHttpInfo(String id); com.squareup.okhttp.Call getVersionsAsync(String id, final ApiCallback<List<Version>> callback); List<KFFunction> list(); ApiResponse<List<KFFunction>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<KFFunction>> callback); ProxyResponse proxy(String id, String body); ApiResponse<ProxyResponse> proxyWithHttpInfo(String id, String body); com.squareup.okhttp.Call proxyAsync(String id, String body, final ApiCallback<ProxyResponse> callback); Map<String, String> setVersion(String id, String versionId); ApiResponse<Map<String, String>> setVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call setVersionAsync(String id, String versionId, final ApiCallback<Map<String, String>> callback); }### Answer: @Test public void getTest() throws ApiException { String id = null; KFFunction response = api.get(id); }
### Question: FunctionsApi { public Service getService(String id) throws ApiException { ApiResponse<Service> resp = getServiceWithHttpInfo(id); return resp.getData(); } FunctionsApi(); FunctionsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); KFFunction create(CreateFunctionRequest body); ApiResponse<KFFunction> createWithHttpInfo(CreateFunctionRequest body); com.squareup.okhttp.Call createAsync(CreateFunctionRequest body, final ApiCallback<KFFunction> callback); void delete(String id); ApiResponse<Void> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<Void> callback); KFFunction get(String id); ApiResponse<KFFunction> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<KFFunction> callback); Service getService(String id); ApiResponse<Service> getServiceWithHttpInfo(String id); com.squareup.okhttp.Call getServiceAsync(String id, final ApiCallback<Service> callback); Version getVersion(String id, String versionId); ApiResponse<Version> getVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call getVersionAsync(String id, String versionId, final ApiCallback<Version> callback); List<Version> getVersions(String id); ApiResponse<List<Version>> getVersionsWithHttpInfo(String id); com.squareup.okhttp.Call getVersionsAsync(String id, final ApiCallback<List<Version>> callback); List<KFFunction> list(); ApiResponse<List<KFFunction>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<KFFunction>> callback); ProxyResponse proxy(String id, String body); ApiResponse<ProxyResponse> proxyWithHttpInfo(String id, String body); com.squareup.okhttp.Call proxyAsync(String id, String body, final ApiCallback<ProxyResponse> callback); Map<String, String> setVersion(String id, String versionId); ApiResponse<Map<String, String>> setVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call setVersionAsync(String id, String versionId, final ApiCallback<Map<String, String>> callback); }### Answer: @Test public void getServiceTest() throws ApiException { String id = null; Service response = api.getService(id); }
### Question: FunctionsApi { public Version getVersion(String id, String versionId) throws ApiException { ApiResponse<Version> resp = getVersionWithHttpInfo(id, versionId); return resp.getData(); } FunctionsApi(); FunctionsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); KFFunction create(CreateFunctionRequest body); ApiResponse<KFFunction> createWithHttpInfo(CreateFunctionRequest body); com.squareup.okhttp.Call createAsync(CreateFunctionRequest body, final ApiCallback<KFFunction> callback); void delete(String id); ApiResponse<Void> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<Void> callback); KFFunction get(String id); ApiResponse<KFFunction> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<KFFunction> callback); Service getService(String id); ApiResponse<Service> getServiceWithHttpInfo(String id); com.squareup.okhttp.Call getServiceAsync(String id, final ApiCallback<Service> callback); Version getVersion(String id, String versionId); ApiResponse<Version> getVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call getVersionAsync(String id, String versionId, final ApiCallback<Version> callback); List<Version> getVersions(String id); ApiResponse<List<Version>> getVersionsWithHttpInfo(String id); com.squareup.okhttp.Call getVersionsAsync(String id, final ApiCallback<List<Version>> callback); List<KFFunction> list(); ApiResponse<List<KFFunction>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<KFFunction>> callback); ProxyResponse proxy(String id, String body); ApiResponse<ProxyResponse> proxyWithHttpInfo(String id, String body); com.squareup.okhttp.Call proxyAsync(String id, String body, final ApiCallback<ProxyResponse> callback); Map<String, String> setVersion(String id, String versionId); ApiResponse<Map<String, String>> setVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call setVersionAsync(String id, String versionId, final ApiCallback<Map<String, String>> callback); }### Answer: @Test public void getVersionTest() throws ApiException { String id = null; String versionId = null; Version response = api.getVersion(id, versionId); }
### Question: FunctionsApi { public List<Version> getVersions(String id) throws ApiException { ApiResponse<List<Version>> resp = getVersionsWithHttpInfo(id); return resp.getData(); } FunctionsApi(); FunctionsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); KFFunction create(CreateFunctionRequest body); ApiResponse<KFFunction> createWithHttpInfo(CreateFunctionRequest body); com.squareup.okhttp.Call createAsync(CreateFunctionRequest body, final ApiCallback<KFFunction> callback); void delete(String id); ApiResponse<Void> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<Void> callback); KFFunction get(String id); ApiResponse<KFFunction> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<KFFunction> callback); Service getService(String id); ApiResponse<Service> getServiceWithHttpInfo(String id); com.squareup.okhttp.Call getServiceAsync(String id, final ApiCallback<Service> callback); Version getVersion(String id, String versionId); ApiResponse<Version> getVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call getVersionAsync(String id, String versionId, final ApiCallback<Version> callback); List<Version> getVersions(String id); ApiResponse<List<Version>> getVersionsWithHttpInfo(String id); com.squareup.okhttp.Call getVersionsAsync(String id, final ApiCallback<List<Version>> callback); List<KFFunction> list(); ApiResponse<List<KFFunction>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<KFFunction>> callback); ProxyResponse proxy(String id, String body); ApiResponse<ProxyResponse> proxyWithHttpInfo(String id, String body); com.squareup.okhttp.Call proxyAsync(String id, String body, final ApiCallback<ProxyResponse> callback); Map<String, String> setVersion(String id, String versionId); ApiResponse<Map<String, String>> setVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call setVersionAsync(String id, String versionId, final ApiCallback<Map<String, String>> callback); }### Answer: @Test public void getVersionsTest() throws ApiException { String id = null; List<Version> response = api.getVersions(id); }
### Question: FunctionsApi { public List<KFFunction> list() throws ApiException { ApiResponse<List<KFFunction>> resp = listWithHttpInfo(); return resp.getData(); } FunctionsApi(); FunctionsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); KFFunction create(CreateFunctionRequest body); ApiResponse<KFFunction> createWithHttpInfo(CreateFunctionRequest body); com.squareup.okhttp.Call createAsync(CreateFunctionRequest body, final ApiCallback<KFFunction> callback); void delete(String id); ApiResponse<Void> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<Void> callback); KFFunction get(String id); ApiResponse<KFFunction> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<KFFunction> callback); Service getService(String id); ApiResponse<Service> getServiceWithHttpInfo(String id); com.squareup.okhttp.Call getServiceAsync(String id, final ApiCallback<Service> callback); Version getVersion(String id, String versionId); ApiResponse<Version> getVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call getVersionAsync(String id, String versionId, final ApiCallback<Version> callback); List<Version> getVersions(String id); ApiResponse<List<Version>> getVersionsWithHttpInfo(String id); com.squareup.okhttp.Call getVersionsAsync(String id, final ApiCallback<List<Version>> callback); List<KFFunction> list(); ApiResponse<List<KFFunction>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<KFFunction>> callback); ProxyResponse proxy(String id, String body); ApiResponse<ProxyResponse> proxyWithHttpInfo(String id, String body); com.squareup.okhttp.Call proxyAsync(String id, String body, final ApiCallback<ProxyResponse> callback); Map<String, String> setVersion(String id, String versionId); ApiResponse<Map<String, String>> setVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call setVersionAsync(String id, String versionId, final ApiCallback<Map<String, String>> callback); }### Answer: @Test public void listTest() throws ApiException { List<KFFunction> response = api.list(); }
### Question: FunctionsApi { public ProxyResponse proxy(String id, String body) throws ApiException { ApiResponse<ProxyResponse> resp = proxyWithHttpInfo(id, body); return resp.getData(); } FunctionsApi(); FunctionsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); KFFunction create(CreateFunctionRequest body); ApiResponse<KFFunction> createWithHttpInfo(CreateFunctionRequest body); com.squareup.okhttp.Call createAsync(CreateFunctionRequest body, final ApiCallback<KFFunction> callback); void delete(String id); ApiResponse<Void> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<Void> callback); KFFunction get(String id); ApiResponse<KFFunction> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<KFFunction> callback); Service getService(String id); ApiResponse<Service> getServiceWithHttpInfo(String id); com.squareup.okhttp.Call getServiceAsync(String id, final ApiCallback<Service> callback); Version getVersion(String id, String versionId); ApiResponse<Version> getVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call getVersionAsync(String id, String versionId, final ApiCallback<Version> callback); List<Version> getVersions(String id); ApiResponse<List<Version>> getVersionsWithHttpInfo(String id); com.squareup.okhttp.Call getVersionsAsync(String id, final ApiCallback<List<Version>> callback); List<KFFunction> list(); ApiResponse<List<KFFunction>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<KFFunction>> callback); ProxyResponse proxy(String id, String body); ApiResponse<ProxyResponse> proxyWithHttpInfo(String id, String body); com.squareup.okhttp.Call proxyAsync(String id, String body, final ApiCallback<ProxyResponse> callback); Map<String, String> setVersion(String id, String versionId); ApiResponse<Map<String, String>> setVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call setVersionAsync(String id, String versionId, final ApiCallback<Map<String, String>> callback); }### Answer: @Test public void proxyTest() throws ApiException { String id = null; String body = null; ProxyResponse response = api.proxy(id, body); }
### Question: FunctionsApi { public Map<String, String> setVersion(String id, String versionId) throws ApiException { ApiResponse<Map<String, String>> resp = setVersionWithHttpInfo(id, versionId); return resp.getData(); } FunctionsApi(); FunctionsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); KFFunction create(CreateFunctionRequest body); ApiResponse<KFFunction> createWithHttpInfo(CreateFunctionRequest body); com.squareup.okhttp.Call createAsync(CreateFunctionRequest body, final ApiCallback<KFFunction> callback); void delete(String id); ApiResponse<Void> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<Void> callback); KFFunction get(String id); ApiResponse<KFFunction> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<KFFunction> callback); Service getService(String id); ApiResponse<Service> getServiceWithHttpInfo(String id); com.squareup.okhttp.Call getServiceAsync(String id, final ApiCallback<Service> callback); Version getVersion(String id, String versionId); ApiResponse<Version> getVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call getVersionAsync(String id, String versionId, final ApiCallback<Version> callback); List<Version> getVersions(String id); ApiResponse<List<Version>> getVersionsWithHttpInfo(String id); com.squareup.okhttp.Call getVersionsAsync(String id, final ApiCallback<List<Version>> callback); List<KFFunction> list(); ApiResponse<List<KFFunction>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<KFFunction>> callback); ProxyResponse proxy(String id, String body); ApiResponse<ProxyResponse> proxyWithHttpInfo(String id, String body); com.squareup.okhttp.Call proxyAsync(String id, String body, final ApiCallback<ProxyResponse> callback); Map<String, String> setVersion(String id, String versionId); ApiResponse<Map<String, String>> setVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call setVersionAsync(String id, String versionId, final ApiCallback<Map<String, String>> callback); }### Answer: @Test public void setVersionTest() throws ApiException { String id = null; String versionId = null; Map<String, String> response = api.setVersion(id, versionId); }
### Question: FlowsApi { public String delete(String id) throws ApiException { ApiResponse<String> resp = deleteWithHttpInfo(id); return resp.getData(); } FlowsApi(); FlowsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); Flow create(CreateFlowRequest body); ApiResponse<Flow> createWithHttpInfo(CreateFlowRequest body); com.squareup.okhttp.Call createAsync(CreateFlowRequest body, final ApiCallback<Flow> callback); String delete(String id); ApiResponse<String> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<String> callback); Flow deploy(String id); ApiResponse<Flow> deployWithHttpInfo(String id); com.squareup.okhttp.Call deployAsync(String id, final ApiCallback<Flow> callback); Flow get(String id); ApiResponse<Flow> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<Flow> callback); DAGStepRef getModel(String id); ApiResponse<DAGStepRef> getModelWithHttpInfo(String id); com.squareup.okhttp.Call getModelAsync(String id, final ApiCallback<DAGStepRef> callback); List<Flow> list(); ApiResponse<List<Flow>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<Flow>> callback); String saveModel(String id, Object body); ApiResponse<String> saveModelWithHttpInfo(String id, Object body); com.squareup.okhttp.Call saveModelAsync(String id, Object body, final ApiCallback<String> callback); String validate(Object body); ApiResponse<String> validateWithHttpInfo(Object body); com.squareup.okhttp.Call validateAsync(Object body, final ApiCallback<String> callback); }### Answer: @Test public void deleteTest() throws ApiException { String id = null; String response = api.delete(id); }
### Question: FlowsApi { public Flow deploy(String id) throws ApiException { ApiResponse<Flow> resp = deployWithHttpInfo(id); return resp.getData(); } FlowsApi(); FlowsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); Flow create(CreateFlowRequest body); ApiResponse<Flow> createWithHttpInfo(CreateFlowRequest body); com.squareup.okhttp.Call createAsync(CreateFlowRequest body, final ApiCallback<Flow> callback); String delete(String id); ApiResponse<String> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<String> callback); Flow deploy(String id); ApiResponse<Flow> deployWithHttpInfo(String id); com.squareup.okhttp.Call deployAsync(String id, final ApiCallback<Flow> callback); Flow get(String id); ApiResponse<Flow> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<Flow> callback); DAGStepRef getModel(String id); ApiResponse<DAGStepRef> getModelWithHttpInfo(String id); com.squareup.okhttp.Call getModelAsync(String id, final ApiCallback<DAGStepRef> callback); List<Flow> list(); ApiResponse<List<Flow>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<Flow>> callback); String saveModel(String id, Object body); ApiResponse<String> saveModelWithHttpInfo(String id, Object body); com.squareup.okhttp.Call saveModelAsync(String id, Object body, final ApiCallback<String> callback); String validate(Object body); ApiResponse<String> validateWithHttpInfo(Object body); com.squareup.okhttp.Call validateAsync(Object body, final ApiCallback<String> callback); }### Answer: @Test public void deployTest() throws ApiException { String id = null; Flow response = api.deploy(id); }
### Question: FlowsApi { public Flow get(String id) throws ApiException { ApiResponse<Flow> resp = getWithHttpInfo(id); return resp.getData(); } FlowsApi(); FlowsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); Flow create(CreateFlowRequest body); ApiResponse<Flow> createWithHttpInfo(CreateFlowRequest body); com.squareup.okhttp.Call createAsync(CreateFlowRequest body, final ApiCallback<Flow> callback); String delete(String id); ApiResponse<String> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<String> callback); Flow deploy(String id); ApiResponse<Flow> deployWithHttpInfo(String id); com.squareup.okhttp.Call deployAsync(String id, final ApiCallback<Flow> callback); Flow get(String id); ApiResponse<Flow> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<Flow> callback); DAGStepRef getModel(String id); ApiResponse<DAGStepRef> getModelWithHttpInfo(String id); com.squareup.okhttp.Call getModelAsync(String id, final ApiCallback<DAGStepRef> callback); List<Flow> list(); ApiResponse<List<Flow>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<Flow>> callback); String saveModel(String id, Object body); ApiResponse<String> saveModelWithHttpInfo(String id, Object body); com.squareup.okhttp.Call saveModelAsync(String id, Object body, final ApiCallback<String> callback); String validate(Object body); ApiResponse<String> validateWithHttpInfo(Object body); com.squareup.okhttp.Call validateAsync(Object body, final ApiCallback<String> callback); }### Answer: @Test public void getTest() throws ApiException { String id = null; Flow response = api.get(id); }
### Question: FlowsApi { public DAGStepRef getModel(String id) throws ApiException { ApiResponse<DAGStepRef> resp = getModelWithHttpInfo(id); return resp.getData(); } FlowsApi(); FlowsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); Flow create(CreateFlowRequest body); ApiResponse<Flow> createWithHttpInfo(CreateFlowRequest body); com.squareup.okhttp.Call createAsync(CreateFlowRequest body, final ApiCallback<Flow> callback); String delete(String id); ApiResponse<String> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<String> callback); Flow deploy(String id); ApiResponse<Flow> deployWithHttpInfo(String id); com.squareup.okhttp.Call deployAsync(String id, final ApiCallback<Flow> callback); Flow get(String id); ApiResponse<Flow> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<Flow> callback); DAGStepRef getModel(String id); ApiResponse<DAGStepRef> getModelWithHttpInfo(String id); com.squareup.okhttp.Call getModelAsync(String id, final ApiCallback<DAGStepRef> callback); List<Flow> list(); ApiResponse<List<Flow>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<Flow>> callback); String saveModel(String id, Object body); ApiResponse<String> saveModelWithHttpInfo(String id, Object body); com.squareup.okhttp.Call saveModelAsync(String id, Object body, final ApiCallback<String> callback); String validate(Object body); ApiResponse<String> validateWithHttpInfo(Object body); com.squareup.okhttp.Call validateAsync(Object body, final ApiCallback<String> callback); }### Answer: @Test public void getModelTest() throws ApiException { String id = null; DAGStepRef response = api.getModel(id); }
### Question: FlowsApi { public List<Flow> list() throws ApiException { ApiResponse<List<Flow>> resp = listWithHttpInfo(); return resp.getData(); } FlowsApi(); FlowsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); Flow create(CreateFlowRequest body); ApiResponse<Flow> createWithHttpInfo(CreateFlowRequest body); com.squareup.okhttp.Call createAsync(CreateFlowRequest body, final ApiCallback<Flow> callback); String delete(String id); ApiResponse<String> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<String> callback); Flow deploy(String id); ApiResponse<Flow> deployWithHttpInfo(String id); com.squareup.okhttp.Call deployAsync(String id, final ApiCallback<Flow> callback); Flow get(String id); ApiResponse<Flow> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<Flow> callback); DAGStepRef getModel(String id); ApiResponse<DAGStepRef> getModelWithHttpInfo(String id); com.squareup.okhttp.Call getModelAsync(String id, final ApiCallback<DAGStepRef> callback); List<Flow> list(); ApiResponse<List<Flow>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<Flow>> callback); String saveModel(String id, Object body); ApiResponse<String> saveModelWithHttpInfo(String id, Object body); com.squareup.okhttp.Call saveModelAsync(String id, Object body, final ApiCallback<String> callback); String validate(Object body); ApiResponse<String> validateWithHttpInfo(Object body); com.squareup.okhttp.Call validateAsync(Object body, final ApiCallback<String> callback); }### Answer: @Test public void listTest() throws ApiException { List<Flow> response = api.list(); }
### Question: FlowsApi { public String saveModel(String id, Object body) throws ApiException { ApiResponse<String> resp = saveModelWithHttpInfo(id, body); return resp.getData(); } FlowsApi(); FlowsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); Flow create(CreateFlowRequest body); ApiResponse<Flow> createWithHttpInfo(CreateFlowRequest body); com.squareup.okhttp.Call createAsync(CreateFlowRequest body, final ApiCallback<Flow> callback); String delete(String id); ApiResponse<String> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<String> callback); Flow deploy(String id); ApiResponse<Flow> deployWithHttpInfo(String id); com.squareup.okhttp.Call deployAsync(String id, final ApiCallback<Flow> callback); Flow get(String id); ApiResponse<Flow> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<Flow> callback); DAGStepRef getModel(String id); ApiResponse<DAGStepRef> getModelWithHttpInfo(String id); com.squareup.okhttp.Call getModelAsync(String id, final ApiCallback<DAGStepRef> callback); List<Flow> list(); ApiResponse<List<Flow>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<Flow>> callback); String saveModel(String id, Object body); ApiResponse<String> saveModelWithHttpInfo(String id, Object body); com.squareup.okhttp.Call saveModelAsync(String id, Object body, final ApiCallback<String> callback); String validate(Object body); ApiResponse<String> validateWithHttpInfo(Object body); com.squareup.okhttp.Call validateAsync(Object body, final ApiCallback<String> callback); }### Answer: @Test public void saveModelTest() throws ApiException { String id = null; Object body = null; String response = api.saveModel(id, body); }
### Question: FlowsApi { public String validate(Object body) throws ApiException { ApiResponse<String> resp = validateWithHttpInfo(body); return resp.getData(); } FlowsApi(); FlowsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); Flow create(CreateFlowRequest body); ApiResponse<Flow> createWithHttpInfo(CreateFlowRequest body); com.squareup.okhttp.Call createAsync(CreateFlowRequest body, final ApiCallback<Flow> callback); String delete(String id); ApiResponse<String> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<String> callback); Flow deploy(String id); ApiResponse<Flow> deployWithHttpInfo(String id); com.squareup.okhttp.Call deployAsync(String id, final ApiCallback<Flow> callback); Flow get(String id); ApiResponse<Flow> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<Flow> callback); DAGStepRef getModel(String id); ApiResponse<DAGStepRef> getModelWithHttpInfo(String id); com.squareup.okhttp.Call getModelAsync(String id, final ApiCallback<DAGStepRef> callback); List<Flow> list(); ApiResponse<List<Flow>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<Flow>> callback); String saveModel(String id, Object body); ApiResponse<String> saveModelWithHttpInfo(String id, Object body); com.squareup.okhttp.Call saveModelAsync(String id, Object body, final ApiCallback<String> callback); String validate(Object body); ApiResponse<String> validateWithHttpInfo(Object body); com.squareup.okhttp.Call validateAsync(Object body, final ApiCallback<String> callback); }### Answer: @Test public void validateTest() throws ApiException { Object body = null; String response = api.validate(body); }
### Question: ConnectorsApi { public Connector get(String id) throws ApiException { ApiResponse<Connector> resp = getWithHttpInfo(id); return resp.getData(); } ConnectorsApi(); ConnectorsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); Connector get(String id); ApiResponse<Connector> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<Connector> callback); List<Connector> list(); ApiResponse<List<Connector>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<Connector>> callback); }### Answer: @Test public void getTest() throws ApiException { String id = null; Connector response = api.get(id); }
### Question: ConnectorsApi { public List<Connector> list() throws ApiException { ApiResponse<List<Connector>> resp = listWithHttpInfo(); return resp.getData(); } ConnectorsApi(); ConnectorsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); Connector get(String id); ApiResponse<Connector> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<Connector> callback); List<Connector> list(); ApiResponse<List<Connector>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<Connector>> callback); }### Answer: @Test public void listTest() throws ApiException { List<Connector> response = api.list(); }
### Question: TableStats { public double estimateScanCost() { return table.numPages() * ioCostPerPage; } TableStats(int tableid, int ioCostPerPage); static TableStats getTableStats(String tablename); static void setTableStats(String tablename, TableStats stats); static void setStatsMap(HashMap<String, TableStats> s); static Map<String, TableStats> getStatsMap(); static void computeStatistics(); double estimateScanCost(); int estimateTableCardinality(double selectivityFactor); double avgSelectivity(int field, simpledb.Predicate.Op op); double estimateSelectivity(int field, Predicate.Op op, Field constant); int totalTuples(); }### Answer: @Test public void estimateScanCostTest() throws IOException, DbException, TransactionAbortedException { Object[] ret; int[] ioCosts = new int[20]; int[] pageNums = new int[ioCosts.length]; for(int i = 0; i < ioCosts.length; ++i) { ioCosts[i] = 1; pageNums[i] = 3*(i+1); } double stats[] = getRandomTableScanCosts(pageNums, ioCosts); ret = SystemTestUtil.checkConstant(stats); Assert.assertEquals(ret[0], Boolean.FALSE); ret = SystemTestUtil.checkLinear(stats); Assert.assertEquals(ret[0], Boolean.TRUE); for(int i = 0; i < ioCosts.length; ++i) { ioCosts[i] = 10*(i + 1); pageNums[i] = 3; } stats = getRandomTableScanCosts(pageNums, ioCosts); ret = SystemTestUtil.checkConstant(stats); Assert.assertEquals(ret[0], Boolean.FALSE); ret = SystemTestUtil.checkLinear(stats); Assert.assertEquals(ret[0], Boolean.TRUE); for(int i = 0; i < ioCosts.length; ++i) { ioCosts[i] = 3*(i + 1); pageNums[i] = (i+1); } stats = getRandomTableScanCosts(pageNums, ioCosts); ret = SystemTestUtil.checkConstant(stats); Assert.assertEquals(ret[0], Boolean.FALSE); ret = SystemTestUtil.checkLinear(stats); Assert.assertEquals(ret[0], Boolean.FALSE); ret = SystemTestUtil.checkQuadratic(stats); Assert.assertEquals(ret[0], Boolean.TRUE); }
### Question: Join extends Operator { public void rewind() throws DbException, TransactionAbortedException { child1.rewind(); child2.rewind(); joinResults.rewind(); } Join(JoinPredicate p, DbIterator child1, DbIterator child2); @Override String getName(); JoinPredicate getJoinPredicate(); String getJoinField1Name(); String getJoinField2Name(); TupleDesc getTupleDesc(); void open(); void close(); void rewind(); @Override DbIterator[] getChildren(); @Override void setChildren(DbIterator[] children); static final int blockMemory; }### Answer: @Test public void rewind() throws Exception { JoinPredicate pred = new JoinPredicate(0, Predicate.Op.EQUALS, 0); Join op = new Join(pred, scan1, scan2); op.open(); while (op.hasNext()) { assertNotNull(op.next()); } assertTrue(TestUtil.checkExhausted(op)); op.rewind(); eqJoin.open(); Tuple expected = eqJoin.next(); Tuple actual = op.next(); assertTrue(TestUtil.compareTuples(expected, actual)); }
### Question: Join extends Operator { public void open() throws DbException, NoSuchElementException, TransactionAbortedException { child1.open(); child2.open(); super.open(); joinResults = blockNestedLoopJoin(); joinResults.open(); } Join(JoinPredicate p, DbIterator child1, DbIterator child2); @Override String getName(); JoinPredicate getJoinPredicate(); String getJoinField1Name(); String getJoinField2Name(); TupleDesc getTupleDesc(); void open(); void close(); void rewind(); @Override DbIterator[] getChildren(); @Override void setChildren(DbIterator[] children); static final int blockMemory; }### Answer: @Test public void gtJoin() throws Exception { JoinPredicate pred = new JoinPredicate(0, Predicate.Op.GREATER_THAN, 0); Join op = new Join(pred, scan1, scan2); op.open(); gtJoin.open(); TestUtil.matchAllTuples(gtJoin, op); } @Test public void eqJoin() throws Exception { JoinPredicate pred = new JoinPredicate(0, Predicate.Op.EQUALS, 0); Join op = new Join(pred, scan1, scan2); op.open(); eqJoin.open(); TestUtil.matchAllTuples(eqJoin, op); }
### Question: TableStats { public int estimateTableCardinality(double selectivityFactor) { return (int) Math.ceil(totalTuples() * selectivityFactor); } TableStats(int tableid, int ioCostPerPage); static TableStats getTableStats(String tablename); static void setTableStats(String tablename, TableStats stats); static void setStatsMap(HashMap<String, TableStats> s); static Map<String, TableStats> getStatsMap(); static void computeStatistics(); double estimateScanCost(); int estimateTableCardinality(double selectivityFactor); double avgSelectivity(int field, simpledb.Predicate.Op op); double estimateSelectivity(int field, Predicate.Op op, Field constant); int totalTuples(); }### Answer: @Test public void estimateTableCardinalityTest() { TableStats s = new TableStats(this.tableId, IO_COST); Assert.assertEquals(306, s.estimateTableCardinality(0.3)); Assert.assertEquals(1020, s.estimateTableCardinality(1.0)); Assert.assertEquals(0, s.estimateTableCardinality(0.0)); }
### Question: JoinOptimizer { public double estimateJoinCost(LogicalJoinNode j, int card1, int card2, double cost1, double cost2) { if (j instanceof LogicalSubplanJoinNode) { return card1 + cost1 + cost2; } else { TupleDesc desc = p.getTupleDesc(j.t1Alias); int blockSize = Join.blockMemory / desc.getSize(); int fullNum = card1 / blockSize; int left = (card1 - blockSize * fullNum) == 0 ? 0 : 1; int blockCard = fullNum + left; double cost = cost1 + blockCard * cost2 + (double) card1 * (double) card2; return cost; } } JoinOptimizer(LogicalPlan p, Vector<LogicalJoinNode> joins); static DbIterator instantiateJoin(LogicalJoinNode lj, DbIterator plan1, DbIterator plan2); double estimateJoinCost(LogicalJoinNode j, int card1, int card2, double cost1, double cost2); int estimateJoinCardinality(LogicalJoinNode j, int card1, int card2, boolean t1pkey, boolean t2pkey, Map<String, TableStats> stats); static int estimateTableJoinCardinality(Predicate.Op joinOp, String table1Alias, String table2Alias, String field1PureName, String field2PureName, int card1, int card2, boolean t1pkey, boolean t2pkey, Map<String, TableStats> stats, Map<String, Integer> tableAliasToId); @SuppressWarnings("unchecked") Set<Set<T>> enumerateSubsets(Vector<T> v, int size); Vector<LogicalJoinNode> orderJoins( HashMap<String, TableStats> stats, HashMap<String, Double> filterSelectivities, boolean explain); }### Answer: @Test public void estimateJoinCostTest() throws ParsingException { TransactionId tid = new TransactionId(); JoinOptimizer jo; Parser p = new Parser(); String t1Alia = "t1"; String t2Alia = "t2"; jo = new JoinOptimizer(p.generateLogicalPlan(tid, "SELECT * FROM " + tableName1 + " t1, " + tableName2 + " t2 WHERE t1.c1 = t2.c2;"), new Vector<LogicalJoinNode>()); LogicalJoinNode equalsJoinNode = new LogicalJoinNode(t1Alia, t2Alia, Integer.toString(1), Integer.toString(2), Predicate.Op.EQUALS); checkJoinEstimateCosts(jo, equalsJoinNode); jo = new JoinOptimizer(p.generateLogicalPlan(tid, "SELECT * FROM " + tableName1 + " t1, " + tableName2 + " t2 WHERE t1.c1 = t2.c2;"), new Vector<LogicalJoinNode>()); equalsJoinNode = new LogicalJoinNode(t2Alia, t1Alia, Integer.toString(2), Integer.toString(1), Predicate.Op.EQUALS); checkJoinEstimateCosts(jo, equalsJoinNode); jo = new JoinOptimizer(p.generateLogicalPlan(tid, "SELECT * FROM " + tableName1 + " t1, " + tableName1 + " t2 WHERE t1.c3 = t2.c4;"), new Vector<LogicalJoinNode>()); equalsJoinNode = new LogicalJoinNode(t1Alia, t1Alia, Integer.toString(3), Integer.toString(4), Predicate.Op.EQUALS); checkJoinEstimateCosts(jo, equalsJoinNode); jo = new JoinOptimizer(p.generateLogicalPlan(tid, "SELECT * FROM " + tableName2 + " t1, " + tableName2 + " t2 WHERE t1.c8 = t2.c7;"), new Vector<LogicalJoinNode>()); equalsJoinNode = new LogicalJoinNode(t2Alia, t2Alia, Integer.toString(8), Integer.toString(7), Predicate.Op.EQUALS); checkJoinEstimateCosts(jo, equalsJoinNode); }
### Question: JoinOptimizer { public int estimateJoinCardinality(LogicalJoinNode j, int card1, int card2, boolean t1pkey, boolean t2pkey, Map<String, TableStats> stats) { if (j instanceof LogicalSubplanJoinNode) { return card1; } else { return estimateTableJoinCardinality(j.p, j.t1Alias, j.t2Alias, j.f1PureName, j.f2PureName, card1, card2, t1pkey, t2pkey, stats, p.getTableAliasToIdMapping()); } } JoinOptimizer(LogicalPlan p, Vector<LogicalJoinNode> joins); static DbIterator instantiateJoin(LogicalJoinNode lj, DbIterator plan1, DbIterator plan2); double estimateJoinCost(LogicalJoinNode j, int card1, int card2, double cost1, double cost2); int estimateJoinCardinality(LogicalJoinNode j, int card1, int card2, boolean t1pkey, boolean t2pkey, Map<String, TableStats> stats); static int estimateTableJoinCardinality(Predicate.Op joinOp, String table1Alias, String table2Alias, String field1PureName, String field2PureName, int card1, int card2, boolean t1pkey, boolean t2pkey, Map<String, TableStats> stats, Map<String, Integer> tableAliasToId); @SuppressWarnings("unchecked") Set<Set<T>> enumerateSubsets(Vector<T> v, int size); Vector<LogicalJoinNode> orderJoins( HashMap<String, TableStats> stats, HashMap<String, Double> filterSelectivities, boolean explain); }### Answer: @Test public void estimateJoinCardinality() throws ParsingException { TransactionId tid = new TransactionId(); Parser p = new Parser(); JoinOptimizer j = new JoinOptimizer(p.generateLogicalPlan(tid, "SELECT * FROM " + tableName2 + " t1, " + tableName2 + " t2 WHERE t1.c8 = t2.c7;"), new Vector<LogicalJoinNode>()); double cardinality; cardinality = j.estimateJoinCardinality(new LogicalJoinNode("t1", "t2", "c"+Integer.toString(3), "c"+Integer.toString(4), Predicate.Op.EQUALS), stats1.estimateTableCardinality(0.8), stats2.estimateTableCardinality(0.2), true, false, TableStats.getStatsMap()); Assert.assertTrue(cardinality == 800 || cardinality == 2000); cardinality = j.estimateJoinCardinality(new LogicalJoinNode("t1", "t2", "c"+Integer.toString(3), "c"+Integer.toString(4), Predicate.Op.EQUALS), stats1.estimateTableCardinality(0.8), stats2.estimateTableCardinality(0.2), false, true,TableStats.getStatsMap()); Assert.assertTrue(cardinality == 800 || cardinality == 2000); }
### Question: Transaction { public void transactionComplete(boolean abort) throws IOException { if (started) { if (abort) { Database.getLogFile().logAbort(tid); } else { Database.getBufferPool().flushPages(tid); Database.getLogFile().logCommit(tid); } try { Database.getBufferPool().transactionComplete(tid, !abort); } catch (IOException e) { e.printStackTrace(); } started = false; } } Transaction(); void start(); TransactionId getId(); void commit(); void abort(); void transactionComplete(boolean abort); }### Answer: @Test public void attemptTransactionTwice() throws Exception { bp.getPage(tid1, p0, Permissions.READ_ONLY); bp.getPage(tid1, p1, Permissions.READ_WRITE); bp.transactionComplete(tid1, true); bp.getPage(tid2, p0, Permissions.READ_WRITE); bp.getPage(tid2, p0, Permissions.READ_WRITE); }
### Question: Join extends Operator { public TupleDesc getTupleDesc() { return td; } Join(JoinPredicate p, DbIterator child1, DbIterator child2); @Override String getName(); JoinPredicate getJoinPredicate(); String getJoinField1Name(); String getJoinField2Name(); TupleDesc getTupleDesc(); void open(); void close(); void rewind(); @Override DbIterator[] getChildren(); @Override void setChildren(DbIterator[] children); static final int blockMemory; }### Answer: @Test public void getTupleDesc() { JoinPredicate pred = new JoinPredicate(0, Predicate.Op.EQUALS, 0); Join op = new Join(pred, scan1, scan2); TupleDesc expected = Utility.getTupleDesc(width1 + width2); TupleDesc actual = op.getTupleDesc(); assertEquals(expected, actual); }
### Question: UserAccount extends BaseAuditableEntity implements SocialUserDetails { public boolean isAuthor(){ for (UserRoleType role : getRoles()) { if (role == UserRoleType.ROLE_AUTHOR){ return true; } } return false; } UserAccount(); UserAccount(String userId, UserRoleType[] roles); String getUserId(); void setUserId(String userId); UserRoleType[] getRoles(); void setRoles(UserRoleType[] roles); String getEmail(); void setEmail(String email); String getDisplayName(); void setDisplayName(String displayName); String getImageUrl(); void setImageUrl(String imageUrl); String getWebSite(); void setWebSite(String webSite); boolean isAccountLocked(); void setAccountLocked(boolean accountLocked); boolean isTrustedAccount(); void setTrustedAccount(boolean trustedAccount); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); @Override String getPassword(); @Override String getUsername(); boolean isAuthor(); boolean isAdmin(); void updateProfile(String displayName, String email, String webSite); @Override String toString(); }### Answer: @Test public void testIsAuthor() { UserAccount normalUser = new UserAccount(); assertFalse(normalUser.isAuthor()); UserRoleType[] roles = new UserRoleType[]{UserRoleType.ROLE_USER, UserRoleType.ROLE_AUTHOR}; UserAccount author = new UserAccount("1234", roles); assertTrue(author.isAuthor()); }
### Question: UserAccount extends BaseAuditableEntity implements SocialUserDetails { public boolean isAdmin(){ for (UserRoleType role : getRoles()) { if (role == UserRoleType.ROLE_ADMIN){ return true; } } return false; } UserAccount(); UserAccount(String userId, UserRoleType[] roles); String getUserId(); void setUserId(String userId); UserRoleType[] getRoles(); void setRoles(UserRoleType[] roles); String getEmail(); void setEmail(String email); String getDisplayName(); void setDisplayName(String displayName); String getImageUrl(); void setImageUrl(String imageUrl); String getWebSite(); void setWebSite(String webSite); boolean isAccountLocked(); void setAccountLocked(boolean accountLocked); boolean isTrustedAccount(); void setTrustedAccount(boolean trustedAccount); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); @Override String getPassword(); @Override String getUsername(); boolean isAuthor(); boolean isAdmin(); void updateProfile(String displayName, String email, String webSite); @Override String toString(); }### Answer: @Test public void testIsAdmin() { UserAccount normalUser = new UserAccount(); assertFalse(normalUser.isAdmin()); UserRoleType[] roles = new UserRoleType[]{UserRoleType.ROLE_USER, UserRoleType.ROLE_ADMIN}; UserAccount author = new UserAccount("1234", roles); assertTrue(author.isAdmin()); }
### Question: SingleEntryScope extends AbstractScope implements Scope { public <T> T call(Callable<T> toCall, Object... scopeContents) throws Exception { enter(scopeContents); try { return toCall.call(); } finally { exit(); } } void run(Runnable toRun, Object... scopeContents); T call(Callable<T> toCall, Object... scopeContents); @Override boolean inScope(); }### Answer: @Test public void testCall() throws Exception { class I implements ThrowingFunction<String, String> { @Override public String apply(String argument) throws Exception { X x = deps.getInstance(X.class); assertNotNull(x); assertEquals("test", x.toString()); return argument + "." + x.toString(); } } String s = SCOPE.run(new I(), "hello", x); assertNotNull(s); assertEquals("hello." + x.toString(), s); }
### Question: ReentrantScope extends AbstractScope { public boolean inScope() { List<?> l = this.lists.get(); return l != null && !l.isEmpty(); } ReentrantScope(); ReentrantScope(Provider<String> injectionInfoProvider); QuietAutoCloseable enter(Object... o); @Override void exit(); boolean inScope(); }### Answer: @Test public void testInScope() throws Exception { final int limit = 10; StringBuilder constant = new StringBuilder("hello"); final boolean[] ran = new boolean[1]; class One implements ThrowingFunction<Integer, Void> { @Override public Void apply(Integer argument) throws Exception { ran[0] = true; assertNotNull(dependencies.getInstance(Integer.class)); assertEquals(argument, dependencies.getInstance(Integer.class)); assertNotNull(dependencies.getInstance(String.class)); assertEquals(argument.toString(), dependencies.getInstance(String.class)); assertNotNull(dependencies.getInstance(StringBuilder.class)); assertEquals("hello", dependencies.getInstance(StringBuilder.class).toString()); int next = argument + 1; if (next < limit) { dependencies.getInstance(AbstractScope.class) .run(this, next, Integer.valueOf(next), Integer.toString(next)); } return null; } } assertTrue(dependencies.getInstance(AbstractScope.class) instanceof ReentrantScope); dependencies.getInstance(AbstractScope.class).run(new One(), 1, constant, Integer.valueOf(1), Integer.toString(1)); assertTrue("Invokable was not run", ran[0]); }
### Question: ExecutorServiceProvider implements Provider<ExecutorService> { @Override public ExecutorService get() { ExecutorService result = null; if (registered.compareAndSet(false, true)) { synchronized (this) { if (exe == null) { result = exe = svc.get(); reg.get().add(exe); } else { result = exe; } } } if (result == null) { synchronized (this) { result = exe; } assert result != null; } return result; } ExecutorServiceProvider(Supplier<ExecutorService> svc, Provider<ShutdownHookRegistry> reg); @Override ExecutorService get(); static Provider<ExecutorService> provider(Supplier<ExecutorService> supplier, Binder binder); static Provider<ExecutorService> provider(int threads, Binder binder); static Provider<ExecutorService> provider(Binder binder); }### Answer: @Test public void testSomeMethod() throws IOException, InterruptedException, ExecutionException { Dependencies deps = new Dependencies(new M()); Thing thing = deps.getInstance(Thing.class); ExecutorService exe = deps.getInstance(ExecutorService.class); assertNotNull(exe); assertSame(thing.p.get(), exe); exe.submit(() -> { new StringBuilder("Hello.").append(1); }).get(); assertFalse(exe.isShutdown()); assertFalse(exe.isTerminated()); assertSame(exe, thing.p.get()); deps.shutdown(); assertTrue(exe.isShutdown()); }