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(Sc... | @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 = sc... |
ScanOperation implements PaginatedTableOperation<T, ScanRequest, ScanResponse>,
PaginatedIndexOperation<T, ScanRequest, ScanResponse> { @Override public Function<ScanRequest, SdkPublisher<ScanResponse>> asyncServiceCall(DynamoDbAsyncClient dynamoDbAsyncClient) { return dynamoDbAsyncClient::scanPaginator; } priv... | @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... |
ScanOperation implements PaginatedTableOperation<T, ScanRequest, ScanResponse>,
PaginatedIndexOperation<T, ScanRequest, ScanResponse> { @Override public ScanRequest generateRequest(TableSchema<T> tableSchema, OperationContext operationContext, DynamoDbEnhancedClientExtension extension) { Map<String, AttributeVa... | @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 dynamoDbEnhancedClientEx... | @Test public void transformResults_multipleItems_returnsCorrectItems() { List<FakeItem> scanResultItems = generateFakeItemList(); List<Map<String, AttributeValue>> scanResultMaps = scanResultItems.stream().map(ScanOperationTest::getAttributeValueMap).collect(toList()); ScanResponse scanResponse = generateFakeScanResult... |
EnableTrailingChecksumInterceptor implements ExecutionInterceptor { @Override public SdkResponse modifyResponse(Context.ModifyResponse context, ExecutionAttributes executionAttributes) { SdkResponse response = context.response(); SdkHttpResponse httpResponse = context.httpResponse(); if (getObjectChecksumEnabledPerResp... | @Test public void modifyResponse_getObjectResponseContainsChecksumHeader_shouldModifyResponse() { long contentLength = 50; GetObjectResponse response = GetObjectResponse.builder().contentLength(contentLength).build(); Context.ModifyResponse modifyResponseContext = modifyResponseContext( GetObjectRequest.builder().build... |
QueryOperation implements PaginatedTableOperation<T, QueryRequest, QueryResponse>,
PaginatedIndexOperation<T, QueryRequest, QueryResponse> { @Override public Function<QueryRequest, SdkIterable<QueryResponse>> serviceCall(DynamoDbClient dynamoDbClient) { return dynamoDbClient::queryPaginator; } private QueryOpe... | @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> res... |
QueryOperation implements PaginatedTableOperation<T, QueryRequest, QueryResponse>,
PaginatedIndexOperation<T, QueryRequest, QueryResponse> { @Override public Function<QueryRequest, SdkPublisher<QueryResponse>> asyncServiceCall(DynamoDbAsyncClient dynamoDbAsyncClient) { return dynamoDbAsyncClient::queryPaginator... | @Test public void getAsyncServiceCall_makesTheRightCallAndReturnsResponse() { QueryRequest queryRequest = QueryRequest.builder().build(); QueryPublisher mockQueryPublisher = mock(QueryPublisher.class); when(mockDynamoDbAsyncClient.queryPaginator(any(QueryRequest.class))).thenReturn(mockQueryPublisher); SdkPublisher<Que... |
QueryOperation implements PaginatedTableOperation<T, QueryRequest, QueryResponse>,
PaginatedIndexOperation<T, QueryRequest, QueryResponse> { @Override public QueryRequest generateRequest(TableSchema<T> tableSchema, OperationContext operationContext, DynamoDbEnhancedClientExtension extension) { Expression queryE... | @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") .exp... |
QueryOperation implements PaginatedTableOperation<T, QueryRequest, QueryResponse>,
PaginatedIndexOperation<T, QueryRequest, QueryResponse> { @Override public Page<T> transformResponse(QueryResponse response, TableSchema<T> tableSchema, OperationContext context, DynamoDbEnhancedClientExtension dynamoDbEnhancedCl... | @Test public void transformResults_multipleItems_returnsCorrectItems() { List<FakeItem> queryResultItems = generateFakeItemList(); List<Map<String, AttributeValue>> queryResultMaps = queryResultItems.stream().map(QueryOperationTest::getAttributeValueMap).collect(toList()); QueryResponse queryResponse = generateFakeQuer... |
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(Bui... | @Test public void table() { DefaultDynamoDbAsyncTable<Object> mappedTable = dynamoDbEnhancedAsyncClient.table("table-name", mockTableSchema); assertThat(mappedTable.dynamoDbClient(), is(mockDynamoDbAsyncClient)); assertThat(mappedTable.mapperExtension(), is(mockDynamoDbEnhancedClientExtension)); assertThat(mappedTable.... |
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... | @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,... | @Test public void keyFrom_secondaryIndex_partitionAndSort() { FakeItemWithIndices item = FakeItemWithIndices.createUniqueFakeItemWithIndices(); DefaultDynamoDbIndex<FakeItemWithIndices> dynamoDbMappedIndex = new DefaultDynamoDbIndex<>(mockDynamoDbClient, mockDynamoDbEnhancedClientExtension, FakeItemWithIndices.getTable... |
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 Extensio... | @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.resolveExte... |
ExtensionResolver { public static List<DynamoDbEnhancedClientExtension> defaultExtensions() { return DEFAULT_EXTENSIONS; } private ExtensionResolver(); static List<DynamoDbEnhancedClientExtension> defaultExtensions(); static DynamoDbEnhancedClientExtension resolveExtensions(List<DynamoDbEnhancedClientExtension> extens... | @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 Bui... | @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(), ... |
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, T... | @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 dynamoDbC... | @Test(expected = IllegalArgumentException.class) public void index_invalidIndex_throwsIllegalArgumentException() { DefaultDynamoDbTable<FakeItemWithIndices> dynamoDbMappedTable = new DefaultDynamoDbTable<>(mockDynamoDbClient, mockDynamoDbEnhancedClientExtension, FakeItemWithIndices.getTableSchema(), TABLE_NAME); dynamo... |
DefaultDynamoDbTable implements DynamoDbTable<T> { @Override public Key keyFrom(T item) { return createKeyFromItem(item, tableSchema, TableMetadata.primaryIndexName()); } DefaultDynamoDbTable(DynamoDbClient dynamoDbClient,
DynamoDbEnhancedClientExtension extension,
Tabl... | @Test public void keyFrom_primaryIndex_partitionAndSort() { FakeItemWithSort item = FakeItemWithSort.createUniqueFakeItemWithSort(); DefaultDynamoDbTable<FakeItemWithSort> dynamoDbMappedIndex = new DefaultDynamoDbTable<>(mockDynamoDbClient, mockDynamoDbEnhancedClientExtension, FakeItemWithSort.getTableSchema(), "test_t... |
DefaultDynamoDbAsyncIndex implements DynamoDbAsyncIndex<T> { @Override public Key keyFrom(T item) { return createKeyFromItem(item, tableSchema, indexName); } DefaultDynamoDbAsyncIndex(DynamoDbAsyncClient dynamoDbClient,
DynamoDbEnhancedClientExtension extension,
... | @Test public void keyFrom_secondaryIndex_partitionAndSort() { FakeItemWithIndices item = FakeItemWithIndices.createUniqueFakeItemWithIndices(); DefaultDynamoDbAsyncIndex<FakeItemWithIndices> dynamoDbMappedIndex = new DefaultDynamoDbAsyncIndex<>(mockDynamoDbAsyncClient, mockDynamoDbEnhancedClientExtension, FakeItemWithI... |
DefaultDynamoDbAsyncTable implements DynamoDbAsyncTable<T> { @Override public DefaultDynamoDbAsyncIndex<T> index(String indexName) { tableSchema.tableMetadata().indexPartitionKey(indexName); return new DefaultDynamoDbAsyncIndex<>(dynamoDbClient, extension, tableSchema, tableName, indexName); } DefaultDynamoDbAsyncTable... | @Test(expected = IllegalArgumentException.class) public void index_invalidIndex_throwsIllegalArgumentException() { DefaultDynamoDbAsyncTable<FakeItemWithIndices> dynamoDbMappedTable = new DefaultDynamoDbAsyncTable<>(mockDynamoDbAsyncClient, mockDynamoDbEnhancedClientExtension, FakeItemWithIndices.getTableSchema(), TABL... |
DefaultDynamoDbAsyncTable implements DynamoDbAsyncTable<T> { @Override public Key keyFrom(T item) { return createKeyFromItem(item, tableSchema, TableMetadata.primaryIndexName()); } DefaultDynamoDbAsyncTable(DynamoDbAsyncClient dynamoDbClient,
DynamoDbEnhancedClientExtension extension,
... | @Test public void keyFrom_primaryIndex_partitionAndSort() { FakeItemWithSort item = FakeItemWithSort.createUniqueFakeItemWithSort(); DefaultDynamoDbAsyncTable<FakeItemWithSort> dynamoDbMappedIndex = new DefaultDynamoDbAsyncTable<>(mockDynamoDbAsyncClient, mockDynamoDbEnhancedClientExtension, FakeItemWithSort.getTableSc... |
CreateBucketInterceptor implements ExecutionInterceptor { @Override public SdkRequest modifyRequest(Context.ModifyRequest context, ExecutionAttributes executionAttributes) { SdkRequest sdkRequest = context.request(); if (sdkRequest instanceof CreateBucketRequest) { CreateBucketRequest request = (CreateBucketRequest) sd... | @Test public void modifyRequest_DoesNotOverrideExistingLocationConstraint() { CreateBucketRequest request = CreateBucketRequest.builder() .bucket("test-bucket") .createBucketConfiguration(CreateBucketConfiguration.builder() .locationConstraint( "us-west-2") .build()) .build(); Context.ModifyRequest context = () -> requ... |
GetObjectPresignRequest extends PresignRequest implements ToCopyableBuilder<GetObjectPresignRequest.Builder, GetObjectPresignRequest> { public static Builder builder() { return new DefaultBuilder(); } private GetObjectPresignRequest(DefaultBuilder builder); static Builder builder(); GetObjectRequest getObjectRequest()... | @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 Converter... | @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(ConverterProviderR... |
ConverterProviderResolver { public static AttributeConverterProvider defaultConverterProvider() { return DEFAULT_ATTRIBUTE_CONVERTER; } private ConverterProviderResolver(); static AttributeConverterProvider defaultConverterProvider(); static AttributeConverterProvider resolveProviders(List<AttributeConverterProvider> ... | @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); AttributeV... | @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_VA... |
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 = t... | @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) .... |
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,
... | @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); expre... | @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(resu... |
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 =... | @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<>(); valu... |
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 Stri... | @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 Stri... | @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 ... | @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.capitali... |
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()]; in... | @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 { 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); s... | @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 CharS... | @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 == Intege... | @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.findFirst... |
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(); ... | @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 ... |
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, SHO... |
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... |
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 Cons... | @Test public void checkedExceptionsAreConvertedToRuntimeExceptions() { assertThatExceptionOfType(RuntimeException.class) .isThrownBy(() -> invokeSafely(this::methodThatThrows)) .withCauseInstanceOf(Exception.class); }
@Test public void ioExceptionsAreConvertedToUncheckedIoExceptions() { assertThatExceptionOfType(Unchec... |
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... | @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... |
SyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<RequestBody> modifyHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { if (shouldRecordChecksum(context.request(), SYNC, executionAttributes, context.httpRequest()) && context.requestBody(... | @Test public void modifyHttpContent_putObjectRequestChecksumEnabled_shouldWrapChecksumRequestBody() { ExecutionAttributes executionAttributes = getExecutionAttributes(); Context.ModifyHttpRequest modifyHttpRequest = InterceptorTestUtils.modifyHttpRequestContext(PutObjectRequest.builder().build()); Optional<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 run... | @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 exceptions... |
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(); @Ov... | @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")... |
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); stati... | @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.isTru... |
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);... | @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.no... |
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 Valida... | @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("Expectin... |
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)); } retur... | @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() { fin... |
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 isT... | @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... |
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 ... | @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 testInc... |
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; } privat... | @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.exclusiveBet... |
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, f... | @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... |
SyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<InputStream> modifyHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse()) && context.responseBody()... | @Test public void modifyHttpResponseContent_getObjectRequest_checksumEnabled_shouldWrapChecksumValidatingPublisher() { SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader(); Context.ModifyHttpResponse modifyHttpResponse = InterceptorTestUtils.modifyHttpResponse(GetObjectRequest.builder().build(), sdk... |
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 Vali... | @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 ... |
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)... | @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", ... |
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 obje... | @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 getOrD... |
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, f... | @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 mutuallyExclus... |
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, fin... | @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_zer... |
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... | @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... | @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 invokeCanReturn... |
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, ... | @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 responseChecksum... | @Test public void afterUnmarshalling_putObjectRequest_shouldValidateChecksum() { SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader(); PutObjectResponse response = PutObjectResponse.builder() .eTag(VALID_CHECKSUM) .build(); PutObjectRequest putObjectRequest = PutObjectRequest.builder() .build(); Sdk... |
GetObjectPresignRequest extends PresignRequest implements ToCopyableBuilder<GetObjectPresignRequest.Builder, GetObjectPresignRequest> { @Override public Builder toBuilder() { return new DefaultBuilder(this); } private GetObjectPresignRequest(DefaultBuilder builder); static Builder builder(); GetObjectRequest getObject... | @Test public void toBuilder() { GetObjectPresignRequest getObjectPresignRequest = GetObjectPresignRequest.builder() .getObjectRequest(GET_OBJECT_REQUEST) .signatureDuration(Duration.ofSeconds(123L)) .build(); GetObjectPresignRequest otherGetObjectPresignRequest = getObjectPresignRequest.toBuilder().build(); assertThat(... |
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,... | @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 IllegalArgumentEx... | @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")).isInstance... |
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... | @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 (T... |
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, in... | @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(mockSubs... |
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 insta... | @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 a... |
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); st... | @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 parsedInst... |
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... | @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_IS... | @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 testIssu... |
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 f... | @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()) <= oneDayMil... |
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));... | @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(Illegal... |
AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { boolean shouldRecordChecksum = shouldRecordChecksum(context.request(), ASYNC, executionAttributes, context... | @Test public void modifyAsyncHttpContent_putObjectRequestChecksumEnabled_shouldWrapChecksumRequestBody() { ExecutionAttributes executionAttributes = getExecutionAttributes(); Context.ModifyHttpRequest modifyHttpRequest = InterceptorTestUtils.modifyHttpRequestContext(PutObjectRequest.builder().build()); Optional<AsyncRe... |
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 cl... | @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 -... |
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 closeIfClos... | @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 IOExcepti... |
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>>... | @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 p... |
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); @... | @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() { assertT... |
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); sta... | @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[] {-... |
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... | @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... |
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.newFixedT... |
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... | @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);... | @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() { assert... |
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> list... | @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 publ... |
AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse()) && contex... | @Test public void modifyAsyncHttpResponseContent_getObjectRequest_checksumEnabled_shouldWrapChecksumValidatingPublisher() { SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader(); Context.ModifyHttpResponse modifyHttpResponse = InterceptorTestUtils.modifyHttpResponse(GetObjectRequest.builder().build()... |
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,... | @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 Daemo... | @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 ThreadFactor... |
MetricCollectionAggregator { public List<PutMetricDataRequest> getRequests() { List<PutMetricDataRequest> requests = new ArrayList<>(); List<MetricDatum> requestMetricDatums = new ArrayList<>(); ValuesInRequestCounter valuesInRequestCounter = new ValuesInRequestCounter(); Map<Instant, Collection<MetricAggregator>> metr... | @Test public void maximumRequestsIsHonored() { List<PutMetricDataRequest> requests; requests = aggregatorWithUniqueMetricsAdded(MetricCollectionAggregator.MAX_METRIC_DATA_PER_REQUEST).getRequests(); assertThat(requests).hasOnlyOneElementSatisfying(request -> { assertThat(request.metricData()).hasSize(MetricCollectionAg... |
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(() -> "M... | @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<Lis... |
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 w... | @Test public void uploadSuccessIsPropagated() { CompletableFuture<Void> uploadFuture = uploader.upload(Arrays.asList(PutMetricDataRequest.builder().build(), PutMetricDataRequest.builder().build())); assertThat(putMetricDataResponseFutures).hasSize(2); assertThat(uploadFuture).isNotCompleted(); putMetricDataResponseFutu... |
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 dro... | @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())); } ... |
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 crea... | @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.s... |
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)... | @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.cre... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.