src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
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); }
@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); }
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); }
@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); }
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); }
@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)); }
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); }
@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())); }
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); }
@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); }
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); }
@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); }
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); }
@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); }
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); }
@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)); }
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); }
@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())); }
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); }
@Test public void getKeyNotInMap() { assertThat(metaTableSchemaCache.get(FakeItem.class)).isNotPresent(); }
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); }
@Test public void createReturnsExistingObject() { MetaTableSchema<FakeItem> metaTableSchema = metaTableSchemaCache.getOrCreate(FakeItem.class); assertThat(metaTableSchema).isNotNull(); assertThat(metaTableSchemaCache.getOrCreate(FakeItem.class)).isSameAs(metaTableSchema); }
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(); }
@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")); }
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(); }
@Test public void toBuilder() { DefaultDynamoDbEnhancedAsyncClient copiedObject = dynamoDbEnhancedAsyncClient.toBuilder().build(); assertThat(copiedObject, is(dynamoDbEnhancedAsyncClient)); }
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(); }
@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())); }
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); }
@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(); }
ExtensionResolver { public static List<DynamoDbEnhancedClientExtension> defaultExtensions() { return DEFAULT_EXTENSIONS; } private ExtensionResolver(); static List<DynamoDbEnhancedClientExtension> defaultExtensions(); static DynamoDbEnhancedClientExtension resolveExtensions(List<DynamoDbEnhancedClientExtension> extensions); }
@Test public void defaultExtensions_isImmutable() { List<DynamoDbEnhancedClientExtension> defaultExtensions = ExtensionResolver.defaultExtensions(); assertThatThrownBy(() -> defaultExtensions.add(mockExtension1)).isInstanceOf(UnsupportedOperationException.class); }
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(); }
@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")); }
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(); }
@Test public void toBuilder() { DefaultDynamoDbEnhancedClient copiedObject = dynamoDbEnhancedClient.toBuilder().build(); assertThat(copiedObject, is(dynamoDbEnhancedClient)); }
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(); }
@Test(expected = IllegalArgumentException.class) public void index_invalidIndex_throwsIllegalArgumentException() { DefaultDynamoDbTable<FakeItemWithIndices> dynamoDbMappedTable = new DefaultDynamoDbTable<>(mockDynamoDbClient, mockDynamoDbEnhancedClientExtension, FakeItemWithIndices.getTableSchema(), TABLE_NAME); dynamoDbMappedTable.index("invalid"); }
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(); }
@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())); }
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(); }
@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())); }
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(); }
@Test(expected = IllegalArgumentException.class) public void index_invalidIndex_throwsIllegalArgumentException() { DefaultDynamoDbAsyncTable<FakeItemWithIndices> dynamoDbMappedTable = new DefaultDynamoDbAsyncTable<>(mockDynamoDbAsyncClient, mockDynamoDbEnhancedClientExtension, FakeItemWithIndices.getTableSchema(), TABLE_NAME); dynamoDbMappedTable.index("invalid"); }
DefaultDynamoDbAsyncTable implements DynamoDbAsyncTable<T> { @Override public Key keyFrom(T item) { return createKeyFromItem(item, tableSchema, TableMetadata.primaryIndexName()); } 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(); }
@Test public void keyFrom_primaryIndex_partitionAndSort() { FakeItemWithSort item = FakeItemWithSort.createUniqueFakeItemWithSort(); DefaultDynamoDbAsyncTable<FakeItemWithSort> dynamoDbMappedIndex = new DefaultDynamoDbAsyncTable<>(mockDynamoDbAsyncClient, 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(); DefaultDynamoDbAsyncTable<FakeItem> dynamoDbMappedIndex = new DefaultDynamoDbAsyncTable<>(mockDynamoDbAsyncClient, 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(); DefaultDynamoDbAsyncTable<FakeItemWithSort> dynamoDbMappedIndex = new DefaultDynamoDbAsyncTable<>(mockDynamoDbAsyncClient, mockDynamoDbEnhancedClientExtension, FakeItemWithSort.getTableSchema(), "test_table"); Key key = dynamoDbMappedIndex.keyFrom(item); assertThat(key.partitionKeyValue(), is(stringValue(item.getId()))); assertThat(key.sortKeyValue(), is(Optional.empty())); }
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); }
@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(); }
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(); }
@Test public void build_missingProperty_getObjectRequest() { assertThatThrownBy(() -> GetObjectPresignRequest.builder() .signatureDuration(Duration.ofSeconds(123L)) .build()) .isInstanceOf(NullPointerException.class) .hasMessageContaining("getObjectRequest"); }
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); }
@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); }
ConverterProviderResolver { public static AttributeConverterProvider defaultConverterProvider() { return DEFAULT_ATTRIBUTE_CONVERTER; } private ConverterProviderResolver(); static AttributeConverterProvider defaultConverterProvider(); static AttributeConverterProvider resolveProviders(List<AttributeConverterProvider> providers); }
@Test public void defaultProvider_returnsInstance() { AttributeConverterProvider defaultProvider = ConverterProviderResolver.defaultConverterProvider(); assertThat(defaultProvider).isNotNull(); assertThat(defaultProvider).isInstanceOf(DefaultAttributeConverterProvider.class); }
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); }
@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)); }
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); }
@Test public void cleanAttributeName_cleansSpecialCharacters() { String result = EnhancedClientUtils.cleanAttributeName("a*b.c-d:e#f"); assertThat(result).isEqualTo("a_b_c_d_e_f"); }
VersionedRecordExtension implements DynamoDbEnhancedClientExtension { public static Builder builder() { return new Builder(); } private VersionedRecordExtension(); static Builder builder(); @Override WriteModification beforeWrite(DynamoDbExtensionContext.BeforeWrite context); }
@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())); }
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(); }
@Test public void joinExpressions_correctlyJoins() { String result = Expression.joinExpressions("one", "two", " AND "); assertThat(result, is("(one) AND (two)")); }
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(); }
@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); }
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(); }
@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); }
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); }
@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("")); }
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); }
@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("")); }
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); }
@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'")); }
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); }
@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")); }
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); }
@Test public void testStartsWithIgnoreCase() { assertTrue(StringUtils.startsWithIgnoreCase("helloworld", "hello")); assertTrue(StringUtils.startsWithIgnoreCase("hELlOwOrlD", "hello")); assertFalse(StringUtils.startsWithIgnoreCase("hello", "world")); }
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); }
@Test public void testReplacePrefixIgnoreCase() { assertEquals("lloWorld" ,replacePrefixIgnoreCase("helloWorld", "he", "")); assertEquals("lloWORld" ,replacePrefixIgnoreCase("helloWORld", "He", "")); assertEquals("llOwOrld" ,replacePrefixIgnoreCase("HEllOwOrld", "he", "")); }
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); }
@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", ':')); }
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); }
@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")); }
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); }
@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)); }
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); }
@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)); }
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); }
@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(); }
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); }
@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); }
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); }
@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()); }
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); }
@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); }
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); }
@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"); }
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); }
@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()); } }
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); }
@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); }
Validate { public static <T> T[] notEmpty(final T[] array, final String message, final Object... values) { if (array == null) { throw new NullPointerException(String.format(message, values)); } if (array.length == 0) { throw new IllegalArgumentException(String.format(message, values)); } return array; } 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); }
@Test public void testNotEmptyArray2() { Validate.notEmpty(new Object[] {null}, "MSG"); try { Validate.notEmpty((Object[]) null, "MSG"); fail("Expecting NullPointerException"); } catch (final NullPointerException ex) { assertEquals("MSG", ex.getMessage()); } try { Validate.notEmpty(new Object[0], "MSG"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } final String[] array = new String[] {"hi"}; final String[] test = Validate.notEmpty(array, "Message"); assertSame(array, test); } @Test public void testNotEmptyCollection2() { final Collection<Integer> coll = new ArrayList<>(); try { Validate.notEmpty((Collection<?>) null, "MSG"); fail("Expecting NullPointerException"); } catch (final NullPointerException ex) { assertEquals("MSG", ex.getMessage()); } try { Validate.notEmpty(coll, "MSG"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } coll.add(8); Validate.notEmpty(coll, "MSG"); final Collection<Integer> test = Validate.notEmpty(coll, "Message"); assertSame(coll, test); } @Test public void testNotEmptyMap2() { final Map<String, Integer> map = new HashMap<>(); try { Validate.notEmpty((Map<?, ?>) null, "MSG"); fail("Expecting NullPointerException"); } catch (final NullPointerException ex) { assertEquals("MSG", ex.getMessage()); } try { Validate.notEmpty(map, "MSG"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } map.put("ll", 8); Validate.notEmpty(map, "MSG"); final Map<String, Integer> test = Validate.notEmpty(map, "Message"); assertSame(map, test); } @Test public void testNotEmptyString2() { Validate.notEmpty("a", "MSG"); try { Validate.notEmpty((String) null, "MSG"); fail("Expecting NullPointerException"); } catch (final NullPointerException ex) { assertEquals("MSG", ex.getMessage()); } try { Validate.notEmpty("", "MSG"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } final String str = "Hi"; final String testStr = Validate.notEmpty(str, "Message"); assertSame(str, testStr); }
Validate { public static <T extends CharSequence> T notBlank(final T chars, final String message, final Object... values) { if (chars == null) { throw new NullPointerException(String.format(message, values)); } if (StringUtils.isBlank(chars)) { throw new IllegalArgumentException(String.format(message, values)); } return chars; } 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); }
@Test public void testNotBlankMsgNullStringShouldThrow() { final String string = null; try { Validate.notBlank(string, "Message"); fail("Expecting NullPointerException"); } catch (final NullPointerException e) { assertEquals("Message", e.getMessage()); } } @Test public void testNotBlankMsgBlankStringShouldThrow() { final String string = " \n \t \r \n "; try { Validate.notBlank(string, "Message"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException e) { assertEquals("Message", e.getMessage()); } } @Test public void testNotBlankMsgBlankStringWithWhitespacesShouldThrow() { final String string = " "; try { Validate.notBlank(string, "Message"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException e) { assertEquals("Message", e.getMessage()); } } @Test public void testNotBlankMsgEmptyStringShouldThrow() { final String string = ""; try { Validate.notBlank(string, "Message"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException e) { assertEquals("Message", e.getMessage()); } } @Test public void testNotBlankMsgNotBlankStringShouldNotThrow() { final String string = "abc"; Validate.notBlank(string, "Message"); } @Test public void testNotBlankMsgNotBlankStringWithWhitespacesShouldNotThrow() { final String string = " abc "; Validate.notBlank(string, "Message"); } @Test public void testNotBlankMsgNotBlankStringWithNewlinesShouldNotThrow() { final String string = " \n \t abc \r \n "; Validate.notBlank(string, "Message"); }
Validate { public static <T> T[] noNullElements(final T[] array, final String message, final Object... values) { Validate.notNull(array, message); for (T anArray : array) { if (anArray == null) { throw new IllegalArgumentException(String.format(message, values)); } } return array; } 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); }
@Test public void testNoNullElementsArray2() { String[] array = new String[] {"a", "b"}; Validate.noNullElements(array, "MSG"); try { Validate.noNullElements((Object[]) null, "MSG"); fail("Expecting NullPointerException"); } catch (final NullPointerException ex) { assertEquals("MSG", ex.getMessage()); } array[1] = null; try { Validate.noNullElements(array, "MSG"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } array = new String[] {"a", "b"}; final String[] test = Validate.noNullElements(array, "Message"); assertSame(array, test); } @Test public void testNoNullElementsCollection2() { final List<String> coll = new ArrayList<>(); coll.add("a"); coll.add("b"); Validate.noNullElements(coll, "MSG"); try { Validate.noNullElements((Collection<?>) null, "MSG"); fail("Expecting NullPointerException"); } catch (final NullPointerException ex) { assertEquals("The validated object is null", ex.getMessage()); } coll.set(1, null); try { Validate.noNullElements(coll, "MSG"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException ex) { assertEquals("MSG", ex.getMessage()); } coll.set(1, "b"); final List<String> test = Validate.noNullElements(coll, "Message"); assertSame(coll, test); }
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); }
@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()); } }
Validate { public static <T extends Comparable<U>, U> T exclusiveBetween(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); }
@Test public void testExclusiveBetween_withMessage() { Validate.exclusiveBetween("a", "c", "b", "Error"); try { Validate.exclusiveBetween("0", "5", "6", "Error"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException e) { assertEquals("Error", e.getMessage()); } try { Validate.exclusiveBetween("0", "5", "5", "Error"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException e) { assertEquals("Error", e.getMessage()); } } @Test public void testExclusiveBetweenLong_withMessage() { Validate.exclusiveBetween(0, 2, 1, "Error"); try { Validate.exclusiveBetween(0, 5, 6, "Error"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException e) { assertEquals("Error", e.getMessage()); } try { Validate.exclusiveBetween(0, 5, 5, "Error"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException e) { assertEquals("Error", e.getMessage()); } } @Test public void testExclusiveBetweenDouble_withMessage() { Validate.exclusiveBetween(0.1, 2.1, 1.1, "Error"); try { Validate.exclusiveBetween(0.1, 5.1, 6.1, "Error"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException e) { assertEquals("Error", e.getMessage()); } try { Validate.exclusiveBetween(0.1, 5.1, 5.1, "Error"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException e) { assertEquals("Error", e.getMessage()); } }
Validate { public static <T, U> U isInstanceOf(final Class<U> type, final T obj, final String message, final Object... values) { if (!type.isInstance(obj)) { throw new IllegalArgumentException(String.format(message, values)); } return type.cast(obj); } 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); }
@Test public void testIsInstanceOf_withMessage() { Validate.isInstanceOf(String.class, "hi", "Error"); Validate.isInstanceOf(Integer.class, 1, "Error"); try { Validate.isInstanceOf(List.class, "hi", "Error"); fail("Expecting IllegalArgumentException"); } catch(final IllegalArgumentException e) { assertEquals("Error", e.getMessage()); } } @Test public void testIsInstanceOf_withMessageArgs() { Validate.isInstanceOf(String.class, "hi", "Error %s=%s", "Name", "Value"); Validate.isInstanceOf(Integer.class, 1, "Error %s=%s", "Name", "Value"); try { Validate.isInstanceOf(List.class, "hi", "Error %s=%s", "Name", "Value"); fail("Expecting IllegalArgumentException"); } catch(final IllegalArgumentException e) { assertEquals("Error Name=Value", e.getMessage()); } try { Validate.isInstanceOf(List.class, "hi", "Error %s=%s", List.class, "Value"); fail("Expecting IllegalArgumentException"); } catch(final IllegalArgumentException e) { assertEquals("Error interface java.util.List=Value", e.getMessage()); } try { Validate.isInstanceOf(List.class, "hi", "Error %s=%s", List.class, null); fail("Expecting IllegalArgumentException"); } catch(final IllegalArgumentException e) { assertEquals("Error interface java.util.List=null", e.getMessage()); } }
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); }
@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()); }
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); }
@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()); } }
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); }
@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")); }
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); }
@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); }
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); }
@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"); }
Validate { public static Duration isPositiveOrNull(Duration duration, String fieldName) { if (duration == null) { return null; } return isPositive(duration, fieldName); } 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); }
@Test public void isPositiveOrNullInteger_null_returnsNull() { assertNull(Validate.isPositiveOrNull((Integer) null, "foo")); } @Test public void isPositiveOrNullInteger_positive_returnsInteger() { Integer num = 42; assertEquals(num, Validate.isPositiveOrNull(num, "foo")); } @Test public void isPositiveOrNullInteger_zero_throws() { expected.expect(IllegalArgumentException.class); expected.expectMessage("foo"); Validate.isPositiveOrNull(0, "foo"); } @Test public void isPositiveOrNullInteger_negative_throws() { expected.expect(IllegalArgumentException.class); expected.expectMessage("foo"); Validate.isPositiveOrNull(-1, "foo"); } @Test public void isPositiveOrNullLong_null_returnsNull() { assertNull(Validate.isPositiveOrNull((Long) null, "foo")); } @Test public void isPositiveOrNullLong_positive_returnsInteger() { Long num = 42L; assertEquals(num, Validate.isPositiveOrNull(num, "foo")); } @Test public void isPositiveOrNullLong_zero_throws() { expected.expect(IllegalArgumentException.class); expected.expectMessage("foo"); Validate.isPositiveOrNull(0L, "foo"); } @Test public void isPositiveOrNullLong_negative_throws() { expected.expect(IllegalArgumentException.class); expected.expectMessage("foo"); Validate.isPositiveOrNull(-1L, "foo"); }
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); }
@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"); }
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(); }
@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)); }
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(); }
@Test(expected = NullPointerException.class) public void leftValueNull_ThrowsException() { Either.left(null); }
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); }
@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()); }
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(); }
@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)); }
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(); }
@Test(expected = NullPointerException.class) public void rightValueNull_ThrowsException() { Either.right(null); }
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(); }
@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); }
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); }
@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); } }
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(); }
@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()); }
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); }
@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))); }
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); }
@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); }
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); }
@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); }
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); }
@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); }
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); }
@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); }
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); }
@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); }
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); }
@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"); }
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); }
@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()); }
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); }
@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); }
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); }
@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()); }
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(); }
@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); } }
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); }
@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)); }
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); }
@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); } }
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); }
@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); }
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(); }
@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(); } }
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(); }
@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(); }
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); }
@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"))); }
CollectionUtils { public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } 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); }
@Test public void firstIfPresent_NullList_ReturnsNull() { List<String> list = null; assertThat(CollectionUtils.firstIfPresent(list)).isNull(); } @Test public void firstIfPresent_EmptyList_ReturnsNull() { List<String> list = Collections.emptyList(); assertThat(CollectionUtils.firstIfPresent(list)).isNull(); } @Test public void firstIfPresent_SingleElementList_ReturnsOnlyElement() { assertThat(CollectionUtils.firstIfPresent(singletonList("foo"))).isEqualTo("foo"); } @Test public void firstIfPresent_MultipleElementList_ReturnsFirstElement() { assertThat(CollectionUtils.firstIfPresent(Arrays.asList("foo", "bar", "baz"))).isEqualTo("foo"); } @Test public void firstIfPresent_FirstElementNull_ReturnsNull() { assertThat(CollectionUtils.firstIfPresent(Arrays.asList(null, "bar", "baz"))).isNull(); }
AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse()) && context.responsePublisher().isPresent()) { long contentLength = context.httpResponse() .firstMatchingHeader(CONTENT_LENGTH_HEADER) .map(Long::parseLong) .orElse(0L); SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(CHECKSUM, checksum); if (contentLength > 0) { return Optional.of(new ChecksumValidatingPublisher(context.responsePublisher().get(), checksum, contentLength)); } } return context.responsePublisher(); } @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); }
@Test public void modifyAsyncHttpResponseContent_getObjectRequest_checksumEnabled_shouldWrapChecksumValidatingPublisher() { SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader(); Context.ModifyHttpResponse modifyHttpResponse = InterceptorTestUtils.modifyHttpResponse(GetObjectRequest.builder().build(), sdkHttpResponse); Optional<Publisher<ByteBuffer>> publisher = interceptor.modifyAsyncHttpResponseContent(modifyHttpResponse, getExecutionAttributes()); assertThat(publisher.get()).isExactlyInstanceOf(ChecksumValidatingPublisher.class); } @Test public void modifyAsyncHttpResponseContent_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<Publisher<ByteBuffer>> publisher = interceptor.modifyAsyncHttpResponseContent(modifyHttpResponse, executionAttributes); assertThat(publisher).isEqualTo(modifyHttpResponse.responsePublisher()); } @Test public void modifyAsyncHttpResponseContent_nonGetObjectRequest_shouldNotModify() { ExecutionAttributes executionAttributes = getExecutionAttributes(); SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader(); sdkHttpResponse.toBuilder().clearHeaders(); Context.ModifyHttpResponse modifyHttpResponse = InterceptorTestUtils.modifyHttpResponse(PutObjectRequest.builder().build(), sdkHttpResponse); Optional<Publisher<ByteBuffer>> publisher = interceptor.modifyAsyncHttpResponseContent(modifyHttpResponse, executionAttributes); assertThat(publisher).isEqualTo(modifyHttpResponse.responsePublisher()); }
ToString { public static String create(String className) { return className + "()"; } private ToString(String className); static String create(String className); static ToString builder(String className); ToString add(String fieldName, Object field); String build(); }
@Test public void createIsCorrect() { assertThat(ToString.create("Foo")).isEqualTo("Foo()"); }
ImmutableMap implements Map<K, V> { public V put(K key, V value) { throw new UnsupportedOperationException(UNMODIFIABLE_MESSAGE); } private ImmutableMap(Map<K, V> map); static Builder<K, V> builder(); static ImmutableMap<K, V> of(K k0, V v0); static ImmutableMap<K, V> of(K k0, V v0, K k1, V v1); static ImmutableMap<K, V> of(K k0, V v0, K k1, V v1, K k2, V v2); static ImmutableMap<K, V> of(K k0, V v0, K k1, V v1, K k2, V v2, K k3, V v3); static ImmutableMap<K, V> of(K k0, V v0, K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4); boolean containsKey(Object key); boolean containsValue(Object value); Set<Entry<K, V>> entrySet(); V get(Object key); boolean isEmpty(); Set<K> keySet(); int size(); Collection<V> values(); void clear(); V put(K key, V value); void putAll(Map<? extends K, ? extends V> map); V remove(Object key); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
@Test public void testErrorOnDuplicateKeys() { try { Map<Integer, String> builtMap = new ImmutableMap.Builder<Integer, String>() .put(1, "one") .put(1, "two") .build(); fail("IllegalArgumentException expected."); } catch (IllegalArgumentException iae) { } catch (Exception e) { fail("IllegalArgumentException expected."); } }
ThreadFactoryBuilder { public ThreadFactory build() { String threadNamePrefixWithPoolNumber = threadNamePrefix + "-" + POOL_NUMBER.getAndIncrement() % POOL_NUMBER_MAX; ThreadFactory result = new NamedThreadFactory(Executors.defaultThreadFactory(), threadNamePrefixWithPoolNumber); if (daemonThreads) { result = new DaemonThreadFactory(result); } return result; } ThreadFactoryBuilder threadNamePrefix(String threadNamePrefix); ThreadFactoryBuilder daemonThreads(Boolean daemonThreads); ThreadFactory build(); }
@Test public void poolNumberWrapsAround() { for (int i = 0; i < 9_9999; i++) { new ThreadFactoryBuilder().build(); } Thread threadBeforeWrap = new ThreadFactoryBuilder().build().newThread(this::doNothing); assertThat(threadBeforeWrap.getName()).isEqualTo("aws-java-sdk-9999-0"); Thread threadAfterWrap = new ThreadFactoryBuilder().build().newThread(this::doNothing); assertThat(threadAfterWrap.getName()).isEqualTo("aws-java-sdk-0-0"); }
MetricCollectionAggregator { public List<PutMetricDataRequest> getRequests() { List<PutMetricDataRequest> requests = new ArrayList<>(); List<MetricDatum> requestMetricDatums = new ArrayList<>(); ValuesInRequestCounter valuesInRequestCounter = new ValuesInRequestCounter(); Map<Instant, Collection<MetricAggregator>> metrics = timeBucketedMetrics.timeBucketedMetrics(); for (Map.Entry<Instant, Collection<MetricAggregator>> entry : metrics.entrySet()) { Instant timeBucket = entry.getKey(); for (MetricAggregator metric : entry.getValue()) { if (requestMetricDatums.size() >= MAX_METRIC_DATA_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); } metric.ifSummary(summaryAggregator -> requestMetricDatums.add(summaryMetricDatum(timeBucket, summaryAggregator))); metric.ifDetailed(detailedAggregator -> { int startIndex = 0; Collection<DetailedMetrics> detailedMetrics = detailedAggregator.detailedMetrics(); while (startIndex < detailedMetrics.size()) { if (valuesInRequestCounter.get() >= MAX_VALUES_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); valuesInRequestCounter.reset(); } MetricDatum data = detailedMetricDatum(timeBucket, detailedAggregator, startIndex, MAX_VALUES_PER_REQUEST - valuesInRequestCounter.get()); int valuesAdded = data.values().size(); startIndex += valuesAdded; valuesInRequestCounter.add(valuesAdded); requestMetricDatums.add(data); } }); } } if (!requestMetricDatums.isEmpty()) { requests.add(newPutRequest(requestMetricDatums)); } timeBucketedMetrics.reset(); return requests; } MetricCollectionAggregator(String namespace, Set<SdkMetric<String>> dimensions, Set<MetricCategory> metricCategories, MetricLevel metricLevel, Set<SdkMetric<?>> detailedMetrics); void addCollection(MetricCollection collection); List<PutMetricDataRequest> getRequests(); static final int MAX_METRIC_DATA_PER_REQUEST; static final int MAX_VALUES_PER_REQUEST; }
@Test public void maximumRequestsIsHonored() { List<PutMetricDataRequest> requests; requests = aggregatorWithUniqueMetricsAdded(MetricCollectionAggregator.MAX_METRIC_DATA_PER_REQUEST).getRequests(); assertThat(requests).hasOnlyOneElementSatisfying(request -> { assertThat(request.metricData()).hasSize(MetricCollectionAggregator.MAX_METRIC_DATA_PER_REQUEST); }); requests = aggregatorWithUniqueMetricsAdded(MetricCollectionAggregator.MAX_METRIC_DATA_PER_REQUEST + 1).getRequests(); assertThat(requests).hasSize(2); assertThat(requests.get(0).metricData()).hasSize(MetricCollectionAggregator.MAX_METRIC_DATA_PER_REQUEST); assertThat(requests.get(1).metricData()).hasSize(1); } @Test public void maximumMetricValuesIsHonored() { List<PutMetricDataRequest> requests; requests = aggregatorWithUniqueValuesAdded(HttpMetric.MAX_CONCURRENCY, MetricCollectionAggregator.MAX_VALUES_PER_REQUEST).getRequests(); assertThat(requests).hasSize(1); validateValuesCount(requests.get(0), MetricCollectionAggregator.MAX_VALUES_PER_REQUEST); requests = aggregatorWithUniqueValuesAdded(HttpMetric.MAX_CONCURRENCY, MetricCollectionAggregator.MAX_VALUES_PER_REQUEST + 1).getRequests(); assertThat(requests).hasSize(2); validateValuesCount(requests.get(0), MetricCollectionAggregator.MAX_VALUES_PER_REQUEST); validateValuesCount(requests.get(1), 1); }
UploadMetricsTasks implements Callable<CompletableFuture<?>> { @Override public CompletableFuture<?> call() { try { List<PutMetricDataRequest> allRequests = collectionAggregator.getRequests(); List<PutMetricDataRequest> requests = allRequests; if (requests.size() > maximumRequestsPerFlush) { METRIC_LOGGER.warn(() -> "Maximum AWS SDK client-side metric call count exceeded: " + allRequests.size() + " > " + maximumRequestsPerFlush + ". Some metric requests will be dropped. This occurs " + "when the caller has configured too many metrics or too unique of dimensions without " + "an associated increase in the maximum-calls-per-upload configured on the publisher."); requests = requests.subList(0, maximumRequestsPerFlush); } return uploader.upload(requests); } catch (Throwable t) { return CompletableFutureUtils.failedFuture(t); } } UploadMetricsTasks(MetricCollectionAggregator collectionAggregator, MetricUploader uploader, int maximumRequestsPerFlush); @Override CompletableFuture<?> call(); }
@Test public void extraTasksAboveMaximumAreDropped() { List<PutMetricDataRequest> requests = Arrays.asList(PutMetricDataRequest.builder().build(), PutMetricDataRequest.builder().build(), PutMetricDataRequest.builder().build()); Mockito.when(aggregator.getRequests()).thenReturn(requests); task.call(); ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class); Mockito.verify(uploader).upload(captor.capture()); List<PutMetricDataRequest> uploadedRequests = captor.getValue(); assertThat(uploadedRequests).hasSize(2); assertThat(uploadedRequests).containsOnlyElementsOf(requests); }
MetricUploader { public CompletableFuture<Void> upload(List<PutMetricDataRequest> requests) { CompletableFuture<?>[] publishResults = startCalls(requests); return CompletableFuture.allOf(publishResults).whenComplete((r, t) -> { int numRequests = publishResults.length; if (t != null) { METRIC_LOGGER.warn(() -> "Failed while publishing some or all AWS SDK client-side metrics to CloudWatch.", t); } else { METRIC_LOGGER.debug(() -> "Successfully published " + numRequests + " AWS SDK client-side metric requests to CloudWatch."); } }); } MetricUploader(CloudWatchAsyncClient cloudWatchClient); CompletableFuture<Void> upload(List<PutMetricDataRequest> requests); void close(boolean closeClient); }
@Test public void uploadSuccessIsPropagated() { CompletableFuture<Void> uploadFuture = uploader.upload(Arrays.asList(PutMetricDataRequest.builder().build(), PutMetricDataRequest.builder().build())); assertThat(putMetricDataResponseFutures).hasSize(2); assertThat(uploadFuture).isNotCompleted(); putMetricDataResponseFutures.get(0).complete(PutMetricDataResponse.builder().build()); assertThat(uploadFuture).isNotCompleted(); putMetricDataResponseFutures.get(1).complete(PutMetricDataResponse.builder().build()); assertThat(uploadFuture).isCompleted(); } @Test public void uploadFailureIsPropagated() { CompletableFuture<Void> uploadFuture = uploader.upload(Arrays.asList(PutMetricDataRequest.builder().build(), PutMetricDataRequest.builder().build())); assertThat(putMetricDataResponseFutures).hasSize(2); assertThat(uploadFuture).isNotCompleted(); putMetricDataResponseFutures.get(0).completeExceptionally(new Throwable()); putMetricDataResponseFutures.get(1).complete(PutMetricDataResponse.builder().build()); assertThat(uploadFuture).isCompletedExceptionally(); }
MetricUploader { public void close(boolean closeClient) { if (closeClient) { this.cloudWatchClient.close(); } } MetricUploader(CloudWatchAsyncClient cloudWatchClient); CompletableFuture<Void> upload(List<PutMetricDataRequest> requests); void close(boolean closeClient); }
@Test public void closeFalseDoesNotCloseClient() { uploader.close(false); Mockito.verify(client, never()).close(); } @Test public void closeTrueClosesClient() { uploader.close(true); Mockito.verify(client, times(1)).close(); }
CloudWatchMetricPublisher implements MetricPublisher { @Override public void publish(MetricCollection metricCollection) { try { executor.submit(new AggregateMetricsTask(metricAggregator, metricCollection)); } catch (RejectedExecutionException e) { METRIC_LOGGER.warn(() -> "Some AWS SDK client-side metrics have been dropped because an internal executor did not " + "accept them. This usually occurs because your publisher has been shut down or you have " + "generated too many requests for the publisher to handle in a timely fashion.", e); } } private CloudWatchMetricPublisher(Builder builder); @Override void publish(MetricCollection metricCollection); @Override void close(); static Builder builder(); static CloudWatchMetricPublisher create(); }
@Test public void namespaceSettingIsHonored() { try (CloudWatchMetricPublisher publisher = publisherBuilder.namespace("namespace").build()) { MetricCollector collector = newCollector(); collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, 5); publisher.publish(new FixedTimeMetricCollection(collector.collect())); } assertThat(getPutMetricCall().namespace()).isEqualTo("namespace"); } @Test public void maximumCallsPerPublishSettingIsHonored() { try (CloudWatchMetricPublisher publisher = publisherBuilder.maximumCallsPerUpload(1) .detailedMetrics(HttpMetric.AVAILABLE_CONCURRENCY) .build()) { for (int i = 0; i < MetricCollectionAggregator.MAX_VALUES_PER_REQUEST + 1; ++i) { MetricCollector collector = newCollector(); collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, i); publisher.publish(new FixedTimeMetricCollection(collector.collect())); } } assertThat(getPutMetricCalls()).hasSize(1); } @Test public void detailedMetricsSettingIsHonored() { try (CloudWatchMetricPublisher publisher = publisherBuilder.detailedMetrics(HttpMetric.AVAILABLE_CONCURRENCY).build()) { for (int i = 0; i < 10; ++i) { MetricCollector collector = newCollector(); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 10); collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, i); publisher.publish(new FixedTimeMetricCollection(collector.collect())); } } PutMetricDataRequest call = getPutMetricCall(); MetricDatum concurrencyMetric = getDatum(call, HttpMetric.MAX_CONCURRENCY); MetricDatum availableConcurrency = getDatum(call, HttpMetric.AVAILABLE_CONCURRENCY); assertThat(concurrencyMetric.values()).isEmpty(); assertThat(concurrencyMetric.counts()).isEmpty(); assertThat(concurrencyMetric.statisticValues()).isNotNull(); assertThat(availableConcurrency.values()).isNotEmpty(); assertThat(availableConcurrency.counts()).isNotEmpty(); assertThat(availableConcurrency.statisticValues()).isNull(); }
SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } private SystemPropertyTlsKeyManagersProvider(); @Override KeyManager[] keyManagers(); static SystemPropertyTlsKeyManagersProvider create(); }
@Test public void propertiesNotSet_returnsNull() { assertThat(PROVIDER.keyManagers()).isNull(); } @Test public void propertiesSet_createsKeyManager() { System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD); assertThat(PROVIDER.keyManagers()).hasSize(1); } @Test public void storeDoesNotExist_returnsNull() { System.setProperty(SSL_KEY_STORE.property(), Paths.get("does", "not", "exist").toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD); assertThat(PROVIDER.keyManagers()).isNull(); } @Test public void invalidStoreType_returnsNull() { System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), "invalid"); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD); assertThat(PROVIDER.keyManagers()).isNull(); } @Test public void passwordIncorrect_returnsNull() { System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), "not correct password"); assertThat(PROVIDER.keyManagers()).isNull(); } @Test public void customKmfAlgorithmSetInProperty_usesAlgorithm() { System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD); assertThat(PROVIDER.keyManagers()).isNotNull(); String property = "ssl.KeyManagerFactory.algorithm"; String previousValue = Security.getProperty(property); Security.setProperty(property, "some-bogus-value"); try { assertThat(PROVIDER.keyManagers()).isNull(); } finally { Security.setProperty(property, previousValue); } }
FileStoreTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } private FileStoreTlsKeyManagersProvider(Path storePath, String storeType, char[] password); @Override KeyManager[] keyManagers(); static FileStoreTlsKeyManagersProvider create(Path path, String type, String password); }
@Test(expected = NullPointerException.class) public void storePathNull_throwsValidationException() { FileStoreTlsKeyManagersProvider.create(null, CLIENT_STORE_TYPE, STORE_PASSWORD); } @Test(expected = NullPointerException.class) public void storeTypeNull_throwsValidationException() { FileStoreTlsKeyManagersProvider.create(clientKeyStore, null, STORE_PASSWORD); } @Test(expected = IllegalArgumentException.class) public void storeTypeEmpty_throwsValidationException() { FileStoreTlsKeyManagersProvider.create(clientKeyStore, "", STORE_PASSWORD); } @Test public void passwordNotGiven_doesNotThrowValidationException() { FileStoreTlsKeyManagersProvider.create(clientKeyStore, CLIENT_STORE_TYPE, null); }