method2testcases
stringlengths 118
6.63k
|
---|
### Question:
CreateTableEnhancedRequest { public Builder toBuilder() { return builder().provisionedThroughput(provisionedThroughput) .localSecondaryIndices(localSecondaryIndices) .globalSecondaryIndices(globalSecondaryIndices); } private CreateTableEnhancedRequest(Builder builder); static Builder builder(); Builder toBuilder(); ProvisionedThroughput provisionedThroughput(); Collection<EnhancedLocalSecondaryIndex> localSecondaryIndices(); Collection<EnhancedGlobalSecondaryIndex> globalSecondaryIndices(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void toBuilder() { CreateTableEnhancedRequest builtObject = CreateTableEnhancedRequest.builder() .provisionedThroughput(getDefaultProvisionedThroughput()) .build(); CreateTableEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); } |
### Question:
DeleteItemEnhancedRequest { public Builder toBuilder() { return builder().key(key).conditionExpression(conditionExpression); } private DeleteItemEnhancedRequest(Builder builder); static Builder builder(); Builder toBuilder(); Key key(); Expression conditionExpression(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void toBuilder() { Key key = Key.builder().partitionValue("key").build(); DeleteItemEnhancedRequest builtObject = DeleteItemEnhancedRequest.builder().key(key).build(); DeleteItemEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); } |
### Question:
QueryEnhancedRequest { public static Builder builder() { return new Builder(); } private QueryEnhancedRequest(Builder builder); static Builder builder(); Builder toBuilder(); QueryConditional queryConditional(); Map<String, AttributeValue> exclusiveStartKey(); Boolean scanIndexForward(); Integer limit(); Boolean consistentRead(); Expression filterExpression(); List<String> attributesToProject(); List<NestedAttributeName> nestedAttributesToProject(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void test_nestedAttributesNullNestedAttributeElement() { List<NestedAttributeName> attributeNames = new ArrayList<>(); attributeNames.add(NestedAttributeName.create("foo")); attributeNames.add(null); assertFails(() -> QueryEnhancedRequest.builder() .addNestedAttributesToProject(attributeNames) .build()); assertFails(() -> QueryEnhancedRequest.builder() .addNestedAttributesToProject(NestedAttributeName.create("foo", "bar"), null) .build()); NestedAttributeName nestedAttributeName = null; QueryEnhancedRequest.builder() .addNestedAttributeToProject(nestedAttributeName) .build(); assertFails(() -> QueryEnhancedRequest.builder() .addNestedAttributesToProject(nestedAttributeName) .build()); } |
### Question:
QueryEnhancedRequest { public Builder toBuilder() { return builder().queryConditional(queryConditional) .exclusiveStartKey(exclusiveStartKey) .scanIndexForward(scanIndexForward) .limit(limit) .consistentRead(consistentRead) .filterExpression(filterExpression) .addNestedAttributesToProject(attributesToProject); } private QueryEnhancedRequest(Builder builder); static Builder builder(); Builder toBuilder(); QueryConditional queryConditional(); Map<String, AttributeValue> exclusiveStartKey(); Boolean scanIndexForward(); Integer limit(); Boolean consistentRead(); Expression filterExpression(); List<String> attributesToProject(); List<NestedAttributeName> nestedAttributesToProject(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void toBuilder() { QueryEnhancedRequest builtObject = QueryEnhancedRequest.builder().build(); QueryEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); } |
### Question:
UpdateItemEnhancedRequest { public Builder<T> toBuilder() { return new Builder<T>().item(item).ignoreNulls(ignoreNulls); } private UpdateItemEnhancedRequest(Builder<T> builder); static Builder<T> builder(Class<? extends T> itemClass); Builder<T> toBuilder(); T item(); Boolean ignoreNulls(); Expression conditionExpression(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void toBuilder() { UpdateItemEnhancedRequest<FakeItem> builtObject = UpdateItemEnhancedRequest.builder(FakeItem.class).build(); UpdateItemEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); } |
### Question:
BatchGetItemEnhancedRequest { public Builder toBuilder() { return new Builder().readBatches(readBatches); } private BatchGetItemEnhancedRequest(Builder builder); static Builder builder(); Builder toBuilder(); Collection<ReadBatch> readBatches(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void toBuilder() { BatchGetItemEnhancedRequest builtObject = BatchGetItemEnhancedRequest.builder().build(); BatchGetItemEnhancedRequest copiedObject = builtObject.toBuilder().build(); assertThat(copiedObject, is(builtObject)); } |
### Question:
ExceptionTranslationInterceptor implements ExecutionInterceptor { @Override public Throwable modifyException(Context.FailedExecution context, ExecutionAttributes executionAttributes) { if (!isS3Exception404(context.exception()) || !isHeadRequest(context.request())) { return context.exception(); } String message = context.exception().getMessage(); S3Exception exception = (S3Exception) (context.exception()); String requestIdFromHeader = exception.awsErrorDetails() .sdkHttpResponse() .firstMatchingHeader("x-amz-request-id") .orElse(null); String requestId = Optional.ofNullable(exception.requestId()).orElse(requestIdFromHeader); AwsErrorDetails errorDetails = exception.awsErrorDetails(); if (context.request() instanceof HeadObjectRequest) { return NoSuchKeyException.builder() .awsErrorDetails(fillErrorDetails(errorDetails, "NoSuchKey", "The specified key does not exist.")) .statusCode(404) .requestId(requestId) .message(message) .build(); } if (context.request() instanceof HeadBucketRequest) { return NoSuchBucketException.builder() .awsErrorDetails(fillErrorDetails(errorDetails, "NoSuchBucket", "The specified bucket does not exist.")) .statusCode(404) .requestId(requestId) .message(message) .build(); } return context.exception(); } @Override Throwable modifyException(Context.FailedExecution context, ExecutionAttributes executionAttributes); }### Answer:
@Test public void headBucket404_shouldTranslateException() { S3Exception s3Exception = create404S3Exception(); Context.FailedExecution failedExecution = getFailedExecution(s3Exception, HeadBucketRequest.builder().build()); assertThat(interceptor.modifyException(failedExecution, new ExecutionAttributes())) .isExactlyInstanceOf(NoSuchBucketException.class); }
@Test public void headObject404_shouldTranslateException() { S3Exception s3Exception = create404S3Exception(); Context.FailedExecution failedExecution = getFailedExecution(s3Exception, HeadObjectRequest.builder().build()); assertThat(interceptor.modifyException(failedExecution, new ExecutionAttributes())) .isExactlyInstanceOf(NoSuchKeyException.class); }
@Test public void headObjectOtherException_shouldNotThrowException() { S3Exception s3Exception = (S3Exception) S3Exception.builder().statusCode(500).build(); Context.FailedExecution failedExecution = getFailedExecution(s3Exception, HeadObjectRequest.builder().build()); assertThat(interceptor.modifyException(failedExecution, new ExecutionAttributes())).isEqualTo(s3Exception); }
@Test public void otherRequest_shouldNotThrowException() { S3Exception s3Exception = create404S3Exception(); Context.FailedExecution failedExecution = getFailedExecution(s3Exception, PutObjectRequest.builder().build()); assertThat(interceptor.modifyException(failedExecution, new ExecutionAttributes())).isEqualTo(s3Exception); } |
### Question:
ImmutableAttribute { public Builder<T, B, R> toBuilder() { return new Builder<T, B, R>(this.type).name(this.name) .getter(this.getter) .setter(this.setter) .tags(this.tags) .attributeConverter(this.attributeConverter); } private ImmutableAttribute(Builder<T, B, R> builder); static Builder<T, B, R> builder(Class<T> itemClass,
Class<B> builderClass,
EnhancedType<R> attributeType); static Builder<T, B, R> builder(Class<T> itemClass,
Class<B> builderClass,
Class<R> attributeClass); String name(); Function<T, R> getter(); BiConsumer<B, R> setter(); Collection<StaticAttributeTag> tags(); EnhancedType<R> type(); AttributeConverter<R> attributeConverter(); Builder<T, B, R> toBuilder(); }### Answer:
@Test public void toBuilder() { ImmutableAttribute<Object, Object, String> immutableAttribute = ImmutableAttribute.builder(Object.class, Object.class, String.class) .name("test-attribute") .getter(TEST_GETTER) .setter(TEST_SETTER) .tags(mockTag, mockTag2) .attributeConverter(attributeConverter) .build(); ImmutableAttribute<Object, Object, String> clonedAttribute = immutableAttribute.toBuilder().build(); assertThat(clonedAttribute.name()).isEqualTo("test-attribute"); assertThat(clonedAttribute.getter()).isSameAs(TEST_GETTER); assertThat(clonedAttribute.setter()).isSameAs(TEST_SETTER); assertThat(clonedAttribute.tags()).containsExactly(mockTag, mockTag2); assertThat(clonedAttribute.type()).isEqualTo(EnhancedType.of(String.class)); assertThat(clonedAttribute.attributeConverter()).isSameAs(attributeConverter); } |
### Question:
StaticImmutableTableSchema implements TableSchema<T> { @Override public EnhancedType<T> itemType() { return this.itemType; } private StaticImmutableTableSchema(Builder<T, B> builder); static Builder<T, B> builder(Class<T> itemClass, Class<B> builderClass); @Override StaticTableMetadata tableMetadata(); @Override T mapToItem(Map<String, AttributeValue> attributeMap); @Override Map<String, AttributeValue> itemToMap(T item, boolean ignoreNulls); @Override Map<String, AttributeValue> itemToMap(T item, Collection<String> attributes); @Override AttributeValue attributeValue(T item, String key); @Override EnhancedType<T> itemType(); @Override List<String> attributeNames(); @Override boolean isAbstract(); AttributeConverterProvider attributeConverterProvider(); }### Answer:
@Test public void itemType_returnsCorrectClass() { assertThat(FakeItem.getTableSchema().itemType(), is(equalTo(EnhancedType.of(FakeItem.class)))); } |
### Question:
StaticImmutableTableSchema implements TableSchema<T> { @Override public StaticTableMetadata tableMetadata() { return tableMetadata; } private StaticImmutableTableSchema(Builder<T, B> builder); static Builder<T, B> builder(Class<T> itemClass, Class<B> builderClass); @Override StaticTableMetadata tableMetadata(); @Override T mapToItem(Map<String, AttributeValue> attributeMap); @Override Map<String, AttributeValue> itemToMap(T item, boolean ignoreNulls); @Override Map<String, AttributeValue> itemToMap(T item, Collection<String> attributes); @Override AttributeValue attributeValue(T item, String key); @Override EnhancedType<T> itemType(); @Override List<String> attributeNames(); @Override boolean isAbstract(); AttributeConverterProvider attributeConverterProvider(); }### Answer:
@Test public void getTableMetadata_hasCorrectFields() { TableMetadata tableMetadata = FakeItemWithSort.getTableSchema().tableMetadata(); assertThat(tableMetadata.primaryPartitionKey(), is("id")); assertThat(tableMetadata.primarySortKey(), is(Optional.of("sort"))); } |
### Question:
StaticImmutableTableSchema implements TableSchema<T> { @Override public Map<String, AttributeValue> itemToMap(T item, boolean ignoreNulls) { Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeMappers.forEach(attributeMapper -> { String attributeKey = attributeMapper.attributeName(); AttributeValue attributeValue = attributeMapper.attributeGetterMethod().apply(item); if (!ignoreNulls || !isNullAttributeValue(attributeValue)) { attributeValueMap.put(attributeKey, attributeValue); } }); indexedFlattenedMappers.forEach((name, flattenedMapper) -> { attributeValueMap.putAll(flattenedMapper.itemToMap(item, ignoreNulls)); }); return unmodifiableMap(attributeValueMap); } private StaticImmutableTableSchema(Builder<T, B> builder); static Builder<T, B> builder(Class<T> itemClass, Class<B> builderClass); @Override StaticTableMetadata tableMetadata(); @Override T mapToItem(Map<String, AttributeValue> attributeMap); @Override Map<String, AttributeValue> itemToMap(T item, boolean ignoreNulls); @Override Map<String, AttributeValue> itemToMap(T item, Collection<String> attributes); @Override AttributeValue attributeValue(T item, String key); @Override EnhancedType<T> itemType(); @Override List<String> attributeNames(); @Override boolean isAbstract(); AttributeConverterProvider attributeConverterProvider(); }### Answer:
@Test public void itemToMap_returnsCorrectMapWithMultipleAttributes() { Map<String, AttributeValue> attributeMap = createSimpleTableSchema().itemToMap(FAKE_ITEM, false); assertThat(attributeMap.size(), is(3)); assertThat(attributeMap, hasEntry("a_boolean", ATTRIBUTE_VALUE_B)); assertThat(attributeMap, hasEntry("a_primitive_boolean", ATTRIBUTE_VALUE_B)); assertThat(attributeMap, hasEntry("a_string", ATTRIBUTE_VALUE_S)); }
@Test public void itemToMap_filtersAttributes() { Map<String, AttributeValue> attributeMap = createSimpleTableSchema() .itemToMap(FAKE_ITEM, asList("a_boolean", "a_string")); assertThat(attributeMap.size(), is(2)); assertThat(attributeMap, hasEntry("a_boolean", ATTRIBUTE_VALUE_B)); assertThat(attributeMap, hasEntry("a_string", ATTRIBUTE_VALUE_S)); }
@Test(expected = IllegalArgumentException.class) public void itemToMap_attributeNotFound_throwsIllegalArgumentException() { createSimpleTableSchema().itemToMap(FAKE_ITEM, singletonList("unknown_key")); } |
### Question:
StaticImmutableTableSchema implements TableSchema<T> { @Override public T mapToItem(Map<String, AttributeValue> attributeMap) { B builder = null; Map<FlattenedMapper<T, B, ?>, Map<String, AttributeValue>> flattenedAttributeValuesMap = new LinkedHashMap<>(); for (Map.Entry<String, AttributeValue> entry : attributeMap.entrySet()) { String key = entry.getKey(); AttributeValue value = entry.getValue(); if (!isNullAttributeValue(value)) { ResolvedImmutableAttribute<T, B> attributeMapper = indexedMappers.get(key); if (attributeMapper != null) { if (builder == null) { builder = constructNewBuilder(); } attributeMapper.updateItemMethod().accept(builder, value); } else { FlattenedMapper<T, B, ?> flattenedMapper = this.indexedFlattenedMappers.get(key); if (flattenedMapper != null) { Map<String, AttributeValue> flattenedAttributeValues = flattenedAttributeValuesMap.get(flattenedMapper); if (flattenedAttributeValues == null) { flattenedAttributeValues = new HashMap<>(); } flattenedAttributeValues.put(key, value); flattenedAttributeValuesMap.put(flattenedMapper, flattenedAttributeValues); } } } } for (Map.Entry<FlattenedMapper<T, B, ?>, Map<String, AttributeValue>> entry : flattenedAttributeValuesMap.entrySet()) { builder = entry.getKey().mapToItem(builder, this::constructNewBuilder, entry.getValue()); } return builder == null ? null : buildItemFunction.apply(builder); } private StaticImmutableTableSchema(Builder<T, B> builder); static Builder<T, B> builder(Class<T> itemClass, Class<B> builderClass); @Override StaticTableMetadata tableMetadata(); @Override T mapToItem(Map<String, AttributeValue> attributeMap); @Override Map<String, AttributeValue> itemToMap(T item, boolean ignoreNulls); @Override Map<String, AttributeValue> itemToMap(T item, Collection<String> attributes); @Override AttributeValue attributeValue(T item, String key); @Override EnhancedType<T> itemType(); @Override List<String> attributeNames(); @Override boolean isAbstract(); AttributeConverterProvider attributeConverterProvider(); }### Answer:
@Test public void mapToItem_returnsCorrectItemWithMultipleAttributes() { Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("a_boolean", ATTRIBUTE_VALUE_B); attributeValueMap.put("a_primitive_boolean", ATTRIBUTE_VALUE_B); attributeValueMap.put("a_string", ATTRIBUTE_VALUE_S); FakeMappedItem fakeMappedItem = createSimpleTableSchema().mapToItem(Collections.unmodifiableMap(attributeValueMap)); assertThat(fakeMappedItem, is(FAKE_ITEM)); }
@Test public void mapToItem_unknownAttributes_doNotCauseErrors() { Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("unknown_attribute", ATTRIBUTE_VALUE_S); createSimpleTableSchema().mapToItem(Collections.unmodifiableMap(attributeValueMap)); }
@Test(expected = IllegalArgumentException.class) public void mapToItem_attributesWrongType_throwsException() { Map<String, AttributeValue> attributeValueMap = new HashMap<>(); attributeValueMap.put("a_boolean", ATTRIBUTE_VALUE_S); attributeValueMap.put("a_primitive_boolean", ATTRIBUTE_VALUE_S); attributeValueMap.put("a_string", ATTRIBUTE_VALUE_B); createSimpleTableSchema().mapToItem(Collections.unmodifiableMap(attributeValueMap)); } |
### Question:
S3Utilities { public static Builder builder() { return new Builder(); } private S3Utilities(Builder builder); static Builder builder(); URL getUrl(Consumer<GetUrlRequest.Builder> getUrlRequest); URL getUrl(GetUrlRequest getUrlRequest); }### Answer:
@Test (expected = NullPointerException.class) public void failIfRegionIsNotSetOnS3UtilitiesObject() throws MalformedURLException { S3Utilities.builder().build(); } |
### Question:
StaticAttribute { public Builder<T, R> toBuilder() { return new Builder<>(this.delegateAttribute.toBuilder()); } private StaticAttribute(Builder<T, R> builder); static Builder<T, R> builder(Class<T> itemClass, EnhancedType<R> attributeType); static Builder<T, R> builder(Class<T> itemClass, Class<R> attributeClass); String name(); Function<T, R> getter(); BiConsumer<T, R> setter(); Collection<StaticAttributeTag> tags(); EnhancedType<R> type(); AttributeConverter<R> attributeConverter(); Builder<T, R> toBuilder(); }### Answer:
@Test public void toBuilder() { StaticAttribute<Object, String> staticAttribute = StaticAttribute.builder(Object.class, String.class) .name("test-attribute") .getter(TEST_GETTER) .setter(TEST_SETTER) .tags(mockTag, mockTag2) .attributeConverter(attributeConverter) .build(); StaticAttribute<Object, String> clonedAttribute = staticAttribute.toBuilder().build(); assertThat(clonedAttribute.name()).isEqualTo("test-attribute"); assertThat(clonedAttribute.getter()).isSameAs(TEST_GETTER); assertThat(clonedAttribute.setter()).isSameAs(TEST_SETTER); assertThat(clonedAttribute.tags()).containsExactly(mockTag, mockTag2); assertThat(clonedAttribute.type()).isEqualTo(EnhancedType.of(String.class)); assertThat(clonedAttribute.attributeConverter()).isSameAs(attributeConverter); } |
### Question:
EnableTrailingChecksumInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerRequest(context.request(), executionAttributes)) { return context.httpRequest().toBuilder().putHeader(ENABLE_CHECKSUM_REQUEST_HEADER, ENABLE_MD5_CHECKSUM_HEADER_VALUE) .build(); } return context.httpRequest(); } @Override SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override SdkResponse modifyResponse(Context.ModifyResponse context, ExecutionAttributes executionAttributes); }### Answer:
@Test public void modifyHttpRequest_getObjectTrailingChecksumEnabled_shouldAddTrailingChecksumHeader() { Context.ModifyHttpRequest modifyHttpRequestContext = modifyHttpRequestContext(GetObjectRequest.builder().build()); SdkHttpRequest sdkHttpRequest = interceptor.modifyHttpRequest(modifyHttpRequestContext, new ExecutionAttributes()); assertThat(sdkHttpRequest.headers().get(ENABLE_CHECKSUM_REQUEST_HEADER)).containsOnly(ENABLE_MD5_CHECKSUM_HEADER_VALUE); }
@Test public void modifyHttpRequest_getObjectTrailingChecksumDisabled_shouldNotModifyHttpRequest() { Context.ModifyHttpRequest modifyHttpRequestContext = modifyHttpRequestContext(GetObjectRequest.builder().build()); SdkHttpRequest sdkHttpRequest = interceptor.modifyHttpRequest(modifyHttpRequestContext, new ExecutionAttributes().putAttribute(AwsSignerExecutionAttribute.SERVICE_CONFIG, S3Configuration.builder().checksumValidationEnabled(false).build())); assertThat(sdkHttpRequest).isEqualToComparingFieldByField(modifyHttpRequestContext.httpRequest()); }
@Test public void modifyHttpRequest_nonGetObjectRequest_shouldNotModifyHttpRequest() { Context.ModifyHttpRequest modifyHttpRequestContext = modifyHttpRequestContext(PutObjectRequest.builder().build()); SdkHttpRequest sdkHttpRequest = interceptor.modifyHttpRequest(modifyHttpRequestContext, new ExecutionAttributes()); assertThat(sdkHttpRequest).isEqualToComparingFieldByField(modifyHttpRequestContext.httpRequest()); } |
### Question:
Key { public Optional<AttributeValue> sortKeyValue() { return Optional.ofNullable(sortValue); } private Key(Builder builder); static Builder builder(); Map<String, AttributeValue> keyMap(TableSchema<?> tableSchema, String index); AttributeValue partitionKeyValue(); Optional<AttributeValue> sortKeyValue(); Map<String, AttributeValue> primaryKeyMap(TableSchema<?> tableSchema); Builder toBuilder(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getSortKeyValue_partitionOnly() { assertThat(partitionOnlyKey.sortKeyValue(), is(Optional.empty())); } |
### Question:
Key { public Builder toBuilder() { return new Builder().partitionValue(this.partitionValue).sortValue(this.sortValue); } private Key(Builder builder); static Builder builder(); Map<String, AttributeValue> keyMap(TableSchema<?> tableSchema, String index); AttributeValue partitionKeyValue(); Optional<AttributeValue> sortKeyValue(); Map<String, AttributeValue> primaryKeyMap(TableSchema<?> tableSchema); Builder toBuilder(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void toBuilder() { Key keyClone = key.toBuilder().build(); assertThat(key, is(equalTo(keyClone))); } |
### Question:
Key { public static Builder builder() { return new Builder(); } private Key(Builder builder); static Builder builder(); Map<String, AttributeValue> keyMap(TableSchema<?> tableSchema, String index); AttributeValue partitionKeyValue(); Optional<AttributeValue> sortKeyValue(); Map<String, AttributeValue> primaryKeyMap(TableSchema<?> tableSchema); Builder toBuilder(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void nullPartitionKey_shouldThrowException() { AttributeValue attributeValue = null; assertThatThrownBy(() -> Key.builder().partitionValue(attributeValue).build()) .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("partitionValue should not be null"); assertThatThrownBy(() -> Key.builder().partitionValue(AttributeValue.builder().nul(true).build()).build()) .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("partitionValue should not be null"); } |
### Question:
ApplyUserAgentInterceptor implements ExecutionInterceptor { @Override public SdkRequest modifyRequest(Context.ModifyRequest context, ExecutionAttributes executionAttributes) { if (!(context.request() instanceof DynamoDbRequest)) { return context.request(); } DynamoDbRequest request = (DynamoDbRequest) context.request(); AwsRequestOverrideConfiguration overrideConfiguration = request.overrideConfiguration().map(c -> c.toBuilder() .applyMutation(USER_AGENT_APPLIER) .build()) .orElse((AwsRequestOverrideConfiguration.builder() .applyMutation(USER_AGENT_APPLIER) .build())); return request.toBuilder().overrideConfiguration(overrideConfiguration).build(); } @Override SdkRequest modifyRequest(Context.ModifyRequest context, ExecutionAttributes executionAttributes); }### Answer:
@Test public void ddbRequest_shouldModifyRequest() { GetItemRequest getItemRequest = GetItemRequest.builder().build(); SdkRequest sdkRequest = interceptor.modifyRequest(() -> getItemRequest, new ExecutionAttributes()); RequestOverrideConfiguration requestOverrideConfiguration = sdkRequest.overrideConfiguration().get(); assertThat(requestOverrideConfiguration.apiNames() .stream() .filter(a -> a.name() .equals("hll") && a.version().equals("ddb-enh")).findAny()) .isPresent(); }
@Test public void otherRequest_shouldNotModifyRequest() { SdkRequest someOtherRequest = new SdkRequest() { @Override public List<SdkField<?>> sdkFields() { return null; } @Override public Optional<? extends RequestOverrideConfiguration> overrideConfiguration() { return Optional.empty(); } @Override public Builder toBuilder() { return null; } }; SdkRequest sdkRequest = interceptor.modifyRequest(() -> someOtherRequest, new ExecutionAttributes()); assertThat(sdkRequest).isEqualTo(someOtherRequest); } |
### Question:
ScanOperation implements PaginatedTableOperation<T, ScanRequest, ScanResponse>,
PaginatedIndexOperation<T, ScanRequest, ScanResponse> { @Override public Function<ScanRequest, SdkIterable<ScanResponse>> serviceCall(DynamoDbClient dynamoDbClient) { return dynamoDbClient::scanPaginator; } private ScanOperation(ScanEnhancedRequest request); static ScanOperation<T> create(ScanEnhancedRequest request); @Override ScanRequest generateRequest(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension); @Override Page<T> transformResponse(ScanResponse response,
TableSchema<T> tableSchema,
OperationContext context,
DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension); @Override Function<ScanRequest, SdkIterable<ScanResponse>> serviceCall(DynamoDbClient dynamoDbClient); @Override Function<ScanRequest, SdkPublisher<ScanResponse>> asyncServiceCall(DynamoDbAsyncClient dynamoDbAsyncClient); }### Answer:
@Test public void getServiceCall_makesTheRightCallAndReturnsResponse() { ScanRequest scanRequest = ScanRequest.builder().build(); ScanIterable mockScanIterable = mock(ScanIterable.class); when(mockDynamoDbClient.scanPaginator(any(ScanRequest.class))).thenReturn(mockScanIterable); SdkIterable<ScanResponse> response = scanOperation.serviceCall(mockDynamoDbClient).apply(scanRequest); assertThat(response, is(mockScanIterable)); verify(mockDynamoDbClient).scanPaginator(scanRequest); } |
### Question:
ScanOperation implements PaginatedTableOperation<T, ScanRequest, ScanResponse>,
PaginatedIndexOperation<T, ScanRequest, ScanResponse> { @Override public Function<ScanRequest, SdkPublisher<ScanResponse>> asyncServiceCall(DynamoDbAsyncClient dynamoDbAsyncClient) { return dynamoDbAsyncClient::scanPaginator; } private ScanOperation(ScanEnhancedRequest request); static ScanOperation<T> create(ScanEnhancedRequest request); @Override ScanRequest generateRequest(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension); @Override Page<T> transformResponse(ScanResponse response,
TableSchema<T> tableSchema,
OperationContext context,
DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension); @Override Function<ScanRequest, SdkIterable<ScanResponse>> serviceCall(DynamoDbClient dynamoDbClient); @Override Function<ScanRequest, SdkPublisher<ScanResponse>> asyncServiceCall(DynamoDbAsyncClient dynamoDbAsyncClient); }### Answer:
@Test public void getAsyncServiceCall_makesTheRightCallAndReturnsResponse() { ScanRequest scanRequest = ScanRequest.builder().build(); ScanPublisher mockScanPublisher = mock(ScanPublisher.class); when(mockDynamoDbAsyncClient.scanPaginator(any(ScanRequest.class))).thenReturn(mockScanPublisher); SdkPublisher<ScanResponse> response = scanOperation.asyncServiceCall(mockDynamoDbAsyncClient) .apply(scanRequest); assertThat(response, is(mockScanPublisher)); verify(mockDynamoDbAsyncClient).scanPaginator(scanRequest); } |
### Question:
ScanOperation implements PaginatedTableOperation<T, ScanRequest, ScanResponse>,
PaginatedIndexOperation<T, ScanRequest, ScanResponse> { @Override public ScanRequest generateRequest(TableSchema<T> tableSchema, OperationContext operationContext, DynamoDbEnhancedClientExtension extension) { Map<String, AttributeValue> expressionValues = null; Map<String, String> expressionNames = null; if (this.request.filterExpression() != null) { expressionValues = this.request.filterExpression().expressionValues(); expressionNames = this.request.filterExpression().expressionNames(); } ProjectionExpressionConvertor attributeToProject = ProjectionExpressionConvertor.create(this.request.nestedAttributesToProject()); Map<String, String> projectionNameMap = attributeToProject.convertToExpressionMap(); if (!projectionNameMap.isEmpty()) { expressionNames = Expression.joinNames(expressionNames, projectionNameMap); } String projectionExpression = attributeToProject.convertToProjectionExpression().orElse(null); ScanRequest.Builder scanRequest = ScanRequest.builder() .tableName(operationContext.tableName()) .limit(this.request.limit()) .exclusiveStartKey(this.request.exclusiveStartKey()) .consistentRead(this.request.consistentRead()) .expressionAttributeValues(expressionValues) .expressionAttributeNames(expressionNames) .projectionExpression(projectionExpression); if (!TableMetadata.primaryIndexName().equals(operationContext.indexName())) { scanRequest = scanRequest.indexName(operationContext.indexName()); } if (this.request.filterExpression() != null) { scanRequest = scanRequest.filterExpression(this.request.filterExpression().expression()); } return scanRequest.build(); } private ScanOperation(ScanEnhancedRequest request); static ScanOperation<T> create(ScanEnhancedRequest request); @Override ScanRequest generateRequest(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension); @Override Page<T> transformResponse(ScanResponse response,
TableSchema<T> tableSchema,
OperationContext context,
DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension); @Override Function<ScanRequest, SdkIterable<ScanResponse>> serviceCall(DynamoDbClient dynamoDbClient); @Override Function<ScanRequest, SdkPublisher<ScanResponse>> asyncServiceCall(DynamoDbAsyncClient dynamoDbAsyncClient); }### Answer:
@Test public void generateRequest_defaultScan() { ScanRequest request = scanOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); ScanRequest expectedRequest = ScanRequest.builder() .tableName(TABLE_NAME) .build(); assertThat(request, is(expectedRequest)); } |
### Question:
ScanOperation implements PaginatedTableOperation<T, ScanRequest, ScanResponse>,
PaginatedIndexOperation<T, ScanRequest, ScanResponse> { @Override public Page<T> transformResponse(ScanResponse response, TableSchema<T> tableSchema, OperationContext context, DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension) { return EnhancedClientUtils.readAndTransformPaginatedItems(response, tableSchema, context, dynamoDbEnhancedClientExtension, ScanResponse::items, ScanResponse::lastEvaluatedKey); } private ScanOperation(ScanEnhancedRequest request); static ScanOperation<T> create(ScanEnhancedRequest request); @Override ScanRequest generateRequest(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension); @Override Page<T> transformResponse(ScanResponse response,
TableSchema<T> tableSchema,
OperationContext context,
DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension); @Override Function<ScanRequest, SdkIterable<ScanResponse>> serviceCall(DynamoDbClient dynamoDbClient); @Override Function<ScanRequest, SdkPublisher<ScanResponse>> asyncServiceCall(DynamoDbAsyncClient dynamoDbAsyncClient); }### Answer:
@Test public void transformResults_multipleItems_returnsCorrectItems() { List<FakeItem> scanResultItems = generateFakeItemList(); List<Map<String, AttributeValue>> scanResultMaps = scanResultItems.stream().map(ScanOperationTest::getAttributeValueMap).collect(toList()); ScanResponse scanResponse = generateFakeScanResults(scanResultMaps); Page<FakeItem> scanResultPage = scanOperation.transformResponse(scanResponse, FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(scanResultPage.items(), is(scanResultItems)); }
@Test public void transformResults_multipleItems_setsLastEvaluatedKey() { List<FakeItem> scanResultItems = generateFakeItemList(); FakeItem lastEvaluatedKey = createUniqueFakeItem(); List<Map<String, AttributeValue>> scanResultMaps = scanResultItems.stream().map(ScanOperationTest::getAttributeValueMap).collect(toList()); ScanResponse scanResponse = generateFakeScanResults(scanResultMaps, getAttributeValueMap(lastEvaluatedKey)); Page<FakeItem> scanResultPage = scanOperation.transformResponse(scanResponse, FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(scanResultPage.lastEvaluatedKey(), is(getAttributeValueMap(lastEvaluatedKey))); }
@Test public void scanItem_withExtension_correctlyTransformsItems() { List<FakeItem> scanResultItems = generateFakeItemList(); List<FakeItem> modifiedResultItems = generateFakeItemList(); List<Map<String, AttributeValue>> scanResultMaps = scanResultItems.stream().map(ScanOperationTest::getAttributeValueMap).collect(toList()); ReadModification[] readModifications = modifiedResultItems.stream() .map(ScanOperationTest::getAttributeValueMap) .map(attributeMap -> ReadModification.builder().transformedItem(attributeMap).build()) .collect(Collectors.toList()) .toArray(new ReadModification[]{}); when(mockDynamoDbEnhancedClientExtension.afterRead(any(DynamoDbExtensionContext.AfterRead.class))) .thenReturn(readModifications[0], Arrays.copyOfRange(readModifications, 1, readModifications.length)); ScanResponse scanResponse = generateFakeScanResults(scanResultMaps); Page<FakeItem> scanResultPage = scanOperation.transformResponse(scanResponse, FakeItem.getTableSchema(), PRIMARY_CONTEXT, mockDynamoDbEnhancedClientExtension); assertThat(scanResultPage.items(), is(modifiedResultItems)); InOrder inOrder = Mockito.inOrder(mockDynamoDbEnhancedClientExtension); scanResultMaps.forEach( attributeMap -> inOrder.verify(mockDynamoDbEnhancedClientExtension).afterRead( DefaultDynamoDbExtensionContext.builder() .tableMetadata(FakeItem.getTableMetadata()) .operationContext(PRIMARY_CONTEXT) .items(attributeMap).build())); } |
### Question:
EnableTrailingChecksumInterceptor implements ExecutionInterceptor { @Override public SdkResponse modifyResponse(Context.ModifyResponse context, ExecutionAttributes executionAttributes) { SdkResponse response = context.response(); SdkHttpResponse httpResponse = context.httpResponse(); if (getObjectChecksumEnabledPerResponse(context.request(), httpResponse)) { GetObjectResponse getResponse = (GetObjectResponse) response; Long contentLength = getResponse.contentLength(); Validate.notNull(contentLength, "Service returned null 'Content-Length'."); return getResponse.toBuilder() .contentLength(contentLength - S3_MD5_CHECKSUM_LENGTH) .build(); } return response; } @Override SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override SdkResponse modifyResponse(Context.ModifyResponse context, ExecutionAttributes executionAttributes); }### Answer:
@Test public void modifyResponse_getObjectResponseContainsChecksumHeader_shouldModifyResponse() { long contentLength = 50; GetObjectResponse response = GetObjectResponse.builder().contentLength(contentLength).build(); Context.ModifyResponse modifyResponseContext = modifyResponseContext( GetObjectRequest.builder().build(), response, SdkHttpFullResponse.builder() .putHeader(CHECKSUM_ENABLED_RESPONSE_HEADER, ENABLE_MD5_CHECKSUM_HEADER_VALUE).build()); GetObjectResponse actualResponse = (GetObjectResponse) interceptor.modifyResponse(modifyResponseContext, new ExecutionAttributes()); assertThat(actualResponse).isNotEqualTo(response); assertThat(actualResponse.contentLength()).isEqualTo(contentLength - S3_MD5_CHECKSUM_LENGTH); }
@Test public void modifyResponse_getObjectResponseNoChecksumHeader_shouldNotModifyResponse() { long contentLength = 50; GetObjectResponse response = GetObjectResponse.builder().contentLength(contentLength).build(); Context.ModifyResponse modifyResponseContext = modifyResponseContext( GetObjectRequest.builder().build(), response, SdkHttpFullResponse.builder().build()); GetObjectResponse actualResponse = (GetObjectResponse) interceptor.modifyResponse(modifyResponseContext, new ExecutionAttributes()); assertThat(actualResponse).isEqualTo(response); }
@Test public void modifyResponse_nonGetObjectResponse_shouldNotModifyResponse() { GetObjectAclResponse getObjectAclResponse = GetObjectAclResponse.builder().build(); Context.ModifyResponse modifyResponseContext = modifyResponseContext( GetObjectAclRequest.builder().build(), getObjectAclResponse, SdkHttpFullResponse.builder().build()); GetObjectAclResponse actualResponse = (GetObjectAclResponse) interceptor.modifyResponse(modifyResponseContext, new ExecutionAttributes()); assertThat(actualResponse).isEqualTo(getObjectAclResponse); } |
### Question:
QueryOperation implements PaginatedTableOperation<T, QueryRequest, QueryResponse>,
PaginatedIndexOperation<T, QueryRequest, QueryResponse> { @Override public Function<QueryRequest, SdkIterable<QueryResponse>> serviceCall(DynamoDbClient dynamoDbClient) { return dynamoDbClient::queryPaginator; } private QueryOperation(QueryEnhancedRequest request); static QueryOperation<T> create(QueryEnhancedRequest request); @Override QueryRequest generateRequest(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension); @Override Function<QueryRequest, SdkIterable<QueryResponse>> serviceCall(DynamoDbClient dynamoDbClient); @Override Function<QueryRequest, SdkPublisher<QueryResponse>> asyncServiceCall(DynamoDbAsyncClient dynamoDbAsyncClient); @Override Page<T> transformResponse(QueryResponse response,
TableSchema<T> tableSchema,
OperationContext context,
DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension); }### Answer:
@Test public void getServiceCall_makesTheRightCallAndReturnsResponse() { QueryRequest queryRequest = QueryRequest.builder().build(); QueryIterable mockQueryIterable = mock(QueryIterable.class); when(mockDynamoDbClient.queryPaginator(any(QueryRequest.class))).thenReturn(mockQueryIterable); SdkIterable<QueryResponse> response = queryOperation.serviceCall(mockDynamoDbClient).apply(queryRequest); assertThat(response, is(mockQueryIterable)); verify(mockDynamoDbClient).queryPaginator(queryRequest); } |
### Question:
QueryOperation implements PaginatedTableOperation<T, QueryRequest, QueryResponse>,
PaginatedIndexOperation<T, QueryRequest, QueryResponse> { @Override public Function<QueryRequest, SdkPublisher<QueryResponse>> asyncServiceCall(DynamoDbAsyncClient dynamoDbAsyncClient) { return dynamoDbAsyncClient::queryPaginator; } private QueryOperation(QueryEnhancedRequest request); static QueryOperation<T> create(QueryEnhancedRequest request); @Override QueryRequest generateRequest(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension); @Override Function<QueryRequest, SdkIterable<QueryResponse>> serviceCall(DynamoDbClient dynamoDbClient); @Override Function<QueryRequest, SdkPublisher<QueryResponse>> asyncServiceCall(DynamoDbAsyncClient dynamoDbAsyncClient); @Override Page<T> transformResponse(QueryResponse response,
TableSchema<T> tableSchema,
OperationContext context,
DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension); }### Answer:
@Test public void getAsyncServiceCall_makesTheRightCallAndReturnsResponse() { QueryRequest queryRequest = QueryRequest.builder().build(); QueryPublisher mockQueryPublisher = mock(QueryPublisher.class); when(mockDynamoDbAsyncClient.queryPaginator(any(QueryRequest.class))).thenReturn(mockQueryPublisher); SdkPublisher<QueryResponse> response = queryOperation.asyncServiceCall(mockDynamoDbAsyncClient).apply(queryRequest); assertThat(response, is(mockQueryPublisher)); verify(mockDynamoDbAsyncClient).queryPaginator(queryRequest); } |
### Question:
QueryOperation implements PaginatedTableOperation<T, QueryRequest, QueryResponse>,
PaginatedIndexOperation<T, QueryRequest, QueryResponse> { @Override public QueryRequest generateRequest(TableSchema<T> tableSchema, OperationContext operationContext, DynamoDbEnhancedClientExtension extension) { Expression queryExpression = this.request.queryConditional().expression(tableSchema, operationContext.indexName()); Map<String, AttributeValue> expressionValues = queryExpression.expressionValues(); Map<String, String> expressionNames = queryExpression.expressionNames(); if (this.request.filterExpression() != null) { expressionValues = Expression.joinValues(expressionValues, this.request.filterExpression().expressionValues()); expressionNames = Expression.joinNames(expressionNames, this.request.filterExpression().expressionNames()); } ProjectionExpressionConvertor attributeToProject = ProjectionExpressionConvertor.create(this.request.nestedAttributesToProject()); Map<String, String> projectionNameMap = attributeToProject.convertToExpressionMap(); if (!projectionNameMap.isEmpty()) { expressionNames = Expression.joinNames(expressionNames, projectionNameMap); } String projectionExpression = attributeToProject.convertToProjectionExpression().orElse(null); QueryRequest.Builder queryRequest = QueryRequest.builder() .tableName(operationContext.tableName()) .keyConditionExpression(queryExpression.expression()) .expressionAttributeValues(expressionValues) .expressionAttributeNames(expressionNames) .scanIndexForward(this.request.scanIndexForward()) .limit(this.request.limit()) .exclusiveStartKey(this.request.exclusiveStartKey()) .consistentRead(this.request.consistentRead()) .projectionExpression(projectionExpression); if (!TableMetadata.primaryIndexName().equals(operationContext.indexName())) { queryRequest = queryRequest.indexName(operationContext.indexName()); } if (this.request.filterExpression() != null) { queryRequest = queryRequest.filterExpression(this.request.filterExpression().expression()); } return queryRequest.build(); } private QueryOperation(QueryEnhancedRequest request); static QueryOperation<T> create(QueryEnhancedRequest request); @Override QueryRequest generateRequest(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension); @Override Function<QueryRequest, SdkIterable<QueryResponse>> serviceCall(DynamoDbClient dynamoDbClient); @Override Function<QueryRequest, SdkPublisher<QueryResponse>> asyncServiceCall(DynamoDbAsyncClient dynamoDbAsyncClient); @Override Page<T> transformResponse(QueryResponse response,
TableSchema<T> tableSchema,
OperationContext context,
DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension); }### Answer:
@Test public void generateRequest_defaultQuery_usesEqualTo() { QueryRequest queryRequest = queryOperation.generateRequest(FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); QueryRequest expectedQueryRequest = QueryRequest.builder() .tableName(TABLE_NAME) .keyConditionExpression("#AMZN_MAPPED_id = :AMZN_MAPPED_id") .expressionAttributeValues(singletonMap(":AMZN_MAPPED_id", AttributeValue.builder().s(keyItem.getId()).build())) .expressionAttributeNames(singletonMap("#AMZN_MAPPED_id", "id")) .build(); assertThat(queryRequest, is(expectedQueryRequest)); } |
### Question:
QueryOperation implements PaginatedTableOperation<T, QueryRequest, QueryResponse>,
PaginatedIndexOperation<T, QueryRequest, QueryResponse> { @Override public Page<T> transformResponse(QueryResponse response, TableSchema<T> tableSchema, OperationContext context, DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension) { return EnhancedClientUtils.readAndTransformPaginatedItems(response, tableSchema, context, dynamoDbEnhancedClientExtension, QueryResponse::items, QueryResponse::lastEvaluatedKey); } private QueryOperation(QueryEnhancedRequest request); static QueryOperation<T> create(QueryEnhancedRequest request); @Override QueryRequest generateRequest(TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension extension); @Override Function<QueryRequest, SdkIterable<QueryResponse>> serviceCall(DynamoDbClient dynamoDbClient); @Override Function<QueryRequest, SdkPublisher<QueryResponse>> asyncServiceCall(DynamoDbAsyncClient dynamoDbAsyncClient); @Override Page<T> transformResponse(QueryResponse response,
TableSchema<T> tableSchema,
OperationContext context,
DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension); }### Answer:
@Test public void transformResults_multipleItems_returnsCorrectItems() { List<FakeItem> queryResultItems = generateFakeItemList(); List<Map<String, AttributeValue>> queryResultMaps = queryResultItems.stream().map(QueryOperationTest::getAttributeValueMap).collect(toList()); QueryResponse queryResponse = generateFakeQueryResults(queryResultMaps); Page<FakeItem> queryResultPage = queryOperation.transformResponse(queryResponse, FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(queryResultPage.items(), is(queryResultItems)); }
@Test public void transformResults_multipleItems_setsLastEvaluatedKey() { List<FakeItem> queryResultItems = generateFakeItemList(); FakeItem lastEvaluatedKey = createUniqueFakeItem(); List<Map<String, AttributeValue>> queryResultMaps = queryResultItems.stream().map(QueryOperationTest::getAttributeValueMap).collect(toList()); QueryResponse queryResponse = generateFakeQueryResults(queryResultMaps, getAttributeValueMap(lastEvaluatedKey)); Page<FakeItem> queryResultPage = queryOperation.transformResponse(queryResponse, FakeItem.getTableSchema(), PRIMARY_CONTEXT, null); assertThat(queryResultPage.lastEvaluatedKey(), is(getAttributeValueMap(lastEvaluatedKey))); }
@Test public void queryItem_withExtension_correctlyTransformsItem() { List<FakeItem> queryResultItems = generateFakeItemList(); List<FakeItem> modifiedResultItems = generateFakeItemList(); List<Map<String, AttributeValue>> queryResultMap = queryResultItems.stream().map(QueryOperationTest::getAttributeValueMap).collect(toList()); ReadModification[] readModifications = modifiedResultItems.stream() .map(QueryOperationTest::getAttributeValueMap) .map(attributeMap -> ReadModification.builder().transformedItem(attributeMap).build()) .collect(Collectors.toList()) .toArray(new ReadModification[]{}); when(mockDynamoDbEnhancedClientExtension.afterRead(any(DynamoDbExtensionContext.AfterRead.class))) .thenReturn(readModifications[0], Arrays.copyOfRange(readModifications, 1, readModifications.length)); QueryResponse queryResponse = generateFakeQueryResults(queryResultMap); Page<FakeItem> queryResultPage = queryOperation.transformResponse(queryResponse, FakeItem.getTableSchema(), PRIMARY_CONTEXT, mockDynamoDbEnhancedClientExtension); assertThat(queryResultPage.items(), is(modifiedResultItems)); InOrder inOrder = Mockito.inOrder(mockDynamoDbEnhancedClientExtension); queryResultMap.forEach( attributeMap -> inOrder.verify(mockDynamoDbEnhancedClientExtension) .afterRead( DefaultDynamoDbExtensionContext.builder() .tableMetadata(FakeItem.getTableMetadata()) .operationContext(PRIMARY_CONTEXT) .items(attributeMap).build())); } |
### Question:
MetaTableSchemaCache { public <T> Optional<MetaTableSchema<T>> get(Class<T> mappedClass) { return Optional.ofNullable((MetaTableSchema<T>) cacheMap().get(mappedClass)); } MetaTableSchema<T> getOrCreate(Class<T> mappedClass); Optional<MetaTableSchema<T>> get(Class<T> mappedClass); }### Answer:
@Test public void getKeyNotInMap() { assertThat(metaTableSchemaCache.get(FakeItem.class)).isNotPresent(); } |
### Question:
MetaTableSchemaCache { public <T> MetaTableSchema<T> getOrCreate(Class<T> mappedClass) { return (MetaTableSchema<T>) cacheMap().computeIfAbsent( mappedClass, ignored -> MetaTableSchema.create(mappedClass)); } MetaTableSchema<T> getOrCreate(Class<T> mappedClass); Optional<MetaTableSchema<T>> get(Class<T> mappedClass); }### Answer:
@Test public void createReturnsExistingObject() { MetaTableSchema<FakeItem> metaTableSchema = metaTableSchemaCache.getOrCreate(FakeItem.class); assertThat(metaTableSchema).isNotNull(); assertThat(metaTableSchemaCache.getOrCreate(FakeItem.class)).isSameAs(metaTableSchema); } |
### Question:
DefaultDynamoDbEnhancedAsyncClient implements DynamoDbEnhancedAsyncClient { @Override public <T> DefaultDynamoDbAsyncTable<T> table(String tableName, TableSchema<T> tableSchema) { return new DefaultDynamoDbAsyncTable<>(dynamoDbClient, extension, tableSchema, tableName); } private DefaultDynamoDbEnhancedAsyncClient(Builder builder); static Builder builder(); @Override DefaultDynamoDbAsyncTable<T> table(String tableName, TableSchema<T> tableSchema); @Override BatchGetResultPagePublisher batchGetItem(BatchGetItemEnhancedRequest request); @Override BatchGetResultPagePublisher batchGetItem(
Consumer<BatchGetItemEnhancedRequest.Builder> requestConsumer); @Override CompletableFuture<BatchWriteResult> batchWriteItem(BatchWriteItemEnhancedRequest request); @Override CompletableFuture<BatchWriteResult> batchWriteItem(
Consumer<BatchWriteItemEnhancedRequest.Builder> requestConsumer); @Override CompletableFuture<List<Document>> transactGetItems(TransactGetItemsEnhancedRequest request); @Override CompletableFuture<List<Document>> transactGetItems(
Consumer<TransactGetItemsEnhancedRequest.Builder> requestConsumer); @Override CompletableFuture<Void> transactWriteItems(TransactWriteItemsEnhancedRequest request); @Override CompletableFuture<Void> transactWriteItems(
Consumer<TransactWriteItemsEnhancedRequest.Builder> requestConsumer); DynamoDbAsyncClient dynamoDbAsyncClient(); DynamoDbEnhancedClientExtension mapperExtension(); Builder toBuilder(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void table() { DefaultDynamoDbAsyncTable<Object> mappedTable = dynamoDbEnhancedAsyncClient.table("table-name", mockTableSchema); assertThat(mappedTable.dynamoDbClient(), is(mockDynamoDbAsyncClient)); assertThat(mappedTable.mapperExtension(), is(mockDynamoDbEnhancedClientExtension)); assertThat(mappedTable.tableSchema(), is(mockTableSchema)); assertThat(mappedTable.tableName(), is("table-name")); } |
### Question:
DefaultDynamoDbEnhancedAsyncClient implements DynamoDbEnhancedAsyncClient { public Builder toBuilder() { return builder().dynamoDbClient(this.dynamoDbClient).extensions(this.extension); } private DefaultDynamoDbEnhancedAsyncClient(Builder builder); static Builder builder(); @Override DefaultDynamoDbAsyncTable<T> table(String tableName, TableSchema<T> tableSchema); @Override BatchGetResultPagePublisher batchGetItem(BatchGetItemEnhancedRequest request); @Override BatchGetResultPagePublisher batchGetItem(
Consumer<BatchGetItemEnhancedRequest.Builder> requestConsumer); @Override CompletableFuture<BatchWriteResult> batchWriteItem(BatchWriteItemEnhancedRequest request); @Override CompletableFuture<BatchWriteResult> batchWriteItem(
Consumer<BatchWriteItemEnhancedRequest.Builder> requestConsumer); @Override CompletableFuture<List<Document>> transactGetItems(TransactGetItemsEnhancedRequest request); @Override CompletableFuture<List<Document>> transactGetItems(
Consumer<TransactGetItemsEnhancedRequest.Builder> requestConsumer); @Override CompletableFuture<Void> transactWriteItems(TransactWriteItemsEnhancedRequest request); @Override CompletableFuture<Void> transactWriteItems(
Consumer<TransactWriteItemsEnhancedRequest.Builder> requestConsumer); DynamoDbAsyncClient dynamoDbAsyncClient(); DynamoDbEnhancedClientExtension mapperExtension(); Builder toBuilder(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void toBuilder() { DefaultDynamoDbEnhancedAsyncClient copiedObject = dynamoDbEnhancedAsyncClient.toBuilder().build(); assertThat(copiedObject, is(dynamoDbEnhancedAsyncClient)); } |
### Question:
DefaultDynamoDbIndex implements DynamoDbIndex<T> { @Override public Key keyFrom(T item) { return createKeyFromItem(item, tableSchema, indexName); } DefaultDynamoDbIndex(DynamoDbClient dynamoDbClient,
DynamoDbEnhancedClientExtension extension,
TableSchema<T> tableSchema,
String tableName,
String indexName); @Override SdkIterable<Page<T>> query(QueryEnhancedRequest request); @Override SdkIterable<Page<T>> query(Consumer<QueryEnhancedRequest.Builder> requestConsumer); @Override SdkIterable<Page<T>> query(QueryConditional queryConditional); @Override SdkIterable<Page<T>> scan(ScanEnhancedRequest request); @Override SdkIterable<Page<T>> scan(Consumer<ScanEnhancedRequest.Builder> requestConsumer); @Override SdkIterable<Page<T>> scan(); @Override DynamoDbEnhancedClientExtension mapperExtension(); @Override TableSchema<T> tableSchema(); DynamoDbClient dynamoDbClient(); String tableName(); String indexName(); @Override Key keyFrom(T item); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void keyFrom_secondaryIndex_partitionAndSort() { FakeItemWithIndices item = FakeItemWithIndices.createUniqueFakeItemWithIndices(); DefaultDynamoDbIndex<FakeItemWithIndices> dynamoDbMappedIndex = new DefaultDynamoDbIndex<>(mockDynamoDbClient, mockDynamoDbEnhancedClientExtension, FakeItemWithIndices.getTableSchema(), "test_table", "gsi_1"); Key key = dynamoDbMappedIndex.keyFrom(item); assertThat(key.partitionKeyValue(), is(stringValue(item.getGsiId()))); assertThat(key.sortKeyValue(), is(Optional.of(stringValue(item.getGsiSort())))); }
@Test public void keyFrom_secondaryIndex_partitionOnly() { FakeItemWithIndices item = FakeItemWithIndices.createUniqueFakeItemWithIndices(); DefaultDynamoDbIndex<FakeItemWithIndices> dynamoDbMappedIndex = new DefaultDynamoDbIndex<>(mockDynamoDbClient, mockDynamoDbEnhancedClientExtension, FakeItemWithIndices.getTableSchema(), "test_table", "gsi_2"); Key key = dynamoDbMappedIndex.keyFrom(item); assertThat(key.partitionKeyValue(), is(stringValue(item.getGsiId()))); assertThat(key.sortKeyValue(), is(Optional.empty())); } |
### Question:
ExtensionResolver { public static DynamoDbEnhancedClientExtension resolveExtensions(List<DynamoDbEnhancedClientExtension> extensions) { if (extensions == null || extensions.isEmpty()) { return null; } if (extensions.size() == 1) { return extensions.get(0); } return ChainExtension.create(extensions); } private ExtensionResolver(); static List<DynamoDbEnhancedClientExtension> defaultExtensions(); static DynamoDbEnhancedClientExtension resolveExtensions(List<DynamoDbEnhancedClientExtension> extensions); }### Answer:
@Test public void resolveExtensions_null() { assertThat(ExtensionResolver.resolveExtensions(null)).isNull(); }
@Test public void resolveExtensions_empty() { assertThat(ExtensionResolver.resolveExtensions(emptyList())).isNull(); }
@Test public void resolveExtensions_singleton() { assertThat(ExtensionResolver.resolveExtensions(singletonList(mockExtension1))).isSameAs(mockExtension1); }
@Test public void resolveExtensions_multiple_beforeWrite_correctCallingOrder() { DynamoDbEnhancedClientExtension extension = ExtensionResolver.resolveExtensions(Arrays.asList(mockExtension1, mockExtension2)); extension.beforeWrite(mock(DynamoDbExtensionContext.BeforeWrite.class)); InOrder inOrder = Mockito.inOrder(mockExtension1, mockExtension2); inOrder.verify(mockExtension1).beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class)); inOrder.verify(mockExtension2).beforeWrite(any(DynamoDbExtensionContext.BeforeWrite.class)); inOrder.verifyNoMoreInteractions(); }
@Test public void resolveExtensions_multiple_afterRead_correctCallingOrder() { DynamoDbEnhancedClientExtension extension = ExtensionResolver.resolveExtensions(Arrays.asList(mockExtension1, mockExtension2)); extension.afterRead(mock(DynamoDbExtensionContext.AfterRead.class)); InOrder inOrder = Mockito.inOrder(mockExtension1, mockExtension2); inOrder.verify(mockExtension2).afterRead(any(DynamoDbExtensionContext.AfterRead.class)); inOrder.verify(mockExtension1).afterRead(any(DynamoDbExtensionContext.AfterRead.class)); inOrder.verifyNoMoreInteractions(); } |
### Question:
ExtensionResolver { public static List<DynamoDbEnhancedClientExtension> defaultExtensions() { return DEFAULT_EXTENSIONS; } private ExtensionResolver(); static List<DynamoDbEnhancedClientExtension> defaultExtensions(); static DynamoDbEnhancedClientExtension resolveExtensions(List<DynamoDbEnhancedClientExtension> extensions); }### Answer:
@Test public void defaultExtensions_isImmutable() { List<DynamoDbEnhancedClientExtension> defaultExtensions = ExtensionResolver.defaultExtensions(); assertThatThrownBy(() -> defaultExtensions.add(mockExtension1)).isInstanceOf(UnsupportedOperationException.class); } |
### Question:
DefaultDynamoDbEnhancedClient implements DynamoDbEnhancedClient { @Override public <T> DefaultDynamoDbTable<T> table(String tableName, TableSchema<T> tableSchema) { return new DefaultDynamoDbTable<>(dynamoDbClient, extension, tableSchema, tableName); } private DefaultDynamoDbEnhancedClient(Builder builder); static Builder builder(); @Override DefaultDynamoDbTable<T> table(String tableName, TableSchema<T> tableSchema); @Override BatchGetResultPageIterable batchGetItem(BatchGetItemEnhancedRequest request); @Override BatchGetResultPageIterable batchGetItem(Consumer<BatchGetItemEnhancedRequest.Builder> requestConsumer); @Override BatchWriteResult batchWriteItem(BatchWriteItemEnhancedRequest request); @Override BatchWriteResult batchWriteItem(Consumer<BatchWriteItemEnhancedRequest.Builder> requestConsumer); @Override List<Document> transactGetItems(TransactGetItemsEnhancedRequest request); @Override List<Document> transactGetItems(
Consumer<TransactGetItemsEnhancedRequest.Builder> requestConsumer); @Override Void transactWriteItems(TransactWriteItemsEnhancedRequest request); @Override Void transactWriteItems(Consumer<TransactWriteItemsEnhancedRequest.Builder> requestConsumer); DynamoDbClient dynamoDbClient(); DynamoDbEnhancedClientExtension mapperExtension(); Builder toBuilder(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void table() { DefaultDynamoDbTable<Object> mappedTable = dynamoDbEnhancedClient.table("table-name", mockTableSchema); assertThat(mappedTable.dynamoDbClient(), is(mockDynamoDbClient)); assertThat(mappedTable.mapperExtension(), is(mockDynamoDbEnhancedClientExtension)); assertThat(mappedTable.tableSchema(), is(mockTableSchema)); assertThat(mappedTable.tableName(), is("table-name")); } |
### Question:
DefaultDynamoDbEnhancedClient implements DynamoDbEnhancedClient { public Builder toBuilder() { return builder().dynamoDbClient(this.dynamoDbClient).extensions(this.extension); } private DefaultDynamoDbEnhancedClient(Builder builder); static Builder builder(); @Override DefaultDynamoDbTable<T> table(String tableName, TableSchema<T> tableSchema); @Override BatchGetResultPageIterable batchGetItem(BatchGetItemEnhancedRequest request); @Override BatchGetResultPageIterable batchGetItem(Consumer<BatchGetItemEnhancedRequest.Builder> requestConsumer); @Override BatchWriteResult batchWriteItem(BatchWriteItemEnhancedRequest request); @Override BatchWriteResult batchWriteItem(Consumer<BatchWriteItemEnhancedRequest.Builder> requestConsumer); @Override List<Document> transactGetItems(TransactGetItemsEnhancedRequest request); @Override List<Document> transactGetItems(
Consumer<TransactGetItemsEnhancedRequest.Builder> requestConsumer); @Override Void transactWriteItems(TransactWriteItemsEnhancedRequest request); @Override Void transactWriteItems(Consumer<TransactWriteItemsEnhancedRequest.Builder> requestConsumer); DynamoDbClient dynamoDbClient(); DynamoDbEnhancedClientExtension mapperExtension(); Builder toBuilder(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void toBuilder() { DefaultDynamoDbEnhancedClient copiedObject = dynamoDbEnhancedClient.toBuilder().build(); assertThat(copiedObject, is(dynamoDbEnhancedClient)); } |
### Question:
DefaultDynamoDbTable implements DynamoDbTable<T> { @Override public DefaultDynamoDbIndex<T> index(String indexName) { tableSchema.tableMetadata().indexPartitionKey(indexName); return new DefaultDynamoDbIndex<>(dynamoDbClient, extension, tableSchema, tableName, indexName); } DefaultDynamoDbTable(DynamoDbClient dynamoDbClient,
DynamoDbEnhancedClientExtension extension,
TableSchema<T> tableSchema,
String tableName); @Override DynamoDbEnhancedClientExtension mapperExtension(); @Override TableSchema<T> tableSchema(); DynamoDbClient dynamoDbClient(); String tableName(); @Override DefaultDynamoDbIndex<T> index(String indexName); @Override void createTable(CreateTableEnhancedRequest request); @Override void createTable(Consumer<CreateTableEnhancedRequest.Builder> requestConsumer); @Override void createTable(); @Override T deleteItem(DeleteItemEnhancedRequest request); @Override T deleteItem(Consumer<DeleteItemEnhancedRequest.Builder> requestConsumer); @Override T deleteItem(Key key); @Override T deleteItem(T keyItem); @Override T getItem(GetItemEnhancedRequest request); @Override T getItem(Consumer<GetItemEnhancedRequest.Builder> requestConsumer); @Override T getItem(Key key); @Override T getItem(T keyItem); @Override PageIterable<T> query(QueryEnhancedRequest request); @Override PageIterable<T> query(Consumer<QueryEnhancedRequest.Builder> requestConsumer); @Override PageIterable<T> query(QueryConditional queryConditional); @Override void putItem(PutItemEnhancedRequest<T> request); @Override void putItem(Consumer<PutItemEnhancedRequest.Builder<T>> requestConsumer); @Override void putItem(T item); @Override PageIterable<T> scan(ScanEnhancedRequest request); @Override PageIterable<T> scan(Consumer<ScanEnhancedRequest.Builder> requestConsumer); @Override PageIterable<T> scan(); @Override T updateItem(UpdateItemEnhancedRequest<T> request); @Override T updateItem(Consumer<UpdateItemEnhancedRequest.Builder<T>> requestConsumer); @Override T updateItem(T item); @Override Key keyFrom(T item); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void index_invalidIndex_throwsIllegalArgumentException() { DefaultDynamoDbTable<FakeItemWithIndices> dynamoDbMappedTable = new DefaultDynamoDbTable<>(mockDynamoDbClient, mockDynamoDbEnhancedClientExtension, FakeItemWithIndices.getTableSchema(), TABLE_NAME); dynamoDbMappedTable.index("invalid"); } |
### Question:
DefaultDynamoDbTable implements DynamoDbTable<T> { @Override public Key keyFrom(T item) { return createKeyFromItem(item, tableSchema, TableMetadata.primaryIndexName()); } DefaultDynamoDbTable(DynamoDbClient dynamoDbClient,
DynamoDbEnhancedClientExtension extension,
TableSchema<T> tableSchema,
String tableName); @Override DynamoDbEnhancedClientExtension mapperExtension(); @Override TableSchema<T> tableSchema(); DynamoDbClient dynamoDbClient(); String tableName(); @Override DefaultDynamoDbIndex<T> index(String indexName); @Override void createTable(CreateTableEnhancedRequest request); @Override void createTable(Consumer<CreateTableEnhancedRequest.Builder> requestConsumer); @Override void createTable(); @Override T deleteItem(DeleteItemEnhancedRequest request); @Override T deleteItem(Consumer<DeleteItemEnhancedRequest.Builder> requestConsumer); @Override T deleteItem(Key key); @Override T deleteItem(T keyItem); @Override T getItem(GetItemEnhancedRequest request); @Override T getItem(Consumer<GetItemEnhancedRequest.Builder> requestConsumer); @Override T getItem(Key key); @Override T getItem(T keyItem); @Override PageIterable<T> query(QueryEnhancedRequest request); @Override PageIterable<T> query(Consumer<QueryEnhancedRequest.Builder> requestConsumer); @Override PageIterable<T> query(QueryConditional queryConditional); @Override void putItem(PutItemEnhancedRequest<T> request); @Override void putItem(Consumer<PutItemEnhancedRequest.Builder<T>> requestConsumer); @Override void putItem(T item); @Override PageIterable<T> scan(ScanEnhancedRequest request); @Override PageIterable<T> scan(Consumer<ScanEnhancedRequest.Builder> requestConsumer); @Override PageIterable<T> scan(); @Override T updateItem(UpdateItemEnhancedRequest<T> request); @Override T updateItem(Consumer<UpdateItemEnhancedRequest.Builder<T>> requestConsumer); @Override T updateItem(T item); @Override Key keyFrom(T item); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void keyFrom_primaryIndex_partitionAndSort() { FakeItemWithSort item = FakeItemWithSort.createUniqueFakeItemWithSort(); DefaultDynamoDbTable<FakeItemWithSort> dynamoDbMappedIndex = new DefaultDynamoDbTable<>(mockDynamoDbClient, mockDynamoDbEnhancedClientExtension, FakeItemWithSort.getTableSchema(), "test_table"); Key key = dynamoDbMappedIndex.keyFrom(item); assertThat(key.partitionKeyValue(), is(stringValue(item.getId()))); assertThat(key.sortKeyValue(), is(Optional.of(stringValue(item.getSort())))); }
@Test public void keyFrom_primaryIndex_partitionOnly() { FakeItem item = FakeItem.createUniqueFakeItem(); DefaultDynamoDbTable<FakeItem> dynamoDbMappedIndex = new DefaultDynamoDbTable<>(mockDynamoDbClient, mockDynamoDbEnhancedClientExtension, FakeItem.getTableSchema(), "test_table"); Key key = dynamoDbMappedIndex.keyFrom(item); assertThat(key.partitionKeyValue(), is(stringValue(item.getId()))); assertThat(key.sortKeyValue(), is(Optional.empty())); }
@Test public void keyFrom_primaryIndex_partitionAndNullSort() { FakeItemWithSort item = FakeItemWithSort.createUniqueFakeItemWithoutSort(); DefaultDynamoDbTable<FakeItemWithSort> dynamoDbMappedIndex = new DefaultDynamoDbTable<>(mockDynamoDbClient, mockDynamoDbEnhancedClientExtension, FakeItemWithSort.getTableSchema(), "test_table"); Key key = dynamoDbMappedIndex.keyFrom(item); assertThat(key.partitionKeyValue(), is(stringValue(item.getId()))); assertThat(key.sortKeyValue(), is(Optional.empty())); } |
### Question:
DefaultDynamoDbAsyncIndex implements DynamoDbAsyncIndex<T> { @Override public Key keyFrom(T item) { return createKeyFromItem(item, tableSchema, indexName); } DefaultDynamoDbAsyncIndex(DynamoDbAsyncClient dynamoDbClient,
DynamoDbEnhancedClientExtension extension,
TableSchema<T> tableSchema,
String tableName,
String indexName); @Override SdkPublisher<Page<T>> query(QueryEnhancedRequest request); @Override SdkPublisher<Page<T>> query(Consumer<QueryEnhancedRequest.Builder> requestConsumer); @Override SdkPublisher<Page<T>> query(QueryConditional queryConditional); @Override SdkPublisher<Page<T>> scan(ScanEnhancedRequest request); @Override SdkPublisher<Page<T>> scan(Consumer<ScanEnhancedRequest.Builder> requestConsumer); @Override SdkPublisher<Page<T>> scan(); @Override DynamoDbEnhancedClientExtension mapperExtension(); @Override TableSchema<T> tableSchema(); DynamoDbAsyncClient dynamoDbClient(); String tableName(); String indexName(); @Override Key keyFrom(T item); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void keyFrom_secondaryIndex_partitionAndSort() { FakeItemWithIndices item = FakeItemWithIndices.createUniqueFakeItemWithIndices(); DefaultDynamoDbAsyncIndex<FakeItemWithIndices> dynamoDbMappedIndex = new DefaultDynamoDbAsyncIndex<>(mockDynamoDbAsyncClient, mockDynamoDbEnhancedClientExtension, FakeItemWithIndices.getTableSchema(), "test_table", "gsi_1"); Key key = dynamoDbMappedIndex.keyFrom(item); assertThat(key.partitionKeyValue(), is(stringValue(item.getGsiId()))); assertThat(key.sortKeyValue(), is(Optional.of(stringValue(item.getGsiSort())))); }
@Test public void keyFrom_secondaryIndex_partitionOnly() { FakeItemWithIndices item = FakeItemWithIndices.createUniqueFakeItemWithIndices(); DefaultDynamoDbAsyncIndex<FakeItemWithIndices> dynamoDbMappedIndex = new DefaultDynamoDbAsyncIndex<>(mockDynamoDbAsyncClient, mockDynamoDbEnhancedClientExtension, FakeItemWithIndices.getTableSchema(), "test_table", "gsi_2"); Key key = dynamoDbMappedIndex.keyFrom(item); assertThat(key.partitionKeyValue(), is(stringValue(item.getGsiId()))); assertThat(key.sortKeyValue(), is(Optional.empty())); } |
### Question:
DefaultDynamoDbAsyncTable implements DynamoDbAsyncTable<T> { @Override public DefaultDynamoDbAsyncIndex<T> index(String indexName) { tableSchema.tableMetadata().indexPartitionKey(indexName); return new DefaultDynamoDbAsyncIndex<>(dynamoDbClient, extension, tableSchema, tableName, indexName); } DefaultDynamoDbAsyncTable(DynamoDbAsyncClient dynamoDbClient,
DynamoDbEnhancedClientExtension extension,
TableSchema<T> tableSchema,
String tableName); @Override DynamoDbEnhancedClientExtension mapperExtension(); @Override TableSchema<T> tableSchema(); DynamoDbAsyncClient dynamoDbClient(); String tableName(); @Override DefaultDynamoDbAsyncIndex<T> index(String indexName); @Override CompletableFuture<Void> createTable(CreateTableEnhancedRequest request); @Override CompletableFuture<Void> createTable(Consumer<CreateTableEnhancedRequest.Builder> requestConsumer); @Override CompletableFuture<Void> createTable(); @Override CompletableFuture<T> deleteItem(DeleteItemEnhancedRequest request); @Override CompletableFuture<T> deleteItem(Consumer<DeleteItemEnhancedRequest.Builder> requestConsumer); @Override CompletableFuture<T> deleteItem(Key key); @Override CompletableFuture<T> deleteItem(T keyItem); @Override CompletableFuture<T> getItem(GetItemEnhancedRequest request); @Override CompletableFuture<T> getItem(Consumer<GetItemEnhancedRequest.Builder> requestConsumer); @Override CompletableFuture<T> getItem(Key key); @Override CompletableFuture<T> getItem(T keyItem); @Override PagePublisher<T> query(QueryEnhancedRequest request); @Override PagePublisher<T> query(Consumer<QueryEnhancedRequest.Builder> requestConsumer); @Override PagePublisher<T> query(QueryConditional queryConditional); @Override CompletableFuture<Void> putItem(PutItemEnhancedRequest<T> request); @Override CompletableFuture<Void> putItem(Consumer<PutItemEnhancedRequest.Builder<T>> requestConsumer); @Override CompletableFuture<Void> putItem(T item); @Override PagePublisher<T> scan(ScanEnhancedRequest request); @Override PagePublisher<T> scan(Consumer<ScanEnhancedRequest.Builder> requestConsumer); @Override PagePublisher<T> scan(); @Override CompletableFuture<T> updateItem(UpdateItemEnhancedRequest<T> request); @Override CompletableFuture<T> updateItem(Consumer<UpdateItemEnhancedRequest.Builder<T>> requestConsumer); @Override CompletableFuture<T> updateItem(T item); @Override Key keyFrom(T item); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void index_invalidIndex_throwsIllegalArgumentException() { DefaultDynamoDbAsyncTable<FakeItemWithIndices> dynamoDbMappedTable = new DefaultDynamoDbAsyncTable<>(mockDynamoDbAsyncClient, mockDynamoDbEnhancedClientExtension, FakeItemWithIndices.getTableSchema(), TABLE_NAME); dynamoDbMappedTable.index("invalid"); } |
### Question:
CreateBucketInterceptor implements ExecutionInterceptor { @Override public SdkRequest modifyRequest(Context.ModifyRequest context, ExecutionAttributes executionAttributes) { SdkRequest sdkRequest = context.request(); if (sdkRequest instanceof CreateBucketRequest) { CreateBucketRequest request = (CreateBucketRequest) sdkRequest; validateBucketNameIsS3Compatible(request.bucket()); if (request.createBucketConfiguration() == null || request.createBucketConfiguration().locationConstraint() == null) { Region region = executionAttributes.getAttribute(AwsExecutionAttribute.AWS_REGION); sdkRequest = request.toBuilder() .createBucketConfiguration(toLocationConstraint(region)) .build(); } } return sdkRequest; } @Override SdkRequest modifyRequest(Context.ModifyRequest context, ExecutionAttributes executionAttributes); }### Answer:
@Test public void modifyRequest_DoesNotOverrideExistingLocationConstraint() { CreateBucketRequest request = CreateBucketRequest.builder() .bucket("test-bucket") .createBucketConfiguration(CreateBucketConfiguration.builder() .locationConstraint( "us-west-2") .build()) .build(); Context.ModifyRequest context = () -> request; ExecutionAttributes attributes = new ExecutionAttributes() .putAttribute(AwsExecutionAttribute.AWS_REGION, Region.US_EAST_1); SdkRequest modifiedRequest = new CreateBucketInterceptor().modifyRequest(context, attributes); String locationConstraint = ((CreateBucketRequest) modifiedRequest).createBucketConfiguration().locationConstraintAsString(); assertThat(locationConstraint).isEqualToIgnoringCase("us-west-2"); }
@Test public void modifyRequest_UpdatesLocationConstraint_When_NullCreateBucketConfiguration() { CreateBucketRequest request = CreateBucketRequest.builder() .bucket("test-bucket") .build(); Context.ModifyRequest context = () -> request; ExecutionAttributes attributes = new ExecutionAttributes() .putAttribute(AwsExecutionAttribute.AWS_REGION, Region.US_EAST_2); SdkRequest modifiedRequest = new CreateBucketInterceptor().modifyRequest(context, attributes); String locationConstraint = ((CreateBucketRequest) modifiedRequest).createBucketConfiguration().locationConstraintAsString(); assertThat(locationConstraint).isEqualToIgnoringCase("us-east-2"); }
@Test public void modifyRequest_UpdatesLocationConstraint_When_NullLocationConstraint() { CreateBucketRequest request = CreateBucketRequest.builder() .bucket("test-bucket") .createBucketConfiguration(CreateBucketConfiguration.builder() .build()) .build(); Context.ModifyRequest context = () -> request; ExecutionAttributes attributes = new ExecutionAttributes() .putAttribute(AwsExecutionAttribute.AWS_REGION, Region.US_WEST_2); SdkRequest modifiedRequest = new CreateBucketInterceptor().modifyRequest(context, attributes); String locationConstraint = ((CreateBucketRequest) modifiedRequest).createBucketConfiguration().locationConstraintAsString(); assertThat(locationConstraint).isEqualToIgnoringCase("us-west-2"); }
@Test public void modifyRequest_UsEast1_UsesNullBucketConfiguration() { CreateBucketRequest request = CreateBucketRequest.builder() .bucket("test-bucket") .createBucketConfiguration(CreateBucketConfiguration.builder() .build()) .build(); Context.ModifyRequest context = () -> request; ExecutionAttributes attributes = new ExecutionAttributes() .putAttribute(AwsExecutionAttribute.AWS_REGION, Region.US_EAST_1); SdkRequest modifiedRequest = new CreateBucketInterceptor().modifyRequest(context, attributes); assertThat(((CreateBucketRequest) modifiedRequest).createBucketConfiguration()).isNull(); } |
### Question:
GetObjectPresignRequest extends PresignRequest implements ToCopyableBuilder<GetObjectPresignRequest.Builder, GetObjectPresignRequest> { public static Builder builder() { return new DefaultBuilder(); } private GetObjectPresignRequest(DefaultBuilder builder); static Builder builder(); GetObjectRequest getObjectRequest(); @Override Builder toBuilder(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void build_missingProperty_getObjectRequest() { assertThatThrownBy(() -> GetObjectPresignRequest.builder() .signatureDuration(Duration.ofSeconds(123L)) .build()) .isInstanceOf(NullPointerException.class) .hasMessageContaining("getObjectRequest"); } |
### Question:
ConverterProviderResolver { public static AttributeConverterProvider resolveProviders(List<AttributeConverterProvider> providers) { if (providers == null || providers.isEmpty()) { return null; } if (providers.size() == 1) { return providers.get(0); } return ChainConverterProvider.create(providers); } private ConverterProviderResolver(); static AttributeConverterProvider defaultConverterProvider(); static AttributeConverterProvider resolveProviders(List<AttributeConverterProvider> providers); }### Answer:
@Test public void resolveProviders_null() { assertThat(ConverterProviderResolver.resolveProviders(null)).isNull(); }
@Test public void resolveProviders_empty() { assertThat(ConverterProviderResolver.resolveProviders(emptyList())).isNull(); }
@Test public void resolveProviders_singleton() { assertThat(ConverterProviderResolver.resolveProviders(singletonList(mockConverterProvider1))) .isSameAs(mockConverterProvider1); }
@Test public void resolveProviders_multiple() { AttributeConverterProvider result = ConverterProviderResolver.resolveProviders( Arrays.asList(mockConverterProvider1, mockConverterProvider2)); assertThat(result).isNotNull(); assertThat(result).isInstanceOf(ChainConverterProvider.class); } |
### Question:
ConverterProviderResolver { public static AttributeConverterProvider defaultConverterProvider() { return DEFAULT_ATTRIBUTE_CONVERTER; } private ConverterProviderResolver(); static AttributeConverterProvider defaultConverterProvider(); static AttributeConverterProvider resolveProviders(List<AttributeConverterProvider> providers); }### Answer:
@Test public void defaultProvider_returnsInstance() { AttributeConverterProvider defaultProvider = ConverterProviderResolver.defaultConverterProvider(); assertThat(defaultProvider).isNotNull(); assertThat(defaultProvider).isInstanceOf(DefaultAttributeConverterProvider.class); } |
### Question:
EnhancedClientUtils { public static Key createKeyFromMap(Map<String, AttributeValue> itemMap, TableSchema<?> tableSchema, String indexName) { String partitionKeyName = tableSchema.tableMetadata().indexPartitionKey(indexName); Optional<String> sortKeyName = tableSchema.tableMetadata().indexSortKey(indexName); AttributeValue partitionKeyValue = itemMap.get(partitionKeyName); Optional<AttributeValue> sortKeyValue = sortKeyName.map(itemMap::get); return sortKeyValue.map( attributeValue -> Key.builder() .partitionValue(partitionKeyValue) .sortValue(attributeValue) .build()) .orElseGet( () -> Key.builder() .partitionValue(partitionKeyValue).build()); } private EnhancedClientUtils(); static String cleanAttributeName(String key); static T readAndTransformSingleItem(Map<String, AttributeValue> itemMap,
TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension); static Page<ItemT> readAndTransformPaginatedItems(
ResponseT response,
TableSchema<ItemT> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension,
Function<ResponseT, List<Map<String, AttributeValue>>> getItems,
Function<ResponseT, Map<String, AttributeValue>> getLastEvaluatedKey); static Key createKeyFromItem(T item, TableSchema<T> tableSchema, String indexName); static Key createKeyFromMap(Map<String, AttributeValue> itemMap,
TableSchema<?> tableSchema,
String indexName); static List<T> getItemsFromSupplier(List<Supplier<T>> itemSupplierList); static boolean isNullAttributeValue(AttributeValue attributeValue); }### Answer:
@Test public void createKeyFromMap_partitionOnly() { Map<String, AttributeValue> itemMap = new HashMap<>(); itemMap.put("id", PARTITION_VALUE); Key key = EnhancedClientUtils.createKeyFromMap(itemMap, FakeItem.getTableSchema(), TableMetadata.primaryIndexName()); assertThat(key.partitionKeyValue()).isEqualTo(PARTITION_VALUE); assertThat(key.sortKeyValue()).isEmpty(); }
@Test public void createKeyFromMap_partitionAndSort() { Map<String, AttributeValue> itemMap = new HashMap<>(); itemMap.put("id", PARTITION_VALUE); itemMap.put("sort", SORT_VALUE); Key key = EnhancedClientUtils.createKeyFromMap(itemMap, FakeItemWithSort.getTableSchema(), TableMetadata.primaryIndexName()); assertThat(key.partitionKeyValue()).isEqualTo(PARTITION_VALUE); assertThat(key.sortKeyValue()).isEqualTo(Optional.of(SORT_VALUE)); } |
### Question:
EnhancedClientUtils { public static String cleanAttributeName(String key) { boolean somethingChanged = false; char[] chars = key.toCharArray(); for (int i = 0; i < chars.length; ++i) { if (chars[i] == '*' || chars[i] == '.' || chars[i] == '-' || chars[i] == '#' || chars[i] == ':') { chars[i] = '_'; somethingChanged = true; } } return somethingChanged ? new String(chars) : key; } private EnhancedClientUtils(); static String cleanAttributeName(String key); static T readAndTransformSingleItem(Map<String, AttributeValue> itemMap,
TableSchema<T> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension); static Page<ItemT> readAndTransformPaginatedItems(
ResponseT response,
TableSchema<ItemT> tableSchema,
OperationContext operationContext,
DynamoDbEnhancedClientExtension dynamoDbEnhancedClientExtension,
Function<ResponseT, List<Map<String, AttributeValue>>> getItems,
Function<ResponseT, Map<String, AttributeValue>> getLastEvaluatedKey); static Key createKeyFromItem(T item, TableSchema<T> tableSchema, String indexName); static Key createKeyFromMap(Map<String, AttributeValue> itemMap,
TableSchema<?> tableSchema,
String indexName); static List<T> getItemsFromSupplier(List<Supplier<T>> itemSupplierList); static boolean isNullAttributeValue(AttributeValue attributeValue); }### Answer:
@Test public void cleanAttributeName_cleansSpecialCharacters() { String result = EnhancedClientUtils.cleanAttributeName("a*b.c-d:e#f"); assertThat(result).isEqualTo("a_b_c_d_e_f"); } |
### Question:
VersionedRecordExtension implements DynamoDbEnhancedClientExtension { public static Builder builder() { return new Builder(); } private VersionedRecordExtension(); static Builder builder(); @Override WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite context); }### Answer:
@Test public void beforeRead_doesNotTransformObject() { FakeItem fakeItem = createUniqueFakeItem(); Map<String, AttributeValue> fakeItemMap = FakeItem.getTableSchema().itemToMap(fakeItem, true); ReadModification result = versionedRecordExtension.afterRead(DefaultDynamoDbExtensionContext .builder() .items(fakeItemMap) .tableMetadata(FakeItem.getTableMetadata()) .operationContext(PRIMARY_CONTEXT).build()); assertThat(result, is(ReadModification.builder().build())); } |
### Question:
Expression { public static String joinExpressions(String expression1, String expression2, String joinToken) { if (expression1 == null) { return expression2; } if (expression2 == null) { return expression1; } return "(" + expression1 + ")" + joinToken + "(" + expression2 + ")"; } private Expression(String expression,
Map<String, AttributeValue> expressionValues,
Map<String, String> expressionNames); static Builder builder(); static Expression join(Expression expression1, Expression expression2, String joinToken); static String joinExpressions(String expression1, String expression2, String joinToken); static Map<String, AttributeValue> joinValues(Map<String, AttributeValue> expressionValues1,
Map<String, AttributeValue> expressionValues2); static Map<String, String> joinNames(Map<String, String> expressionNames1,
Map<String, String> expressionNames2); String expression(); Map<String, AttributeValue> expressionValues(); Map<String, String> expressionNames(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void joinExpressions_correctlyJoins() { String result = Expression.joinExpressions("one", "two", " AND "); assertThat(result, is("(one) AND (two)")); } |
### Question:
Expression { public static Map<String, String> joinNames(Map<String, String> expressionNames1, Map<String, String> expressionNames2) { if (expressionNames1 == null) { return expressionNames2; } if (expressionNames2 == null) { return expressionNames1; } Map<String, String> result = new HashMap<>(expressionNames1); expressionNames2.forEach((key, value) -> { String oldValue = result.put(key, value); if (oldValue != null && !oldValue.equals(value)) { throw new IllegalArgumentException( String.format("Attempt to coalesce two expressions with conflicting expression names. " + "Expression name key = '%s'", key)); } }); return Collections.unmodifiableMap(result); } private Expression(String expression,
Map<String, AttributeValue> expressionValues,
Map<String, String> expressionNames); static Builder builder(); static Expression join(Expression expression1, Expression expression2, String joinToken); static String joinExpressions(String expression1, String expression2, String joinToken); static Map<String, AttributeValue> joinValues(Map<String, AttributeValue> expressionValues1,
Map<String, AttributeValue> expressionValues2); static Map<String, String> joinNames(Map<String, String> expressionNames1,
Map<String, String> expressionNames2); String expression(); Map<String, AttributeValue> expressionValues(); Map<String, String> expressionNames(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void joinNames_correctlyJoins() { Map<String, String> names1 = new HashMap<>(); names1.put("one", "1"); names1.put("two", "2"); Map<String, String> names2 = new HashMap<>(); names2.put("three", "3"); names2.put("four", "4"); Map<String, String> result = Expression.joinNames(names1, names2); assertThat(result.size(), is(4)); assertThat(result, hasEntry("one", "1")); assertThat(result, hasEntry("two", "2")); assertThat(result, hasEntry("three", "3")); assertThat(result, hasEntry("four", "4")); }
@Test public void joinNames_conflictingKey() { Map<String, String> names1 = new HashMap<>(); names1.put("one", "1"); names1.put("two", "2"); Map<String, String> names2 = new HashMap<>(); names2.put("three", "3"); names2.put("two", "4"); exception.expect(IllegalArgumentException.class); exception.expectMessage("two"); Expression.joinNames(names1, names2); } |
### Question:
Expression { public static Map<String, AttributeValue> joinValues(Map<String, AttributeValue> expressionValues1, Map<String, AttributeValue> expressionValues2) { if (expressionValues1 == null) { return expressionValues2; } if (expressionValues2 == null) { return expressionValues1; } Map<String, AttributeValue> result = new HashMap<>(expressionValues1); expressionValues2.forEach((key, value) -> { AttributeValue oldValue = result.put(key, value); if (oldValue != null && !oldValue.equals(value)) { throw new IllegalArgumentException( String.format("Attempt to coalesce two expressions with conflicting expression values. " + "Expression value key = '%s'", key)); } }); return Collections.unmodifiableMap(result); } private Expression(String expression,
Map<String, AttributeValue> expressionValues,
Map<String, String> expressionNames); static Builder builder(); static Expression join(Expression expression1, Expression expression2, String joinToken); static String joinExpressions(String expression1, String expression2, String joinToken); static Map<String, AttributeValue> joinValues(Map<String, AttributeValue> expressionValues1,
Map<String, AttributeValue> expressionValues2); static Map<String, String> joinNames(Map<String, String> expressionNames1,
Map<String, String> expressionNames2); String expression(); Map<String, AttributeValue> expressionValues(); Map<String, String> expressionNames(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void joinValues_correctlyJoins() { Map<String, AttributeValue> values1 = new HashMap<>(); values1.put("one", EnhancedAttributeValue.fromString("1").toAttributeValue()); values1.put("two", EnhancedAttributeValue.fromString("2").toAttributeValue()); Map<String, AttributeValue> values2 = new HashMap<>(); values2.put("three", EnhancedAttributeValue.fromString("3").toAttributeValue()); values2.put("four", EnhancedAttributeValue.fromString("4").toAttributeValue()); Map<String, AttributeValue> result = Expression.joinValues(values1, values2); assertThat(result.size(), is(4)); assertThat(result, hasEntry("one", EnhancedAttributeValue.fromString("1").toAttributeValue())); assertThat(result, hasEntry("two", EnhancedAttributeValue.fromString("2").toAttributeValue())); assertThat(result, hasEntry("three", EnhancedAttributeValue.fromString("3").toAttributeValue())); assertThat(result, hasEntry("four", EnhancedAttributeValue.fromString("4").toAttributeValue())); }
@Test public void joinValues_conflictingKey() { Map<String, AttributeValue> values1 = new HashMap<>(); values1.put("one", EnhancedAttributeValue.fromString("1").toAttributeValue()); values1.put("two", EnhancedAttributeValue.fromString("2").toAttributeValue()); Map<String, AttributeValue> values2 = new HashMap<>(); values2.put("three", EnhancedAttributeValue.fromString("3").toAttributeValue()); values2.put("two", EnhancedAttributeValue.fromString("4").toAttributeValue()); exception.expect(IllegalArgumentException.class); exception.expectMessage("two"); Expression.joinValues(values1, values2); } |
### Question:
StringUtils { public static String upperCase(final String str) { if (str == null) { return null; } return str.toUpperCase(Locale.ENGLISH); } private StringUtils(); static boolean isEmpty(final CharSequence cs); static boolean isBlank(final CharSequence cs); static boolean isNotBlank(final CharSequence cs); static String trim(final String str); static String trimToNull(final String str); static String trimToEmpty(final String str); static boolean equals(final String cs1, final String cs2); static String substring(final String str, int start); static String substring(final String str, int start, int end); static String upperCase(final String str); static String lowerCase(final String str); static String capitalize(final String str); static String uncapitalize(final String str); static String fromBytes(byte[] bytes, Charset charset); static boolean startsWithIgnoreCase(String str, String prefix); static String replacePrefixIgnoreCase(String str, String prefix, String replacement); static String replaceEach(final String text, final String[] searchList, final String[] replacementList); static Character findFirstOccurrence(String s, char ...charsToMatch); static boolean safeStringToBoolean(String value); }### Answer:
@Test public void testUpperCase() { assertNull(StringUtils.upperCase(null)); assertEquals("upperCase(String) failed", "FOO TEST THING", StringUtils.upperCase("fOo test THING")); assertEquals("upperCase(empty-string) failed", "", StringUtils.upperCase("")); } |
### Question:
StringUtils { public static String lowerCase(final String str) { if (str == null) { return null; } return str.toLowerCase(Locale.ENGLISH); } private StringUtils(); static boolean isEmpty(final CharSequence cs); static boolean isBlank(final CharSequence cs); static boolean isNotBlank(final CharSequence cs); static String trim(final String str); static String trimToNull(final String str); static String trimToEmpty(final String str); static boolean equals(final String cs1, final String cs2); static String substring(final String str, int start); static String substring(final String str, int start, int end); static String upperCase(final String str); static String lowerCase(final String str); static String capitalize(final String str); static String uncapitalize(final String str); static String fromBytes(byte[] bytes, Charset charset); static boolean startsWithIgnoreCase(String str, String prefix); static String replacePrefixIgnoreCase(String str, String prefix, String replacement); static String replaceEach(final String text, final String[] searchList, final String[] replacementList); static Character findFirstOccurrence(String s, char ...charsToMatch); static boolean safeStringToBoolean(String value); }### Answer:
@Test public void testLowerCase() { assertNull(StringUtils.lowerCase(null)); assertEquals("lowerCase(String) failed", "foo test thing", StringUtils.lowerCase("fOo test THING")); assertEquals("lowerCase(empty-string) failed", "", StringUtils.lowerCase("")); } |
### Question:
StringUtils { public static String capitalize(final String str) { if (str == null || str.length() == 0) { return str; } int firstCodepoint = str.codePointAt(0); int newCodePoint = Character.toTitleCase(firstCodepoint); if (firstCodepoint == newCodePoint) { return str; } int[] newCodePoints = new int[str.length()]; int outOffset = 0; newCodePoints[outOffset++] = newCodePoint; for (int inOffset = Character.charCount(firstCodepoint); inOffset < str.length(); ) { int codepoint = str.codePointAt(inOffset); newCodePoints[outOffset++] = codepoint; inOffset += Character.charCount(codepoint); } return new String(newCodePoints, 0, outOffset); } private StringUtils(); static boolean isEmpty(final CharSequence cs); static boolean isBlank(final CharSequence cs); static boolean isNotBlank(final CharSequence cs); static String trim(final String str); static String trimToNull(final String str); static String trimToEmpty(final String str); static boolean equals(final String cs1, final String cs2); static String substring(final String str, int start); static String substring(final String str, int start, int end); static String upperCase(final String str); static String lowerCase(final String str); static String capitalize(final String str); static String uncapitalize(final String str); static String fromBytes(byte[] bytes, Charset charset); static boolean startsWithIgnoreCase(String str, String prefix); static String replacePrefixIgnoreCase(String str, String prefix, String replacement); static String replaceEach(final String text, final String[] searchList, final String[] replacementList); static Character findFirstOccurrence(String s, char ...charsToMatch); static boolean safeStringToBoolean(String value); }### Answer:
@Test public void testCapitalize() { assertNull(StringUtils.capitalize(null)); assertEquals("capitalize(empty-string) failed", "", StringUtils.capitalize("")); assertEquals("capitalize(single-char-string) failed", "X", StringUtils.capitalize("x")); assertEquals("capitalize(String) failed", FOO_CAP, StringUtils.capitalize(FOO_CAP)); assertEquals("capitalize(string) failed", FOO_CAP, StringUtils.capitalize(FOO_UNCAP)); assertEquals("capitalize(String) is not using TitleCase", "\u01C8", StringUtils.capitalize("\u01C9")); assertNull(StringUtils.capitalize(null)); assertEquals("", StringUtils.capitalize("")); assertEquals("Cat", StringUtils.capitalize("cat")); assertEquals("CAt", StringUtils.capitalize("cAt")); assertEquals("'cat'", StringUtils.capitalize("'cat'")); } |
### Question:
StringUtils { public static String uncapitalize(final String str) { if (str == null || str.length() == 0) { return str; } int firstCodepoint = str.codePointAt(0); int newCodePoint = Character.toLowerCase(firstCodepoint); if (firstCodepoint == newCodePoint) { return str; } int[] newCodePoints = new int[str.length()]; int outOffset = 0; newCodePoints[outOffset++] = newCodePoint; for (int inOffset = Character.charCount(firstCodepoint); inOffset < str.length(); ) { int codepoint = str.codePointAt(inOffset); newCodePoints[outOffset++] = codepoint; inOffset += Character.charCount(codepoint); } return new String(newCodePoints, 0, outOffset); } private StringUtils(); static boolean isEmpty(final CharSequence cs); static boolean isBlank(final CharSequence cs); static boolean isNotBlank(final CharSequence cs); static String trim(final String str); static String trimToNull(final String str); static String trimToEmpty(final String str); static boolean equals(final String cs1, final String cs2); static String substring(final String str, int start); static String substring(final String str, int start, int end); static String upperCase(final String str); static String lowerCase(final String str); static String capitalize(final String str); static String uncapitalize(final String str); static String fromBytes(byte[] bytes, Charset charset); static boolean startsWithIgnoreCase(String str, String prefix); static String replacePrefixIgnoreCase(String str, String prefix, String replacement); static String replaceEach(final String text, final String[] searchList, final String[] replacementList); static Character findFirstOccurrence(String s, char ...charsToMatch); static boolean safeStringToBoolean(String value); }### Answer:
@Test public void testUnCapitalize() { assertNull(StringUtils.uncapitalize(null)); assertEquals("uncapitalize(String) failed", FOO_UNCAP, StringUtils.uncapitalize(FOO_CAP)); assertEquals("uncapitalize(string) failed", FOO_UNCAP, StringUtils.uncapitalize(FOO_UNCAP)); assertEquals("uncapitalize(empty-string) failed", "", StringUtils.uncapitalize("")); assertEquals("uncapitalize(single-char-string) failed", "x", StringUtils.uncapitalize("X")); assertEquals("cat", StringUtils.uncapitalize("cat")); assertEquals("cat", StringUtils.uncapitalize("Cat")); assertEquals("cAT", StringUtils.uncapitalize("CAT")); } |
### Question:
StringUtils { public static boolean startsWithIgnoreCase(String str, String prefix) { return str.regionMatches(true, 0, prefix, 0, prefix.length()); } private StringUtils(); static boolean isEmpty(final CharSequence cs); static boolean isBlank(final CharSequence cs); static boolean isNotBlank(final CharSequence cs); static String trim(final String str); static String trimToNull(final String str); static String trimToEmpty(final String str); static boolean equals(final String cs1, final String cs2); static String substring(final String str, int start); static String substring(final String str, int start, int end); static String upperCase(final String str); static String lowerCase(final String str); static String capitalize(final String str); static String uncapitalize(final String str); static String fromBytes(byte[] bytes, Charset charset); static boolean startsWithIgnoreCase(String str, String prefix); static String replacePrefixIgnoreCase(String str, String prefix, String replacement); static String replaceEach(final String text, final String[] searchList, final String[] replacementList); static Character findFirstOccurrence(String s, char ...charsToMatch); static boolean safeStringToBoolean(String value); }### Answer:
@Test public void testStartsWithIgnoreCase() { assertTrue(StringUtils.startsWithIgnoreCase("helloworld", "hello")); assertTrue(StringUtils.startsWithIgnoreCase("hELlOwOrlD", "hello")); assertFalse(StringUtils.startsWithIgnoreCase("hello", "world")); } |
### Question:
StringUtils { public static String replacePrefixIgnoreCase(String str, String prefix, String replacement) { return str.replaceFirst("(?i)" + prefix, replacement); } private StringUtils(); static boolean isEmpty(final CharSequence cs); static boolean isBlank(final CharSequence cs); static boolean isNotBlank(final CharSequence cs); static String trim(final String str); static String trimToNull(final String str); static String trimToEmpty(final String str); static boolean equals(final String cs1, final String cs2); static String substring(final String str, int start); static String substring(final String str, int start, int end); static String upperCase(final String str); static String lowerCase(final String str); static String capitalize(final String str); static String uncapitalize(final String str); static String fromBytes(byte[] bytes, Charset charset); static boolean startsWithIgnoreCase(String str, String prefix); static String replacePrefixIgnoreCase(String str, String prefix, String replacement); static String replaceEach(final String text, final String[] searchList, final String[] replacementList); static Character findFirstOccurrence(String s, char ...charsToMatch); static boolean safeStringToBoolean(String value); }### Answer:
@Test public void testReplacePrefixIgnoreCase() { assertEquals("lloWorld" ,replacePrefixIgnoreCase("helloWorld", "he", "")); assertEquals("lloWORld" ,replacePrefixIgnoreCase("helloWORld", "He", "")); assertEquals("llOwOrld" ,replacePrefixIgnoreCase("HEllOwOrld", "he", "")); } |
### Question:
StringUtils { public static Character findFirstOccurrence(String s, char ...charsToMatch) { int lowestIndex = Integer.MAX_VALUE; for (char toMatch : charsToMatch) { int currentIndex = s.indexOf(toMatch); if (currentIndex != -1 && currentIndex < lowestIndex) { lowestIndex = currentIndex; } } return lowestIndex == Integer.MAX_VALUE ? null : s.charAt(lowestIndex); } private StringUtils(); static boolean isEmpty(final CharSequence cs); static boolean isBlank(final CharSequence cs); static boolean isNotBlank(final CharSequence cs); static String trim(final String str); static String trimToNull(final String str); static String trimToEmpty(final String str); static boolean equals(final String cs1, final String cs2); static String substring(final String str, int start); static String substring(final String str, int start, int end); static String upperCase(final String str); static String lowerCase(final String str); static String capitalize(final String str); static String uncapitalize(final String str); static String fromBytes(byte[] bytes, Charset charset); static boolean startsWithIgnoreCase(String str, String prefix); static String replacePrefixIgnoreCase(String str, String prefix, String replacement); static String replaceEach(final String text, final String[] searchList, final String[] replacementList); static Character findFirstOccurrence(String s, char ...charsToMatch); static boolean safeStringToBoolean(String value); }### Answer:
@Test public void findFirstOccurrence() { assertEquals((Character) ':', StringUtils.findFirstOccurrence("abc:def/ghi:jkl/mno", ':', '/')); assertEquals((Character) ':', StringUtils.findFirstOccurrence("abc:def/ghi:jkl/mno", '/', ':')); }
@Test public void findFirstOccurrence_NoMatch() { assertNull(StringUtils.findFirstOccurrence("abc", ':')); } |
### Question:
StringUtils { public static boolean safeStringToBoolean(String value) { if (value.equalsIgnoreCase("true")) { return true; } else if (value.equalsIgnoreCase("false")) { return false; } throw new IllegalArgumentException("Value was defined as '" + value + "', but should be 'false' or 'true'"); } private StringUtils(); static boolean isEmpty(final CharSequence cs); static boolean isBlank(final CharSequence cs); static boolean isNotBlank(final CharSequence cs); static String trim(final String str); static String trimToNull(final String str); static String trimToEmpty(final String str); static boolean equals(final String cs1, final String cs2); static String substring(final String str, int start); static String substring(final String str, int start, int end); static String upperCase(final String str); static String lowerCase(final String str); static String capitalize(final String str); static String uncapitalize(final String str); static String fromBytes(byte[] bytes, Charset charset); static boolean startsWithIgnoreCase(String str, String prefix); static String replacePrefixIgnoreCase(String str, String prefix, String replacement); static String replaceEach(final String text, final String[] searchList, final String[] replacementList); static Character findFirstOccurrence(String s, char ...charsToMatch); static boolean safeStringToBoolean(String value); }### Answer:
@Test public void safeStringTooBoolean_mixedSpaceTrue_shouldReturnTrue() { assertTrue(StringUtils.safeStringToBoolean("TrUe")); }
@Test public void safeStringTooBoolean_mixedSpaceFalse_shouldReturnFalse() { assertFalse(StringUtils.safeStringToBoolean("fAlSE")); }
@Test(expected = IllegalArgumentException.class) public void safeStringTooBoolean_invalidValue_shouldThrowException() { assertFalse(StringUtils.safeStringToBoolean("foobar")); } |
### Question:
NumericUtils { public static Duration min(Duration a, Duration b) { return (a.compareTo(b) < 0) ? a : b; } private NumericUtils(); static int saturatedCast(long value); static Duration min(Duration a, Duration b); static Duration max(Duration a, Duration b); }### Answer:
@Test public void minTestDifferentDurations() { assertThat(min(SHORT_DURATION, LONG_DURATION), is(SHORT_DURATION)); }
@Test public void minTestDifferentDurationsReverse() { assertThat(min(LONG_DURATION, SHORT_DURATION), is(SHORT_DURATION)); }
@Test public void minTestSameDurations() { assertThat(min(SHORT_DURATION, SHORT_SAME_DURATION), is(SHORT_SAME_DURATION)); }
@Test public void minTestDifferentNegativeDurations() { assertThat(min(NEGATIVE_SHORT_DURATION, NEGATIVE_LONG_DURATION), is(NEGATIVE_LONG_DURATION)); }
@Test public void minTestNegativeSameDurations() { assertThat(min(NEGATIVE_SHORT_DURATION, NEGATIVE_SHORT_SAME_DURATION), is(NEGATIVE_SHORT_DURATION)); } |
### Question:
NumericUtils { public static Duration max(Duration a, Duration b) { return (a.compareTo(b) > 0) ? a : b; } private NumericUtils(); static int saturatedCast(long value); static Duration min(Duration a, Duration b); static Duration max(Duration a, Duration b); }### Answer:
@Test public void maxTestDifferentDurations() { assertThat(max(LONG_DURATION, SHORT_DURATION), is(LONG_DURATION)); }
@Test public void maxTestDifferentDurationsReverse() { assertThat(max(SHORT_DURATION, LONG_DURATION), is(LONG_DURATION)); }
@Test public void maxTestSameDurations() { assertThat(max(SHORT_DURATION, SHORT_SAME_DURATION), is(SHORT_SAME_DURATION)); }
@Test public void maxTestDifferentNegativeDurations() { assertThat(max(NEGATIVE_SHORT_DURATION, NEGATIVE_LONG_DURATION), is(NEGATIVE_SHORT_DURATION)); }
@Test public void maxTestNegativeSameDurations() { assertThat(max(NEGATIVE_SHORT_DURATION, NEGATIVE_SHORT_SAME_DURATION), is(NEGATIVE_SHORT_DURATION)); } |
### Question:
FunctionalUtils { public static <T> T invokeSafely(UnsafeSupplier<T> unsafeSupplier) { return safeSupplier(unsafeSupplier).get(); } private FunctionalUtils(); static void runAndLogError(Logger log, String errorMsg, UnsafeRunnable runnable); static Consumer<T> noOpConsumer(); static Runnable noOpRunnable(); static Consumer<I> safeConsumer(UnsafeConsumer<I> unsafeConsumer); static Function<T, R> safeFunction(UnsafeFunction<T, R> unsafeFunction); static Supplier<T> safeSupplier(UnsafeSupplier<T> unsafeSupplier); static Runnable safeRunnable(UnsafeRunnable unsafeRunnable); static Function<I, O> toFunction(Supplier<O> supplier); static T invokeSafely(UnsafeSupplier<T> unsafeSupplier); static void invokeSafely(UnsafeRunnable unsafeRunnable); }### Answer:
@Test public void checkedExceptionsAreConvertedToRuntimeExceptions() { assertThatExceptionOfType(RuntimeException.class) .isThrownBy(() -> invokeSafely(this::methodThatThrows)) .withCauseInstanceOf(Exception.class); }
@Test public void ioExceptionsAreConvertedToUncheckedIoExceptions() { assertThatExceptionOfType(UncheckedIOException.class) .isThrownBy(() -> invokeSafely(this::methodThatThrowsIOException)) .withCauseInstanceOf(IOException.class); }
@Test public void runtimeExceptionsAreNotWrapped() { assertThatExceptionOfType(RuntimeException.class) .isThrownBy(() -> invokeSafely(this::methodWithCheckedSignatureThatThrowsRuntimeException)) .withNoCause(); }
@Test public void interruptedExceptionShouldSetInterruptedOnTheThread() { assertThatExceptionOfType(RuntimeException.class) .isThrownBy(() -> invokeSafely(this::methodThatThrowsInterruptedException)) .withCauseInstanceOf(InterruptedException.class); assertThat(Thread.currentThread().isInterrupted()).isTrue(); Thread.interrupted(); } |
### Question:
FunctionalUtils { public static <I> Consumer<I> safeConsumer(UnsafeConsumer<I> unsafeConsumer) { return (input) -> { try { unsafeConsumer.accept(input); } catch (Exception e) { throw asRuntimeException(e); } }; } private FunctionalUtils(); static void runAndLogError(Logger log, String errorMsg, UnsafeRunnable runnable); static Consumer<T> noOpConsumer(); static Runnable noOpRunnable(); static Consumer<I> safeConsumer(UnsafeConsumer<I> unsafeConsumer); static Function<T, R> safeFunction(UnsafeFunction<T, R> unsafeFunction); static Supplier<T> safeSupplier(UnsafeSupplier<T> unsafeSupplier); static Runnable safeRunnable(UnsafeRunnable unsafeRunnable); static Function<I, O> toFunction(Supplier<O> supplier); static T invokeSafely(UnsafeSupplier<T> unsafeSupplier); static void invokeSafely(UnsafeRunnable unsafeRunnable); }### Answer:
@Test public void canUseConsumerThatThrowsCheckedExceptionInLambda() { Stream.of(DONT_THROW_EXCEPTION).forEach(safeConsumer(this::consumerMethodWithChecked)); }
@Test public void exceptionsForConsumersAreConverted() { assertThatExceptionOfType(RuntimeException.class) .isThrownBy(() -> Stream.of(THROW_EXCEPTION).forEach(safeConsumer(this::consumerMethodWithChecked))) .withCauseExactlyInstanceOf(Exception.class); } |
### Question:
SyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<RequestBody> modifyHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { if (shouldRecordChecksum(context.request(), SYNC, executionAttributes, context.httpRequest()) && context.requestBody().isPresent()) { SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(CHECKSUM, checksum); executionAttributes.putAttribute(SYNC_RECORDING_CHECKSUM, true); RequestBody requestBody = context.requestBody().get(); ChecksumCalculatingStreamProvider streamProvider = new ChecksumCalculatingStreamProvider(requestBody.contentStreamProvider(), checksum); return Optional.of(RequestBody.fromContentProvider(streamProvider, requestBody.contentLength(), requestBody.contentType())); } return context.requestBody(); } @Override Optional<RequestBody> modifyHttpContent(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override Optional<InputStream> modifyHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); }### Answer:
@Test public void modifyHttpContent_putObjectRequestChecksumEnabled_shouldWrapChecksumRequestBody() { ExecutionAttributes executionAttributes = getExecutionAttributes(); Context.ModifyHttpRequest modifyHttpRequest = InterceptorTestUtils.modifyHttpRequestContext(PutObjectRequest.builder().build()); Optional<RequestBody> requestBody = interceptor.modifyHttpContent(modifyHttpRequest, executionAttributes); assertThat(requestBody.isPresent()).isTrue(); assertThat(executionAttributes.getAttribute(CHECKSUM)).isNotNull(); assertThat(requestBody.get().contentStreamProvider()).isNotEqualTo(modifyHttpRequest.requestBody().get()); }
@Test public void modifyHttpContent_nonPutObjectRequest_shouldNotModify() { ExecutionAttributes executionAttributes = getExecutionAttributes(); Context.ModifyHttpRequest modifyHttpRequest = InterceptorTestUtils.modifyHttpRequestContext(GetObjectRequest.builder().build()); Optional<RequestBody> requestBody = interceptor.modifyHttpContent(modifyHttpRequest, executionAttributes); assertThat(requestBody).isEqualTo(modifyHttpRequest.requestBody()); }
@Test public void modifyHttpContent_putObjectRequest_checksumDisabled_shouldNotModify() { ExecutionAttributes executionAttributes = getExecutionAttributesWithChecksumDisabled(); Context.ModifyHttpRequest modifyHttpRequest = InterceptorTestUtils.modifyHttpRequestContext(GetObjectRequest.builder().build()); Optional<RequestBody> requestBody = interceptor.modifyHttpContent(modifyHttpRequest, executionAttributes); assertThat(requestBody).isEqualTo(modifyHttpRequest.requestBody()); } |
### Question:
FunctionalUtils { public static <T, R> Function<T, R> safeFunction(UnsafeFunction<T, R> unsafeFunction) { return t -> { try { return unsafeFunction.apply(t); } catch (Exception e) { throw asRuntimeException(e); } }; } private FunctionalUtils(); static void runAndLogError(Logger log, String errorMsg, UnsafeRunnable runnable); static Consumer<T> noOpConsumer(); static Runnable noOpRunnable(); static Consumer<I> safeConsumer(UnsafeConsumer<I> unsafeConsumer); static Function<T, R> safeFunction(UnsafeFunction<T, R> unsafeFunction); static Supplier<T> safeSupplier(UnsafeSupplier<T> unsafeSupplier); static Runnable safeRunnable(UnsafeRunnable unsafeRunnable); static Function<I, O> toFunction(Supplier<O> supplier); static T invokeSafely(UnsafeSupplier<T> unsafeSupplier); static void invokeSafely(UnsafeRunnable unsafeRunnable); }### Answer:
@Test public void canUseFunctionThatThrowsCheckedExceptionInLambda() { Optional<String> result = Stream.of(DONT_THROW_EXCEPTION).map(safeFunction(this::functionMethodWithChecked)).findFirst(); assertThat(result).isPresent().contains("Hello"); }
@Test @SuppressWarnings("ResultOfMethodCallIgnored") public void exceptionsForFunctionsAreConverted() { assertThatExceptionOfType(RuntimeException.class) .isThrownBy(() -> Stream.of(THROW_EXCEPTION).map(safeFunction(this::functionMethodWithChecked)).findFirst()) .withCauseExactlyInstanceOf(Exception.class); } |
### Question:
Pair { public static <LeftT, RightT> Pair<LeftT, RightT> of(LeftT left, RightT right) { return new Pair<>(left, right); } private Pair(LeftT left, RightT right); LeftT left(); RightT right(); ReturnT apply(BiFunction<LeftT, RightT, ReturnT> function); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static Pair<LeftT, RightT> of(LeftT left, RightT right); }### Answer:
@Test public void equalsMethodWorksAsExpected() { Pair foo = Pair.of("Foo", 50); assertThat(foo).isEqualTo(Pair.of("Foo", 50)); assertThat(foo).isNotEqualTo(Pair.of("Foo-bar", 50)); }
@Test public void canBeUseAsMapKey() { Map<Pair<String, Integer>, String> map = new HashMap<>(); map.put(Pair.of("Hello", 100), "World"); assertThat(map.get(Pair.of("Hello", 100))).isEqualTo("World"); } |
### Question:
Validate { public static void isTrue(final boolean expression, final String message, final Object... values) { if (!expression) { throw new IllegalArgumentException(String.format(message, values)); } } private Validate(); static void isTrue(final boolean expression, final String message, final Object... values); static T notNull(final T object, final String message, final Object... values); static void isNull(final T object, final String message, final Object... values); static T paramNotNull(final T object, final String paramName); static T paramNotBlank(final T chars, final String paramName); static T validState(final T object, final Predicate<T> test, final String message, final Object... values); static T[] notEmpty(final T[] array, final String message, final Object... values); static T notEmpty(final T collection, final String message, final Object... values); static T notEmpty(final T map, final String message, final Object... values); static T notEmpty(final T chars, final String message, final Object... values); static T notBlank(final T chars, final String message, final Object... values); static T[] noNullElements(final T[] array, final String message, final Object... values); static T noNullElements(final T iterable, final String message, final Object... values); static void validState(final boolean expression, final String message, final Object... values); static T inclusiveBetween(final U start, final U end, final T value,
final String message, final Object... values); static long inclusiveBetween(final long start, final long end, final long value, final String message); static double inclusiveBetween(final double start, final double end, final double value, final String message); static T exclusiveBetween(final U start, final U end, final T value,
final String message, final Object... values); static long exclusiveBetween(final long start, final long end, final long value, final String message); static double exclusiveBetween(final double start, final double end, final double value, final String message); static U isInstanceOf(final Class<U> type, final T obj, final String message, final Object... values); static Class<? extends T> isAssignableFrom(final Class<T> superType, final Class<?> type,
final String message, final Object... values); static int isPositive(int num, String fieldName); static long isPositive(long num, String fieldName); static int isNotNegative(int num, String fieldName); static Duration isPositive(Duration duration, String fieldName); static Duration isPositiveOrNull(Duration duration, String fieldName); static Integer isPositiveOrNull(Integer num, String fieldName); static Long isPositiveOrNull(Long num, String fieldName); static Duration isNotNegative(Duration duration, String fieldName); static T getOrDefault(T param, Supplier<T> defaultValue); static void mutuallyExclusive(String message, Object... objs); }### Answer:
@Test public void testIsTrue2() { Validate.isTrue(true, "MSG"); try { Validate.isTrue(false, "MSG"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } }
@Test public void testIsTrue3() { Validate.isTrue(true, "MSG", 6); try { Validate.isTrue(false, "MSG", 6); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } }
@Test public void testIsTrue4() { Validate.isTrue(true, "MSG", 7); try { Validate.isTrue(false, "MSG", 7); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } }
@Test public void testIsTrue5() { Validate.isTrue(true, "MSG", 7.4d); try { Validate.isTrue(false, "MSG", 7.4d); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } } |
### Question:
Validate { public static <T> T notNull(final T object, final String message, final Object... values) { if (object == null) { throw new NullPointerException(String.format(message, values)); } return object; } private Validate(); static void isTrue(final boolean expression, final String message, final Object... values); static T notNull(final T object, final String message, final Object... values); static void isNull(final T object, final String message, final Object... values); static T paramNotNull(final T object, final String paramName); static T paramNotBlank(final T chars, final String paramName); static T validState(final T object, final Predicate<T> test, final String message, final Object... values); static T[] notEmpty(final T[] array, final String message, final Object... values); static T notEmpty(final T collection, final String message, final Object... values); static T notEmpty(final T map, final String message, final Object... values); static T notEmpty(final T chars, final String message, final Object... values); static T notBlank(final T chars, final String message, final Object... values); static T[] noNullElements(final T[] array, final String message, final Object... values); static T noNullElements(final T iterable, final String message, final Object... values); static void validState(final boolean expression, final String message, final Object... values); static T inclusiveBetween(final U start, final U end, final T value,
final String message, final Object... values); static long inclusiveBetween(final long start, final long end, final long value, final String message); static double inclusiveBetween(final double start, final double end, final double value, final String message); static T exclusiveBetween(final U start, final U end, final T value,
final String message, final Object... values); static long exclusiveBetween(final long start, final long end, final long value, final String message); static double exclusiveBetween(final double start, final double end, final double value, final String message); static U isInstanceOf(final Class<U> type, final T obj, final String message, final Object... values); static Class<? extends T> isAssignableFrom(final Class<T> superType, final Class<?> type,
final String message, final Object... values); static int isPositive(int num, String fieldName); static long isPositive(long num, String fieldName); static int isNotNegative(int num, String fieldName); static Duration isPositive(Duration duration, String fieldName); static Duration isPositiveOrNull(Duration duration, String fieldName); static Integer isPositiveOrNull(Integer num, String fieldName); static Long isPositiveOrNull(Long num, String fieldName); static Duration isNotNegative(Duration duration, String fieldName); static T getOrDefault(T param, Supplier<T> defaultValue); static void mutuallyExclusive(String message, Object... objs); }### Answer:
@SuppressWarnings("unused") @Test public void testNotNull2() { Validate.notNull(new Object(), "MSG"); try { Validate.notNull(null, "MSG"); fail("Expecting NullPointerException"); } catch (final NullPointerException ex) { assertEquals("MSG", ex.getMessage()); } final String str = "Hi"; final String testStr = Validate.notNull(str, "Message"); assertSame(str, testStr); } |
### Question:
Validate { public static <T extends Comparable<U>, U> T inclusiveBetween(final U start, final U end, final T value, final String message, final Object... values) { if (value.compareTo(start) < 0 || value.compareTo(end) > 0) { throw new IllegalArgumentException(String.format(message, values)); } return value; } private Validate(); static void isTrue(final boolean expression, final String message, final Object... values); static T notNull(final T object, final String message, final Object... values); static void isNull(final T object, final String message, final Object... values); static T paramNotNull(final T object, final String paramName); static T paramNotBlank(final T chars, final String paramName); static T validState(final T object, final Predicate<T> test, final String message, final Object... values); static T[] notEmpty(final T[] array, final String message, final Object... values); static T notEmpty(final T collection, final String message, final Object... values); static T notEmpty(final T map, final String message, final Object... values); static T notEmpty(final T chars, final String message, final Object... values); static T notBlank(final T chars, final String message, final Object... values); static T[] noNullElements(final T[] array, final String message, final Object... values); static T noNullElements(final T iterable, final String message, final Object... values); static void validState(final boolean expression, final String message, final Object... values); static T inclusiveBetween(final U start, final U end, final T value,
final String message, final Object... values); static long inclusiveBetween(final long start, final long end, final long value, final String message); static double inclusiveBetween(final double start, final double end, final double value, final String message); static T exclusiveBetween(final U start, final U end, final T value,
final String message, final Object... values); static long exclusiveBetween(final long start, final long end, final long value, final String message); static double exclusiveBetween(final double start, final double end, final double value, final String message); static U isInstanceOf(final Class<U> type, final T obj, final String message, final Object... values); static Class<? extends T> isAssignableFrom(final Class<T> superType, final Class<?> type,
final String message, final Object... values); static int isPositive(int num, String fieldName); static long isPositive(long num, String fieldName); static int isNotNegative(int num, String fieldName); static Duration isPositive(Duration duration, String fieldName); static Duration isPositiveOrNull(Duration duration, String fieldName); static Integer isPositiveOrNull(Integer num, String fieldName); static Long isPositiveOrNull(Long num, String fieldName); static Duration isNotNegative(Duration duration, String fieldName); static T getOrDefault(T param, Supplier<T> defaultValue); static void mutuallyExclusive(String message, Object... objs); }### Answer:
@Test public void testInclusiveBetween_withMessage() { Validate.inclusiveBetween("a", "c", "b", "Error"); try { Validate.inclusiveBetween("0", "5", "6", "Error"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException e) { assertEquals("Error", e.getMessage()); } }
@Test public void testInclusiveBetweenLong_withMessage() { Validate.inclusiveBetween(0, 2, 1, "Error"); Validate.inclusiveBetween(0, 2, 2, "Error"); try { Validate.inclusiveBetween(0, 5, 6, "Error"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException e) { assertEquals("Error", e.getMessage()); } }
@Test public void testInclusiveBetweenDouble_withMessage() { Validate.inclusiveBetween(0.1, 2.1, 1.1, "Error"); Validate.inclusiveBetween(0.1, 2.1, 2.1, "Error"); try { Validate.inclusiveBetween(0.1, 5.1, 6.1, "Error"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException e) { assertEquals("Error", e.getMessage()); } } |
### Question:
SyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<InputStream> modifyHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse()) && context.responseBody().isPresent()) { SdkChecksum checksum = new Md5Checksum(); long contentLength = context.httpResponse() .firstMatchingHeader(CONTENT_LENGTH_HEADER) .map(Long::parseLong) .orElse(0L); if (contentLength > 0) { return Optional.of(new ChecksumValidatingInputStream(context.responseBody().get(), checksum, contentLength)); } } return context.responseBody(); } @Override Optional<RequestBody> modifyHttpContent(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override Optional<InputStream> modifyHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); }### Answer:
@Test public void modifyHttpResponseContent_getObjectRequest_checksumEnabled_shouldWrapChecksumValidatingPublisher() { SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader(); Context.ModifyHttpResponse modifyHttpResponse = InterceptorTestUtils.modifyHttpResponse(GetObjectRequest.builder().build(), sdkHttpResponse); Optional<InputStream> publisher = interceptor.modifyHttpResponseContent(modifyHttpResponse, getExecutionAttributes()); assertThat(publisher.get()).isExactlyInstanceOf(ChecksumValidatingInputStream.class); }
@Test public void modifyHttpResponseContent_getObjectRequest_responseDoesNotContainChecksum_shouldNotModify() { ExecutionAttributes executionAttributes = getExecutionAttributesWithChecksumDisabled(); SdkHttpResponse sdkHttpResponse = SdkHttpResponse.builder() .putHeader(CONTENT_LENGTH_HEADER, "100") .build(); Context.ModifyHttpResponse modifyHttpResponse = InterceptorTestUtils.modifyHttpResponse(GetObjectRequest.builder().build(), sdkHttpResponse); Optional<InputStream> publisher = interceptor.modifyHttpResponseContent(modifyHttpResponse, executionAttributes); assertThat(publisher).isEqualTo(modifyHttpResponse.responseBody()); }
@Test public void modifyHttpResponseContent_nonGetObjectRequest_shouldNotModify() { ExecutionAttributes executionAttributes = getExecutionAttributes(); SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader(); sdkHttpResponse.toBuilder().clearHeaders(); Context.ModifyHttpResponse modifyHttpResponse = InterceptorTestUtils.modifyHttpResponse(PutObjectRequest.builder().build(), sdkHttpResponse); Optional<InputStream> publisher = interceptor.modifyHttpResponseContent(modifyHttpResponse, executionAttributes); assertThat(publisher).isEqualTo(modifyHttpResponse.responseBody()); } |
### Question:
Validate { public static <T> Class<? extends T> isAssignableFrom(final Class<T> superType, final Class<?> type, final String message, final Object... values) { if (!superType.isAssignableFrom(type)) { throw new IllegalArgumentException(String.format(message, values)); } return (Class<? extends T>) type; } private Validate(); static void isTrue(final boolean expression, final String message, final Object... values); static T notNull(final T object, final String message, final Object... values); static void isNull(final T object, final String message, final Object... values); static T paramNotNull(final T object, final String paramName); static T paramNotBlank(final T chars, final String paramName); static T validState(final T object, final Predicate<T> test, final String message, final Object... values); static T[] notEmpty(final T[] array, final String message, final Object... values); static T notEmpty(final T collection, final String message, final Object... values); static T notEmpty(final T map, final String message, final Object... values); static T notEmpty(final T chars, final String message, final Object... values); static T notBlank(final T chars, final String message, final Object... values); static T[] noNullElements(final T[] array, final String message, final Object... values); static T noNullElements(final T iterable, final String message, final Object... values); static void validState(final boolean expression, final String message, final Object... values); static T inclusiveBetween(final U start, final U end, final T value,
final String message, final Object... values); static long inclusiveBetween(final long start, final long end, final long value, final String message); static double inclusiveBetween(final double start, final double end, final double value, final String message); static T exclusiveBetween(final U start, final U end, final T value,
final String message, final Object... values); static long exclusiveBetween(final long start, final long end, final long value, final String message); static double exclusiveBetween(final double start, final double end, final double value, final String message); static U isInstanceOf(final Class<U> type, final T obj, final String message, final Object... values); static Class<? extends T> isAssignableFrom(final Class<T> superType, final Class<?> type,
final String message, final Object... values); static int isPositive(int num, String fieldName); static long isPositive(long num, String fieldName); static int isNotNegative(int num, String fieldName); static Duration isPositive(Duration duration, String fieldName); static Duration isPositiveOrNull(Duration duration, String fieldName); static Integer isPositiveOrNull(Integer num, String fieldName); static Long isPositiveOrNull(Long num, String fieldName); static Duration isNotNegative(Duration duration, String fieldName); static T getOrDefault(T param, Supplier<T> defaultValue); static void mutuallyExclusive(String message, Object... objs); }### Answer:
@Test public void testIsAssignable_withMessage() { Validate.isAssignableFrom(CharSequence.class, String.class, "Error"); Validate.isAssignableFrom(AbstractList.class, ArrayList.class, "Error"); try { Validate.isAssignableFrom(List.class, String.class, "Error"); fail("Expecting IllegalArgumentException"); } catch(final IllegalArgumentException e) { assertEquals("Error", e.getMessage()); } } |
### Question:
Validate { public static <T> T paramNotNull(final T object, final String paramName) { if (object == null) { throw new NullPointerException(String.format("%s must not be null.", paramName)); } return object; } private Validate(); static void isTrue(final boolean expression, final String message, final Object... values); static T notNull(final T object, final String message, final Object... values); static void isNull(final T object, final String message, final Object... values); static T paramNotNull(final T object, final String paramName); static T paramNotBlank(final T chars, final String paramName); static T validState(final T object, final Predicate<T> test, final String message, final Object... values); static T[] notEmpty(final T[] array, final String message, final Object... values); static T notEmpty(final T collection, final String message, final Object... values); static T notEmpty(final T map, final String message, final Object... values); static T notEmpty(final T chars, final String message, final Object... values); static T notBlank(final T chars, final String message, final Object... values); static T[] noNullElements(final T[] array, final String message, final Object... values); static T noNullElements(final T iterable, final String message, final Object... values); static void validState(final boolean expression, final String message, final Object... values); static T inclusiveBetween(final U start, final U end, final T value,
final String message, final Object... values); static long inclusiveBetween(final long start, final long end, final long value, final String message); static double inclusiveBetween(final double start, final double end, final double value, final String message); static T exclusiveBetween(final U start, final U end, final T value,
final String message, final Object... values); static long exclusiveBetween(final long start, final long end, final long value, final String message); static double exclusiveBetween(final double start, final double end, final double value, final String message); static U isInstanceOf(final Class<U> type, final T obj, final String message, final Object... values); static Class<? extends T> isAssignableFrom(final Class<T> superType, final Class<?> type,
final String message, final Object... values); static int isPositive(int num, String fieldName); static long isPositive(long num, String fieldName); static int isNotNegative(int num, String fieldName); static Duration isPositive(Duration duration, String fieldName); static Duration isPositiveOrNull(Duration duration, String fieldName); static Integer isPositiveOrNull(Integer num, String fieldName); static Long isPositiveOrNull(Long num, String fieldName); static Duration isNotNegative(Duration duration, String fieldName); static T getOrDefault(T param, Supplier<T> defaultValue); static void mutuallyExclusive(String message, Object... objs); }### Answer:
@Test public void paramNotNull_NullParam_ThrowsException() { try { Validate.paramNotNull(null, "someField"); } catch (NullPointerException e) { assertEquals(e.getMessage(), "someField must not be null."); } }
@Test public void paramNotNull_NonNullParam_ReturnsObject() { assertEquals("foo", Validate.paramNotNull("foo", "someField")); } |
### Question:
Validate { public static <T> T getOrDefault(T param, Supplier<T> defaultValue) { paramNotNull(defaultValue, "defaultValue"); return param != null ? param : defaultValue.get(); } private Validate(); static void isTrue(final boolean expression, final String message, final Object... values); static T notNull(final T object, final String message, final Object... values); static void isNull(final T object, final String message, final Object... values); static T paramNotNull(final T object, final String paramName); static T paramNotBlank(final T chars, final String paramName); static T validState(final T object, final Predicate<T> test, final String message, final Object... values); static T[] notEmpty(final T[] array, final String message, final Object... values); static T notEmpty(final T collection, final String message, final Object... values); static T notEmpty(final T map, final String message, final Object... values); static T notEmpty(final T chars, final String message, final Object... values); static T notBlank(final T chars, final String message, final Object... values); static T[] noNullElements(final T[] array, final String message, final Object... values); static T noNullElements(final T iterable, final String message, final Object... values); static void validState(final boolean expression, final String message, final Object... values); static T inclusiveBetween(final U start, final U end, final T value,
final String message, final Object... values); static long inclusiveBetween(final long start, final long end, final long value, final String message); static double inclusiveBetween(final double start, final double end, final double value, final String message); static T exclusiveBetween(final U start, final U end, final T value,
final String message, final Object... values); static long exclusiveBetween(final long start, final long end, final long value, final String message); static double exclusiveBetween(final double start, final double end, final double value, final String message); static U isInstanceOf(final Class<U> type, final T obj, final String message, final Object... values); static Class<? extends T> isAssignableFrom(final Class<T> superType, final Class<?> type,
final String message, final Object... values); static int isPositive(int num, String fieldName); static long isPositive(long num, String fieldName); static int isNotNegative(int num, String fieldName); static Duration isPositive(Duration duration, String fieldName); static Duration isPositiveOrNull(Duration duration, String fieldName); static Integer isPositiveOrNull(Integer num, String fieldName); static Long isPositiveOrNull(Long num, String fieldName); static Duration isNotNegative(Duration duration, String fieldName); static T getOrDefault(T param, Supplier<T> defaultValue); static void mutuallyExclusive(String message, Object... objs); }### Answer:
@Test public void getOrDefault_ParamNotNull_ReturnsParam() { assertEquals("foo", Validate.getOrDefault("foo", () -> "bar")); }
@Test public void getOrDefault_ParamNull_ReturnsDefaultValue() { assertEquals("bar", Validate.getOrDefault(null, () -> "bar")); }
@Test(expected = NullPointerException.class) public void getOrDefault_DefaultValueNull_ThrowsException() { Validate.getOrDefault("bar", null); } |
### Question:
Validate { public static void mutuallyExclusive(String message, Object... objs) { boolean oneProvided = false; for (Object o : objs) { if (o != null) { if (oneProvided) { throw new IllegalArgumentException(message); } else { oneProvided = true; } } } } private Validate(); static void isTrue(final boolean expression, final String message, final Object... values); static T notNull(final T object, final String message, final Object... values); static void isNull(final T object, final String message, final Object... values); static T paramNotNull(final T object, final String paramName); static T paramNotBlank(final T chars, final String paramName); static T validState(final T object, final Predicate<T> test, final String message, final Object... values); static T[] notEmpty(final T[] array, final String message, final Object... values); static T notEmpty(final T collection, final String message, final Object... values); static T notEmpty(final T map, final String message, final Object... values); static T notEmpty(final T chars, final String message, final Object... values); static T notBlank(final T chars, final String message, final Object... values); static T[] noNullElements(final T[] array, final String message, final Object... values); static T noNullElements(final T iterable, final String message, final Object... values); static void validState(final boolean expression, final String message, final Object... values); static T inclusiveBetween(final U start, final U end, final T value,
final String message, final Object... values); static long inclusiveBetween(final long start, final long end, final long value, final String message); static double inclusiveBetween(final double start, final double end, final double value, final String message); static T exclusiveBetween(final U start, final U end, final T value,
final String message, final Object... values); static long exclusiveBetween(final long start, final long end, final long value, final String message); static double exclusiveBetween(final double start, final double end, final double value, final String message); static U isInstanceOf(final Class<U> type, final T obj, final String message, final Object... values); static Class<? extends T> isAssignableFrom(final Class<T> superType, final Class<?> type,
final String message, final Object... values); static int isPositive(int num, String fieldName); static long isPositive(long num, String fieldName); static int isNotNegative(int num, String fieldName); static Duration isPositive(Duration duration, String fieldName); static Duration isPositiveOrNull(Duration duration, String fieldName); static Integer isPositiveOrNull(Integer num, String fieldName); static Long isPositiveOrNull(Long num, String fieldName); static Duration isNotNegative(Duration duration, String fieldName); static T getOrDefault(T param, Supplier<T> defaultValue); static void mutuallyExclusive(String message, Object... objs); }### Answer:
@Test public void mutuallyExclusive_AllNull_DoesNotThrow() { Validate.mutuallyExclusive("error", null, null, null); }
@Test public void mutuallyExclusive_OnlyOneProvided_DoesNotThrow() { Validate.mutuallyExclusive("error", null, "foo", null); }
@Test(expected = IllegalArgumentException.class) public void mutuallyExclusive_MultipleProvided_DoesNotThrow() { Validate.mutuallyExclusive("error", null, "foo", "bar"); } |
### Question:
Validate { public static <T> void isNull(final T object, final String message, final Object... values) { if (object != null) { throw new IllegalArgumentException(String.format(message, values)); } } private Validate(); static void isTrue(final boolean expression, final String message, final Object... values); static T notNull(final T object, final String message, final Object... values); static void isNull(final T object, final String message, final Object... values); static T paramNotNull(final T object, final String paramName); static T paramNotBlank(final T chars, final String paramName); static T validState(final T object, final Predicate<T> test, final String message, final Object... values); static T[] notEmpty(final T[] array, final String message, final Object... values); static T notEmpty(final T collection, final String message, final Object... values); static T notEmpty(final T map, final String message, final Object... values); static T notEmpty(final T chars, final String message, final Object... values); static T notBlank(final T chars, final String message, final Object... values); static T[] noNullElements(final T[] array, final String message, final Object... values); static T noNullElements(final T iterable, final String message, final Object... values); static void validState(final boolean expression, final String message, final Object... values); static T inclusiveBetween(final U start, final U end, final T value,
final String message, final Object... values); static long inclusiveBetween(final long start, final long end, final long value, final String message); static double inclusiveBetween(final double start, final double end, final double value, final String message); static T exclusiveBetween(final U start, final U end, final T value,
final String message, final Object... values); static long exclusiveBetween(final long start, final long end, final long value, final String message); static double exclusiveBetween(final double start, final double end, final double value, final String message); static U isInstanceOf(final Class<U> type, final T obj, final String message, final Object... values); static Class<? extends T> isAssignableFrom(final Class<T> superType, final Class<?> type,
final String message, final Object... values); static int isPositive(int num, String fieldName); static long isPositive(long num, String fieldName); static int isNotNegative(int num, String fieldName); static Duration isPositive(Duration duration, String fieldName); static Duration isPositiveOrNull(Duration duration, String fieldName); static Integer isPositiveOrNull(Integer num, String fieldName); static Long isPositiveOrNull(Long num, String fieldName); static Duration isNotNegative(Duration duration, String fieldName); static T getOrDefault(T param, Supplier<T> defaultValue); static void mutuallyExclusive(String message, Object... objs); }### Answer:
@Test public void isNull_notNull_shouldThrow() { expected.expect(IllegalArgumentException.class); expected.expectMessage("not null"); Validate.isNull("string", "not null"); }
@Test public void isNull_null_shouldPass() { Validate.isNull(null, "not null"); } |
### Question:
ReflectionMethodInvoker { public R invoke(T obj, Object... args) throws NoSuchMethodException { Method targetMethod = getTargetMethod(); try { Object rawResult = targetMethod.invoke(obj, args); return returnType.cast(rawResult); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(createInvocationErrorMessage(), e); } } ReflectionMethodInvoker(Class<T> clazz,
Class<R> returnType,
String methodName,
Class<?>... parameterTypes); R invoke(T obj, Object... args); void initialize(); boolean isInitialized(); }### Answer:
@Test public void invokeCanInvokeMethodAndReturnsCorrectResult() throws Exception { ReflectionMethodInvoker<String, Integer> invoker = new ReflectionMethodInvoker<>(String.class, Integer.class, "indexOf", String.class, int.class); assertThat(invoker.invoke("ababab", "ab", 1), is(2)); }
@Test public void invokeCanReturnVoid() throws Exception { ReflectionMethodInvoker<InvokeTestClass, Void> invoker = new ReflectionMethodInvoker<>(InvokeTestClass.class, Void.class, "happyVoid"); invoker.invoke(invokeTestInstance); }
@Test public void invokeThrowsNoSuchMethodExceptionWhenMethodSignatureNotFound() throws Exception { ReflectionMethodInvoker<String, Integer> invoker = new ReflectionMethodInvoker<>(String.class, Integer.class, "foo", String.class, int.class); exception.expect(NoSuchMethodException.class); invoker.invoke("ababab", "ab", 1); }
@Test public void invoke_callThrowsNullPointerException_throwsAsRuntimeException() throws Exception { ReflectionMethodInvoker<String, Integer> invoker = new ReflectionMethodInvoker<>(String.class, Integer.class, null, String.class, int.class); exception.expect(RuntimeException.class); exception.expectCause(Matchers.<NullPointerException>instanceOf(NullPointerException.class)); exception.expectMessage("String"); invoker.invoke("ababab", "ab", 1); }
@Test public void invoke_invokedMethodThrowsException_throwsAsRuntimeException() throws Exception { ReflectionMethodInvoker<InvokeTestClass, Void> invoker = new ReflectionMethodInvoker<>(InvokeTestClass.class, Void.class, "throwsException"); exception.expect(RuntimeException.class); exception.expectMessage("InvokeTestClass"); exception.expectMessage("throwsException"); exception.expectCause(Matchers.<InvocationTargetException>instanceOf(InvocationTargetException.class)); invoker.invoke(invokeTestInstance); }
@Test public void invoke_invokePrivateMethod_throwsNoSuchMethodException() throws Exception { ReflectionMethodInvoker<InvokeTestClass, Void> invoker = new ReflectionMethodInvoker<>(InvokeTestClass.class, Void.class, "illegalAccessException"); exception.expect(NoSuchMethodException.class); invoker.invoke(invokeTestInstance); }
@Test public void invoke_canBeCalledMultipleTimes() throws Exception { ReflectionMethodInvoker<String, Integer> invoker = new ReflectionMethodInvoker<>(String.class, Integer.class, "indexOf", String.class, int.class); assertThat(invoker.invoke("ababab", "ab", 1), is(2)); assertThat(invoker.invoke("ababab", "ab", 1), is(2)); } |
### Question:
Either { public static <L, R> Either<L, R> left(L value) { return new Either<>(Optional.of(value), Optional.empty()); } private Either(Optional<L> l, Optional<R> r); T map(
Function<? super L, ? extends T> lFunc,
Function<? super R, ? extends T> rFunc); Either<T, R> mapLeft(Function<? super L, ? extends T> lFunc); Either<L, T> mapRight(Function<? super R, ? extends T> rFunc); void apply(Consumer<? super L> lFunc, Consumer<? super R> rFunc); static Either<L, R> left(L value); static Either<L, R> right(R value); Optional<L> left(); Optional<R> right(); static Optional<Either<L, R>> fromNullable(L left, R right); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test(expected = NullPointerException.class) public void leftValueNull_ThrowsException() { Either.left(null); } |
### Question:
SyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) { boolean recordingChecksum = Boolean.TRUE.equals(executionAttributes.getAttribute(SYNC_RECORDING_CHECKSUM)); boolean responseChecksumIsValid = responseChecksumIsValid(context.httpResponse()); if (recordingChecksum && responseChecksumIsValid) { validatePutObjectChecksum((PutObjectResponse) context.response(), executionAttributes); } } @Override Optional<RequestBody> modifyHttpContent(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override Optional<InputStream> modifyHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); }### Answer:
@Test public void afterUnmarshalling_putObjectRequest_shouldValidateChecksum() { SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader(); PutObjectResponse response = PutObjectResponse.builder() .eTag(VALID_CHECKSUM) .build(); PutObjectRequest putObjectRequest = PutObjectRequest.builder() .build(); SdkHttpRequest sdkHttpRequest = SdkHttpFullRequest.builder() .uri(URI.create("http: .method(SdkHttpMethod.PUT) .build(); Context.AfterUnmarshalling afterUnmarshallingContext = InterceptorTestUtils.afterUnmarshallingContext(putObjectRequest, sdkHttpRequest, response, sdkHttpResponse); interceptor.afterUnmarshalling(afterUnmarshallingContext, getExecutionAttributesWithChecksum()); }
@Test public void afterUnmarshalling_putObjectRequest_with_SSE_shouldNotValidateChecksum() { SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader(); PutObjectResponse response = PutObjectResponse.builder() .eTag(INVALID_CHECKSUM) .build(); PutObjectRequest putObjectRequest = PutObjectRequest.builder().build(); SdkHttpRequest sdkHttpRequest = SdkHttpFullRequest.builder() .putHeader(SERVER_SIDE_ENCRYPTION_HEADER, AWS_KMS.toString()) .putHeader("x-amz-server-side-encryption-aws-kms-key-id", ENABLE_MD5_CHECKSUM_HEADER_VALUE) .uri(URI.create("http: .method(SdkHttpMethod.PUT) .build(); Context.AfterUnmarshalling afterUnmarshallingContext = InterceptorTestUtils.afterUnmarshallingContext(putObjectRequest, sdkHttpRequest, response, sdkHttpResponse); interceptor.afterUnmarshalling(afterUnmarshallingContext, getExecutionAttributesWithChecksum()); } |
### Question:
GetObjectPresignRequest extends PresignRequest implements ToCopyableBuilder<GetObjectPresignRequest.Builder, GetObjectPresignRequest> { @Override public Builder toBuilder() { return new DefaultBuilder(this); } private GetObjectPresignRequest(DefaultBuilder builder); static Builder builder(); GetObjectRequest getObjectRequest(); @Override Builder toBuilder(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void toBuilder() { GetObjectPresignRequest getObjectPresignRequest = GetObjectPresignRequest.builder() .getObjectRequest(GET_OBJECT_REQUEST) .signatureDuration(Duration.ofSeconds(123L)) .build(); GetObjectPresignRequest otherGetObjectPresignRequest = getObjectPresignRequest.toBuilder().build(); assertThat(otherGetObjectPresignRequest.getObjectRequest()).isEqualTo(GET_OBJECT_REQUEST); assertThat(otherGetObjectPresignRequest.signatureDuration()).isEqualTo(Duration.ofSeconds(123L)); } |
### Question:
Either { public static <L, R> Either<L, R> right(R value) { return new Either<>(Optional.empty(), Optional.of(value)); } private Either(Optional<L> l, Optional<R> r); T map(
Function<? super L, ? extends T> lFunc,
Function<? super R, ? extends T> rFunc); Either<T, R> mapLeft(Function<? super L, ? extends T> lFunc); Either<L, T> mapRight(Function<? super R, ? extends T> rFunc); void apply(Consumer<? super L> lFunc, Consumer<? super R> rFunc); static Either<L, R> left(L value); static Either<L, R> right(R value); Optional<L> left(); Optional<R> right(); static Optional<Either<L, R>> fromNullable(L left, R right); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test(expected = NullPointerException.class) public void rightValueNull_ThrowsException() { Either.right(null); } |
### Question:
Either { public static <L, R> Optional<Either<L, R>> fromNullable(L left, R right) { if (left != null && right == null) { return Optional.of(left(left)); } if (left == null && right != null) { return Optional.of(right(right)); } if (left == null && right == null) { return Optional.empty(); } throw new IllegalArgumentException(String.format("Only one of either left or right should be non-null. " + "Got (left: %s, right: %s)", left, right)); } private Either(Optional<L> l, Optional<R> r); T map(
Function<? super L, ? extends T> lFunc,
Function<? super R, ? extends T> rFunc); Either<T, R> mapLeft(Function<? super L, ? extends T> lFunc); Either<L, T> mapRight(Function<? super R, ? extends T> rFunc); void apply(Consumer<? super L> lFunc, Consumer<? super R> rFunc); static Either<L, R> left(L value); static Either<L, R> right(R value); Optional<L> left(); Optional<R> right(); static Optional<Either<L, R>> fromNullable(L left, R right); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void fromNullable() { assertThat(Either.fromNullable("left", null)).contains(Either.left("left")); assertThat(Either.fromNullable(null, "right")).contains(Either.right("right")); assertThat(Either.fromNullable(null, null)).isEmpty(); assertThatThrownBy(() -> Either.fromNullable("left", "right")).isInstanceOf(IllegalArgumentException.class); } |
### Question:
CompletableFutureUtils { public static <T> CompletableFuture<T> forwardExceptionTo(CompletableFuture<T> src, CompletableFuture<?> dst) { src.whenComplete((r, e) -> { if (e != null) { dst.completeExceptionally(e); } }); return src; } private CompletableFutureUtils(); static CompletableFuture<U> failedFuture(Throwable t); static CompletionException errorAsCompletionException(Throwable t); static CompletableFuture<T> forwardExceptionTo(CompletableFuture<T> src, CompletableFuture<?> dst); }### Answer:
@Test(timeout = 1000) public void testForwardException() { CompletableFuture src = new CompletableFuture(); CompletableFuture dst = new CompletableFuture(); Exception e = new RuntimeException("BOOM"); CompletableFutureUtils.forwardExceptionTo(src, dst); src.completeExceptionally(e); try { dst.join(); fail(); } catch (Throwable t) { assertThat(t.getCause()).isEqualTo(e); } } |
### Question:
BufferingSubscriber extends DelegatingSubscriber<T, List<T>> { @Override public void onNext(T t) { currentBuffer.add(t); if (currentBuffer.size() == bufferSize) { subscriber.onNext(currentBuffer); currentBuffer.clear(); } else { subscription.request(1); } } BufferingSubscriber(Subscriber<? super List<T>> subscriber, int bufferSize); @Override void onSubscribe(Subscription subscription); @Override void onNext(T t); @Override void onComplete(); }### Answer:
@Test public void onNextNotCalled_WhenCurrentSizeLessThanBufferSize() { int count = 3; callOnNext(count); verify(mockSubscription, times(count)).request(1); verify(mockSubscriber, times(0)).onNext(any()); }
@Test public void onNextIsCalled_onlyWhen_BufferSizeRequirementIsMet() { callOnNext(BUFFER_SIZE); verify(mockSubscriber, times(1)).onNext(any()); } |
### Question:
ReflectionUtils { public static Class<?> getWrappedClass(Class<?> clazz) { if (!clazz.isPrimitive()) { return clazz; } return PRIMITIVES_TO_WRAPPERS.getOrDefault(clazz, clazz); } private ReflectionUtils(); static Class<?> getWrappedClass(Class<?> clazz); }### Answer:
@Test public void getWrappedClass_primitiveClass_returnsWrappedClass() { assertThat(ReflectionUtils.getWrappedClass(int.class), is(equalTo(Integer.class))); }
@Test public void getWrappedClass_nonPrimitiveClass_returnsSameClass() { assertThat(ReflectionUtils.getWrappedClass(String.class), is(equalTo(String.class))); } |
### Question:
DateUtils { public static String formatIso8601Date(Instant date) { return ISO_INSTANT.format(date); } private DateUtils(); static Instant parseIso8601Date(String dateString); static String formatIso8601Date(Instant date); static Instant parseRfc1123Date(String dateString); static String formatRfc1123Date(Instant instant); static long numberOfDaysSinceEpoch(long milliSinceEpoch); static Instant parseUnixTimestampInstant(String dateString); static Instant parseUnixTimestampMillisInstant(String dateString); static String formatUnixTimestampInstant(Instant instant); }### Answer:
@Test public void formatIso8601Date() throws ParseException { Date date = Date.from(INSTANT); String expected = COMMON_DATE_FORMAT.format(date); String actual = DateUtils.formatIso8601Date(date.toInstant()); assertEquals(expected, actual); Instant expectedDate = COMMON_DATE_FORMAT.parse(expected).toInstant(); Instant actualDate = DateUtils.parseIso8601Date(actual); assertEquals(expectedDate, actualDate); } |
### Question:
DateUtils { public static String formatRfc1123Date(Instant instant) { return RFC_1123_DATE_TIME.format(ZonedDateTime.ofInstant(instant, UTC)); } private DateUtils(); static Instant parseIso8601Date(String dateString); static String formatIso8601Date(Instant date); static Instant parseRfc1123Date(String dateString); static String formatRfc1123Date(Instant instant); static long numberOfDaysSinceEpoch(long milliSinceEpoch); static Instant parseUnixTimestampInstant(String dateString); static Instant parseUnixTimestampMillisInstant(String dateString); static String formatUnixTimestampInstant(Instant instant); }### Answer:
@Test public void formatRfc1123Date() throws ParseException { String string = DateUtils.formatRfc1123Date(INSTANT); Instant parsedDateAsInstant = LONG_DATE_FORMAT.parse(string).toInstant(); assertEquals(INSTANT, parsedDateAsInstant); String formattedDate = LONG_DATE_FORMAT.format(Date.from(INSTANT)); Instant parsedInstant = DateUtils.parseRfc1123Date(formattedDate); assertEquals(INSTANT, parsedInstant); } |
### Question:
DateUtils { public static Instant parseRfc1123Date(String dateString) { if (dateString == null) { return null; } return parseInstant(dateString, RFC_1123_DATE_TIME); } private DateUtils(); static Instant parseIso8601Date(String dateString); static String formatIso8601Date(Instant date); static Instant parseRfc1123Date(String dateString); static String formatRfc1123Date(Instant instant); static long numberOfDaysSinceEpoch(long milliSinceEpoch); static Instant parseUnixTimestampInstant(String dateString); static Instant parseUnixTimestampMillisInstant(String dateString); static String formatUnixTimestampInstant(Instant instant); }### Answer:
@Test public void parseRfc822Date() throws ParseException { String formatted = LONG_DATE_FORMAT.format(Date.from(INSTANT)); Instant expected = LONG_DATE_FORMAT.parse(formatted).toInstant(); Instant actual = DateUtils.parseRfc1123Date(formatted); assertEquals(expected, actual); } |
### Question:
DateUtils { public static Instant parseIso8601Date(String dateString) { if (dateString.endsWith("+0000")) { dateString = dateString .substring(0, dateString.length() - 5) .concat("Z"); } try { return parseInstant(dateString, ISO_INSTANT); } catch (DateTimeParseException e) { return parseInstant(dateString, ALTERNATE_ISO_8601_DATE_FORMAT); } } private DateUtils(); static Instant parseIso8601Date(String dateString); static String formatIso8601Date(Instant date); static Instant parseRfc1123Date(String dateString); static String formatRfc1123Date(Instant instant); static long numberOfDaysSinceEpoch(long milliSinceEpoch); static Instant parseUnixTimestampInstant(String dateString); static Instant parseUnixTimestampMillisInstant(String dateString); static String formatUnixTimestampInstant(Instant instant); }### Answer:
@Test public void parseIso8601Date() throws ParseException { checkParsing(DateTimeFormatter.ISO_INSTANT, COMMON_DATE_FORMAT); }
@Test(expected = DateTimeParseException.class) public void invalidDate() { final String input = "2014-03-06T14:28:58.000Z.000Z"; DateUtils.parseIso8601Date(input); }
@Test public void testIssue233JavaTimeLimit() { String s = ALTERNATE_ISO_8601_DATE_FORMAT.format( ZonedDateTime.ofInstant(Instant.ofEpochMilli(Long.MAX_VALUE), UTC)); System.out.println("s: " + s); Instant parsed = DateUtils.parseIso8601Date(s); assertEquals(ZonedDateTime.ofInstant(parsed, UTC).getYear(), MAX_MILLIS_YEAR); } |
### Question:
DateUtils { public static long numberOfDaysSinceEpoch(long milliSinceEpoch) { return Duration.ofMillis(milliSinceEpoch).toDays(); } private DateUtils(); static Instant parseIso8601Date(String dateString); static String formatIso8601Date(Instant date); static Instant parseRfc1123Date(String dateString); static String formatRfc1123Date(Instant instant); static long numberOfDaysSinceEpoch(long milliSinceEpoch); static Instant parseUnixTimestampInstant(String dateString); static Instant parseUnixTimestampMillisInstant(String dateString); static String formatUnixTimestampInstant(Instant instant); }### Answer:
@Test public void numberOfDaysSinceEpoch() { final long now = System.currentTimeMillis(); final long days = DateUtils.numberOfDaysSinceEpoch(now); final long oneDayMilli = Duration.ofDays(1).toMillis(); assertTrue(now >= Duration.ofDays(days).toMillis()); assertTrue((now - Duration.ofDays(days).toMillis()) <= oneDayMilli); } |
### Question:
HostnameValidator { public static void validateHostnameCompliant(String hostnameComponent, String paramName, String object) { if (StringUtils.isEmpty(hostnameComponent)) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the required '%s' " + "component is missing.", object, paramName)); } if (hostnameComponent.length() > HOSTNAME_MAX_LENGTH) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component exceeds the maximum length of %d characters.", object, paramName, HOSTNAME_MAX_LENGTH)); } Matcher m = HOSTNAME_COMPLIANT_PATTERN.matcher(hostnameComponent); if (!m.matches()) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component must only contain alphanumeric characters and dashes.", object, paramName)); } } private HostnameValidator(); static void validateHostnameCompliant(String hostnameComponent, String paramName, String object); }### Answer:
@Test public void validHostComponent_shouldWork() { HostnameValidator.validateHostnameCompliant("1", "id", "test"); HostnameValidator.validateHostnameCompliant(LONG_STRING_64.substring(0, LONG_STRING_64.length() - 1), "id", "test"); }
@Test public void nullHostComponent_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("id"); exception.expectMessage("missing"); HostnameValidator.validateHostnameCompliant(null, "id", "test"); }
@Test public void emptyHostComponent_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("id"); exception.expectMessage("missing"); HostnameValidator.validateHostnameCompliant("", "id", "test"); }
@Test public void hostComponentWithSlash_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("id"); exception.expectMessage("alphanumeric"); HostnameValidator.validateHostnameCompliant("foo%2bar", "id", "test"); }
@Test public void hostComponentWithEncodedString_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("id"); exception.expectMessage("63"); HostnameValidator.validateHostnameCompliant(LONG_STRING_64, "id", "test"); }
@Test public void hostComponentTooLong_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("id"); exception.expectMessage("63"); HostnameValidator.validateHostnameCompliant(LONG_STRING_64, "id", "test"); } |
### Question:
AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { boolean shouldRecordChecksum = shouldRecordChecksum(context.request(), ASYNC, executionAttributes, context.httpRequest()); if (shouldRecordChecksum && context.asyncRequestBody().isPresent()) { SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(ASYNC_RECORDING_CHECKSUM, true); executionAttributes.putAttribute(CHECKSUM, checksum); return Optional.of(new ChecksumCalculatingAsyncRequestBody(context.asyncRequestBody().get(), checksum)); } return context.asyncRequestBody(); } @Override Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); }### Answer:
@Test public void modifyAsyncHttpContent_putObjectRequestChecksumEnabled_shouldWrapChecksumRequestBody() { ExecutionAttributes executionAttributes = getExecutionAttributes(); Context.ModifyHttpRequest modifyHttpRequest = InterceptorTestUtils.modifyHttpRequestContext(PutObjectRequest.builder().build()); Optional<AsyncRequestBody> asyncRequestBody = interceptor.modifyAsyncHttpContent(modifyHttpRequest, executionAttributes); assertThat(asyncRequestBody.isPresent()).isTrue(); assertThat(executionAttributes.getAttribute(CHECKSUM)).isNotNull(); assertThat(asyncRequestBody.get()).isExactlyInstanceOf(ChecksumCalculatingAsyncRequestBody.class); }
@Test public void modifyAsyncHttpContent_nonPutObjectRequest_shouldNotModify() { ExecutionAttributes executionAttributes = getExecutionAttributes(); Context.ModifyHttpRequest modifyHttpRequest = InterceptorTestUtils.modifyHttpRequestContext(GetObjectRequest.builder().build()); Optional<AsyncRequestBody> asyncRequestBody = interceptor.modifyAsyncHttpContent(modifyHttpRequest, executionAttributes); assertThat(asyncRequestBody).isEqualTo(modifyHttpRequest.asyncRequestBody()); }
@Test public void modifyAsyncHttpContent_putObjectRequest_checksumDisabled_shouldNotModify() { ExecutionAttributes executionAttributes = getExecutionAttributesWithChecksumDisabled(); Context.ModifyHttpRequest modifyHttpRequest = InterceptorTestUtils.modifyHttpRequestContext(GetObjectRequest.builder().build()); Optional<AsyncRequestBody> asyncRequestBody = interceptor.modifyAsyncHttpContent(modifyHttpRequest, executionAttributes); assertThat(asyncRequestBody).isEqualTo(modifyHttpRequest.asyncRequestBody()); } |
### Question:
IoUtils { public static String toUtf8String(InputStream is) throws IOException { return new String(toByteArray(is), StandardCharsets.UTF_8); } private IoUtils(); static byte[] toByteArray(InputStream is); static String toUtf8String(InputStream is); static void closeQuietly(AutoCloseable is, Logger log); static void closeIfCloseable(Object maybeCloseable, Logger log); static long copy(InputStream in, OutputStream out); static long copy(InputStream in, OutputStream out, long readLimit); static void drainInputStream(InputStream in); static void markStreamWithMaxReadLimit(InputStream s); }### Answer:
@Test public void testEmptyByteArray() throws Exception { String s = IoUtils.toUtf8String(new ByteArrayInputStream(new byte[0])); assertEquals("", s); }
@Test public void testZeroByteStream() throws Exception { String s = IoUtils.toUtf8String(new InputStream() { @Override public int read() throws IOException { return -1; } }); assertEquals("", s); }
@Test public void test() throws Exception { String s = IoUtils.toUtf8String(new ByteArrayInputStream("Testing".getBytes(StandardCharsets.UTF_8))); assertEquals("Testing", s); } |
### Question:
IoUtils { public static void drainInputStream(InputStream in) { try { while (in.read() != -1) { } } catch (IOException ignored) { } } private IoUtils(); static byte[] toByteArray(InputStream is); static String toUtf8String(InputStream is); static void closeQuietly(AutoCloseable is, Logger log); static void closeIfCloseable(Object maybeCloseable, Logger log); static long copy(InputStream in, OutputStream out); static long copy(InputStream in, OutputStream out, long readLimit); static void drainInputStream(InputStream in); static void markStreamWithMaxReadLimit(InputStream s); }### Answer:
@Test public void drainInputStream_AlreadyEos_DoesNotThrowException() throws IOException { final InputStream inputStream = randomInputStream(); while (inputStream.read() != -1) { } IoUtils.drainInputStream(inputStream); }
@Test public void drainInputStream_RemainingBytesInStream_ReadsAllRemainingData() throws IOException { final InputStream inputStream = randomInputStream(); IoUtils.drainInputStream(inputStream); assertEquals(-1, inputStream.read()); } |
### Question:
CachedSupplier implements Supplier<T>, SdkAutoCloseable { public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } private CachedSupplier(Builder<T> builder); static CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier); @Override T get(); @Override void close(); }### Answer:
@Test public void allCallsBeforeInitializationBlock() { try (WaitingSupplier waitingSupplier = new WaitingSupplier(future(), future())) { CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier).build(); performAsyncGets(cachedSupplier, 2); waitingSupplier.waitForGetsToHaveStarted(2); } }
@Test public void staleValueBlocksAllCalls() { try (WaitingSupplier waitingSupplier = new WaitingSupplier(past(), future())) { CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier).build(); waitingSupplier.permits.release(1); waitFor(performAsyncGet(cachedSupplier)); performAsyncGets(cachedSupplier, 2); waitingSupplier.waitForGetsToHaveStarted(3); waitingSupplier.permits.release(50); waitForAsyncGetsToFinish(); waitingSupplier.waitForGetsToHaveFinished(3); } }
@Test public void basicCachingWorks() { try (WaitingSupplier waitingSupplier = new WaitingSupplier(future(), future())) { CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier).build(); waitingSupplier.permits.release(5); waitFor(performAsyncGets(cachedSupplier, 5)); waitingSupplier.waitForGetsToHaveFinished(1); } }
@Test public void oneCallerBlocksPrefetchStrategyWorks() throws InterruptedException { try (WaitingSupplier waitingSupplier = new WaitingSupplier(future(), past())) { CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier) .prefetchStrategy(new OneCallerBlocks()) .build(); waitingSupplier.permits.release(1); waitFor(performAsyncGet(cachedSupplier)); performAsyncGet(cachedSupplier); waitingSupplier.waitForGetsToHaveStarted(2); waitFor(performAsyncGet(cachedSupplier)); waitingSupplier.permits.release(50); waitForAsyncGetsToFinish(); waitingSupplier.waitForGetsToHaveFinished(2); } }
@Test public void nonBlockingPrefetchStrategyWorks() { try (WaitingSupplier waitingSupplier = new WaitingSupplier(future(), past()); CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier) .prefetchStrategy(new NonBlocking("test-%s")) .build()) { waitingSupplier.permits.release(1); waitFor(performAsyncGet(cachedSupplier)); waitFor(performAsyncGet(cachedSupplier)); waitingSupplier.waitForGetsToHaveStarted(2); waitingSupplier.waitForGetsToHaveFinished(1); } } |
### Question:
ComparableUtils { public static <T> int safeCompare(Comparable<T> d1, T d2) { if (d1 != null && d2 != null) { return d1.compareTo(d2); } else if (d1 == null && d2 != null) { return -1; } else if (d1 != null) { return 1; } else { return 0; } } private ComparableUtils(); static int safeCompare(Comparable<T> d1, T d2); @SafeVarargs static T minimum(T... values); }### Answer:
@Test public void safeCompare_SecondNull_ReturnsPositive() { assertThat(ComparableUtils.safeCompare(1.0, null), greaterThan(0)); }
@Test public void safeCompare_FirstNull_ReturnsNegative() { assertThat(ComparableUtils.safeCompare(null, 7.0), lessThan(0)); }
@Test public void safeCompare_BothNull_ReturnsZero() { assertThat(ComparableUtils.safeCompare(null, null), equalTo(0)); }
@Test public void safeCompare_FirstLarger_ReturnsPositive() { assertThat(ComparableUtils.safeCompare(7.0, 6.0), greaterThan(0)); }
@Test public void safeCompare_SecondLarger_ReturnsNegative() { assertThat(ComparableUtils.safeCompare(6.0, 7.0), lessThan(0)); } |
### Question:
BinaryUtils { public static String toHex(byte[] data) { return Base16Lower.encodeAsString(data); } private BinaryUtils(); static String toHex(byte[] data); static byte[] fromHex(String hexData); static String toBase64(byte[] data); static byte[] toBase64Bytes(byte[] data); static byte[] fromBase64(String b64Data); static byte[] fromBase64Bytes(byte[] b64Data); static ByteArrayInputStream toStream(ByteBuffer byteBuffer); static byte[] copyAllBytesFrom(ByteBuffer bb); static byte[] copyRemainingBytesFrom(ByteBuffer bb); static byte[] copyBytesFrom(ByteBuffer bb); }### Answer:
@Test public void testHex() { { String hex = BinaryUtils.toHex(new byte[] {0}); System.out.println(hex); String hex2 = Base16Lower.encodeAsString(new byte[] {0}); assertEquals(hex, hex2); } { String hex = BinaryUtils.toHex(new byte[] {-1}); System.out.println(hex); String hex2 = Base16Lower.encodeAsString(new byte[] {-1}); assertEquals(hex, hex2); } } |
### Question:
BinaryUtils { public static byte[] copyRemainingBytesFrom(ByteBuffer bb) { if (bb == null) { return null; } if (!bb.hasRemaining()) { return EMPTY_BYTE_ARRAY; } if (bb.hasArray()) { int endIdx = bb.arrayOffset() + bb.limit(); int startIdx = endIdx - bb.remaining(); return Arrays.copyOfRange(bb.array(), startIdx, endIdx); } ByteBuffer copy = bb.asReadOnlyBuffer(); byte[] dst = new byte[copy.remaining()]; copy.get(dst); return dst; } private BinaryUtils(); static String toHex(byte[] data); static byte[] fromHex(String hexData); static String toBase64(byte[] data); static byte[] toBase64Bytes(byte[] data); static byte[] fromBase64(String b64Data); static byte[] fromBase64Bytes(byte[] b64Data); static ByteArrayInputStream toStream(ByteBuffer byteBuffer); static byte[] copyAllBytesFrom(ByteBuffer bb); static byte[] copyRemainingBytesFrom(ByteBuffer bb); static byte[] copyBytesFrom(ByteBuffer bb); }### Answer:
@Test public void testCopyRemainingBytesFrom_nullBuffer() { assertThat(BinaryUtils.copyRemainingBytesFrom(null)).isNull(); }
@Test public void testCopyRemainingBytesFrom_noRemainingBytes() { ByteBuffer bb = ByteBuffer.allocate(1); bb.put(new byte[]{1}); bb.flip(); bb.get(); assertThat(BinaryUtils.copyRemainingBytesFrom(bb)).hasSize(0); }
@Test public void testCopyRemainingBytesFrom_fullBuffer() { ByteBuffer bb = ByteBuffer.allocate(4); bb.put(new byte[]{1, 2, 3, 4}); bb.flip(); byte[] copy = BinaryUtils.copyRemainingBytesFrom(bb); assertThat(bb).isEqualTo(ByteBuffer.wrap(copy)); assertThat(copy).hasSize(4); }
@Test public void testCopyRemainingBytesFrom_partiallyReadBuffer() { ByteBuffer bb = ByteBuffer.allocate(4); bb.put(new byte[]{1, 2, 3, 4}); bb.flip(); bb.get(); bb.get(); byte[] copy = BinaryUtils.copyRemainingBytesFrom(bb); assertThat(bb).isEqualTo(ByteBuffer.wrap(copy)); assertThat(copy).hasSize(2); } |
### Question:
Lazy { public T getValue() { T result = value; if (result == null) { synchronized (this) { result = value; if (result == null) { result = initializer.get(); value = result; } } } return result; } Lazy(Supplier<T> initializer); T getValue(); @Override String toString(); }### Answer:
@Test public void nullIsNotCached() { Mockito.when(mockDelegate.get()).thenReturn(null); lazy.getValue(); lazy.getValue(); Mockito.verify(mockDelegate, times(2)).get(); }
@Test(timeout = 10_000) public void delegateCalledOnlyOnce() throws Exception { final int threads = 5; ExecutorService executor = Executors.newFixedThreadPool(threads); try { for (int i = 0; i < 1000; ++i) { mockDelegate = Mockito.mock(Supplier.class); Mockito.when(mockDelegate.get()).thenReturn(""); lazy = new Lazy<>(mockDelegate); CountDownLatch everyoneIsWaitingLatch = new CountDownLatch(threads); CountDownLatch everyoneIsDoneLatch = new CountDownLatch(threads); CountDownLatch callGetValueLatch = new CountDownLatch(1); for (int j = 0; j < threads; ++j) { executor.submit(() -> { everyoneIsWaitingLatch.countDown(); callGetValueLatch.await(); lazy.getValue(); everyoneIsDoneLatch.countDown(); return null; }); } everyoneIsWaitingLatch.await(); callGetValueLatch.countDown(); everyoneIsDoneLatch.await(); Mockito.verify(mockDelegate, times(1)).get(); } } finally { executor.shutdownNow(); } } |
### Question:
AttributeMap implements ToCopyableBuilder<AttributeMap.Builder, AttributeMap>, SdkAutoCloseable { public static Builder builder() { return new Builder(); } private AttributeMap(Map<? extends Key<?>, ?> attributes); boolean containsKey(Key<T> typedKey); T get(Key<T> key); AttributeMap merge(AttributeMap lowerPrecedence); static AttributeMap empty(); AttributeMap copy(); @Override void close(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); @Override Builder toBuilder(); static Builder builder(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void putAll_ThrowsRuntimeExceptionWhenTypesMismatched() { Map<AttributeMap.Key<?>, Object> attributes = new HashMap<>(); attributes.put(STRING_KEY, 42); AttributeMap.builder() .putAll(attributes) .build(); } |
### Question:
CollectionUtils { public static boolean isNullOrEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } private CollectionUtils(); static boolean isNullOrEmpty(Collection<?> collection); static boolean isNullOrEmpty(Map<?, ?> map); static List<T> mergeLists(List<T> list1, List<T> list2); static T firstIfPresent(List<T> list); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map, Supplier<Map<T, List<U>>> mapConstructor); static Map<T, List<U>> unmodifiableMapOfLists(Map<T, List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map,
Supplier<Map<T, List<U>>> mapConstructor); static Collector<Map.Entry<K, V>, ?, Map<K, V>> toMap(); static Map<K, VOutT> mapValues(Map<K, VInT> inputMap, Function<VInT, VOutT> mapper); }### Answer:
@Test public void isEmpty_NullCollection_ReturnsTrue() { assertTrue(CollectionUtils.isNullOrEmpty((Collection<?>) null)); }
@Test public void isEmpty_EmptyCollection_ReturnsTrue() { assertTrue(CollectionUtils.isNullOrEmpty(Collections.emptyList())); }
@Test public void isEmpty_NonEmptyCollection_ReturnsFalse() { assertFalse(CollectionUtils.isNullOrEmpty(Arrays.asList("something"))); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.