index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/Md5UtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.Test; import software.amazon.awssdk.utils.internal.Base16; public class Md5UtilsTest { @Test public void testBytes() { byte[] md5 = Md5Utils.computeMD5Hash("Testing MD5".getBytes(StandardCharsets.UTF_8)); assertEquals("0b4f503b8eb7714ce12402406895cf68", StringUtils.lowerCase(Base16.encodeAsString(md5))); String b64 = Md5Utils.md5AsBase64("Testing MD5".getBytes(StandardCharsets.UTF_8)); assertEquals("C09QO463cUzhJAJAaJXPaA==", b64); } @Test public void testStream() throws IOException { byte[] md5 = Md5Utils.computeMD5Hash(new ByteArrayInputStream("Testing MD5".getBytes(StandardCharsets.UTF_8))); assertEquals("0b4f503b8eb7714ce12402406895cf68", StringUtils.lowerCase(Base16.encodeAsString(md5))); String b64 = Md5Utils.md5AsBase64(new ByteArrayInputStream("Testing MD5".getBytes(StandardCharsets.UTF_8))); assertEquals("C09QO463cUzhJAJAaJXPaA==", b64); } @Test public void testFile() throws Exception { File f = File.createTempFile("Md5UtilsTest-", "txt"); f.deleteOnExit(); FileUtils.writeStringToFile(f, "Testing MD5"); byte[] md5 = Md5Utils.computeMD5Hash(f); assertEquals("0b4f503b8eb7714ce12402406895cf68", StringUtils.lowerCase(Base16.encodeAsString(md5))); String b64 = Md5Utils.md5AsBase64(f); assertEquals("C09QO463cUzhJAJAaJXPaA==", b64); } }
3,200
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/IoUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.in; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Random; import org.junit.jupiter.api.Test; public class IoUtilsTest { private final Random random = new Random(); @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); } @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()); } @Test public void applyMaxReadLimit_shouldHonor() throws IOException { int length = 1 << 18; InputStream inputStream = randomInputStream(length); InputStream bufferedInputStream = new BufferedInputStream(inputStream); IoUtils.markStreamWithMaxReadLimit(bufferedInputStream, length + 1); IoUtils.drainInputStream(bufferedInputStream); assertThat(bufferedInputStream.available()).isEqualTo(0); bufferedInputStream.reset(); assertThat(bufferedInputStream.available()).isEqualTo(length); } private InputStream randomInputStream() { byte[] data = new byte[100]; random.nextBytes(data); return new ByteArrayInputStream(data); } private InputStream randomInputStream(int length) { byte[] data = new byte[length]; random.nextBytes(data); return new ByteArrayInputStream(data); } }
3,201
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/Base16CodecTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.security.MessageDigest; import java.util.Arrays; import java.util.UUID; import org.junit.jupiter.api.Test; import software.amazon.awssdk.utils.internal.Base16; import software.amazon.awssdk.utils.internal.Base16Lower; /** * @author hchar */ public class Base16CodecTest { @Test public void testVectorsPerRfc4648() throws Exception { String[] testVectors = {"", "f", "fo", "foo", "foob", "fooba", "foobar"}; String[] expected = {"", "66", "666F", "666F6F", "666F6F62", "666F6F6261", "666F6F626172"}; for (int i = 0; i < testVectors.length; i++) { String data = testVectors[i]; byte[] source = data.getBytes("UTF-8"); String b16encoded = Base16.encodeAsString(data.getBytes("UTF-8")); assertEquals(expected[i], b16encoded); byte[] b16 = b16encoded.getBytes("UTF-8"); byte[] decoded = Base16.decode(b16); assertTrue(Arrays.equals(source, decoded)); decoded = Base16Lower.decode(b16); assertTrue(Arrays.equals(source, decoded)); } } @Test public void testCodecConsistency() throws Exception { byte[] decoded = null; for (int h = 0; h < 1000; h++) { byte[] digest = MessageDigest.getInstance("SHA-1").digest( UUID.randomUUID().toString().getBytes("UTF-8") ); String b16Encoded = Base16.encodeAsString(digest); { decoded = Base16.decode(b16Encoded); assertTrue(Arrays.equals(decoded, digest)); decoded = Base16Lower.decode(b16Encoded); assertTrue(Arrays.equals(decoded, digest)); } { // test decoding case insensitivity decoded = Base16.decode(b16Encoded.toLowerCase()); assertTrue(Arrays.equals(decoded, digest)); decoded = Base16Lower.decode(b16Encoded.toLowerCase()); assertTrue(Arrays.equals(decoded, digest)); } } } }
3,202
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/SystemSettingTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.assertj.core.api.Java6Assertions.assertThat; import org.junit.jupiter.api.Test; public class SystemSettingTest { @Test public void getNonDefaultStringValue_doesNotReturnDefaultValue() { TestSystemSetting setting = new TestSystemSetting("prop", "env", "default"); assertThat(setting.getNonDefaultStringValue().isPresent()).isFalse(); } private static class TestSystemSetting implements SystemSetting { private final String property; private final String environmentVariable; private final String defaultValue; public TestSystemSetting(String property, String environmentVariable, String defaultValue) { this.property = property; this.environmentVariable = environmentVariable; this.defaultValue = defaultValue; } @Override public String property() { return property; } @Override public String environmentVariable() { return environmentVariable; } @Override public String defaultValue() { return defaultValue; } } }
3,203
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/HostnameValidatorTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class HostnameValidatorTest { private static final String LONG_STRING_64 = "1234567890123456789012345678901234567890123456789012345678901234"; @Rule public ExpectedException exception = ExpectedException.none(); @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("empty"); HostnameValidator.validateHostnameCompliant("", "id", "test"); } @Test public void blankHostComponent_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("id"); exception.expectMessage("blank"); HostnameValidator.validateHostnameCompliant(" ", "id", "test"); } @Test public void hostComponentWithSlash_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("id"); exception.expectMessage("\"[A-Za-z0-9\\-]+\""); 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"); } }
3,204
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/SdkHttpUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.entry; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import software.amazon.awssdk.utils.http.SdkHttpUtils; public class SdkHttpUtilsTest { @Test public void urlValuesEncodeCorrectly() { String nonEncodedCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"; String encodedCharactersInput = "\t\n\r !\"#$%&'()*+,/:;<=>?@[\\]^`{|}"; String encodedCharactersOutput = "%09%0A%0D%20%21%22%23%24%25%26%27%28%29%2A%2B%2C%2F%3A%3B%3C%3D%3E%3F%40%5B%5C%5D%5E%60%7B%7C%7D"; assertThat(SdkHttpUtils.urlEncode(null)).isEqualTo(null); assertThat(SdkHttpUtils.urlEncode("")).isEqualTo(""); assertThat(SdkHttpUtils.urlEncode(nonEncodedCharacters)).isEqualTo(nonEncodedCharacters); assertThat(SdkHttpUtils.urlEncode(encodedCharactersInput)).isEqualTo(encodedCharactersOutput); } @Test public void encodeUrlIgnoreSlashesEncodesCorrectly() { String nonEncodedCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~/"; String encodedCharactersInput = "\t\n\r !\"#$%&'()*+,:;<=>?@[\\]^`{|}"; String encodedCharactersOutput = "%09%0A%0D%20%21%22%23%24%25%26%27%28%29%2A%2B%2C%3A%3B%3C%3D%3E%3F%40%5B%5C%5D%5E%60%7B%7C%7D"; assertThat(SdkHttpUtils.urlEncodeIgnoreSlashes(null)).isEqualTo(null); assertThat(SdkHttpUtils.urlEncodeIgnoreSlashes("")).isEqualTo(""); assertThat(SdkHttpUtils.urlEncodeIgnoreSlashes(nonEncodedCharacters)).isEqualTo(nonEncodedCharacters); assertThat(SdkHttpUtils.urlEncodeIgnoreSlashes(encodedCharactersInput)).isEqualTo(encodedCharactersOutput); } @Test public void formDataValuesEncodeCorrectly() { String nonEncodedCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.*"; String encodedCharactersInput = "\t\n\r !\"#$%&'()+,/:;<=>?@[\\]^`{|}~"; String encodedCharactersOutput = "%09%0A%0D+%21%22%23%24%25%26%27%28%29%2B%2C%2F%3A%3B%3C%3D%3E%3F%40%5B%5C%5D%5E%60%7B%7C%7D%7E"; assertThat(SdkHttpUtils.formDataEncode(null)).isEqualTo(null); assertThat(SdkHttpUtils.formDataEncode("")).isEqualTo(""); assertThat(SdkHttpUtils.formDataEncode(nonEncodedCharacters)).isEqualTo(nonEncodedCharacters); assertThat(SdkHttpUtils.formDataEncode(encodedCharactersInput)).isEqualTo(encodedCharactersOutput); } @Test public void encodeFlattenBehavesCorrectly() { HashMap<String, List<String>> values = new LinkedHashMap<>(); values.put("SingleValue", singletonList("Value")); values.put("SpaceValue", singletonList(" ")); values.put("EncodedValue", singletonList("/")); values.put("NoValue", null); values.put("NullValue", singletonList(null)); values.put("BlankValue", singletonList("")); values.put("MultiValue", asList("Value1", "Value2")); String expectedQueryString = "SingleValue=Value&SpaceValue=%20&EncodedValue=%2F&NullValue&BlankValue=&MultiValue=Value1&MultiValue=Value2"; String expectedFormDataString = "SingleValue=Value&SpaceValue=+&EncodedValue=%2F&NullValue&BlankValue=&MultiValue=Value1&MultiValue=Value2"; assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> SdkHttpUtils.encodeAndFlattenQueryParameters(null)); assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> SdkHttpUtils.encodeAndFlattenFormData(null)); assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> SdkHttpUtils.encodeFormData(null)); assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> SdkHttpUtils.encodeQueryParameters(null)); assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> SdkHttpUtils.flattenQueryParameters(null)); assertThat(SdkHttpUtils.encodeAndFlattenQueryParameters(values)).hasValue(expectedQueryString); assertThat(SdkHttpUtils.encodeAndFlattenFormData(values)).hasValue(expectedFormDataString); assertThat(SdkHttpUtils.encodeAndFlattenQueryParameters(Collections.emptyMap())).isNotPresent(); assertThat(SdkHttpUtils.encodeAndFlattenQueryParameters(Collections.emptyMap())).isNotPresent(); } @Test public void urisAppendCorrectly() { assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> SdkHttpUtils.appendUri(null, "")); assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> SdkHttpUtils.appendUri(null, null)); assertThat(SdkHttpUtils.appendUri("", null)).isEqualTo(""); assertThat(SdkHttpUtils.appendUri("", "")).isEqualTo(""); assertThat(SdkHttpUtils.appendUri("", "bar")).isEqualTo("/bar"); assertThat(SdkHttpUtils.appendUri("", "/bar")).isEqualTo("/bar"); assertThat(SdkHttpUtils.appendUri("", "bar/")).isEqualTo("/bar/"); assertThat(SdkHttpUtils.appendUri("", "/bar/")).isEqualTo("/bar/"); assertThat(SdkHttpUtils.appendUri("foo.com", null)).isEqualTo("foo.com"); assertThat(SdkHttpUtils.appendUri("foo.com", "")).isEqualTo("foo.com"); assertThat(SdkHttpUtils.appendUri("foo.com/", "")).isEqualTo("foo.com/"); assertThat(SdkHttpUtils.appendUri("foo.com", "bar")).isEqualTo("foo.com/bar"); assertThat(SdkHttpUtils.appendUri("foo.com/", "bar")).isEqualTo("foo.com/bar"); assertThat(SdkHttpUtils.appendUri("foo.com", "/bar")).isEqualTo("foo.com/bar"); assertThat(SdkHttpUtils.appendUri("foo.com/", "/bar")).isEqualTo("foo.com/bar"); assertThat(SdkHttpUtils.appendUri("foo.com/", "/bar/")).isEqualTo("foo.com/bar/"); assertThat(SdkHttpUtils.appendUri("foo.com/", "//bar/")).isEqualTo("foo.com//bar/"); } @Test public void standardPortsAreCorrect() { assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> SdkHttpUtils.standardPort(null)); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> SdkHttpUtils.standardPort("foo")); assertThat(SdkHttpUtils.standardPort("http")).isEqualTo(80); assertThat(SdkHttpUtils.standardPort("https")).isEqualTo(443); assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> SdkHttpUtils.isUsingStandardPort(null, 80)); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> SdkHttpUtils.isUsingStandardPort("foo", 80)); assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> SdkHttpUtils.isUsingStandardPort("foo", null)); assertThat(SdkHttpUtils.isUsingStandardPort("http", null)).isTrue(); assertThat(SdkHttpUtils.isUsingStandardPort("https", null)).isTrue(); assertThat(SdkHttpUtils.isUsingStandardPort("http", -1)).isTrue(); assertThat(SdkHttpUtils.isUsingStandardPort("https", -1)).isTrue(); assertThat(SdkHttpUtils.isUsingStandardPort("http", 80)).isTrue(); assertThat(SdkHttpUtils.isUsingStandardPort("http", 8080)).isFalse(); assertThat(SdkHttpUtils.isUsingStandardPort("https", 443)).isTrue(); assertThat(SdkHttpUtils.isUsingStandardPort("https", 8443)).isFalse(); } @Test public void headerRetrievalWorksCorrectly() { Map<String, List<String>> headers = new HashMap<>(); headers.put("FOO", asList("bar", "baz")); headers.put("foo", singletonList(null)); headers.put("other", singletonList("foo")); headers.put("Foo", singletonList("baz2")); assertThat(SdkHttpUtils.allMatchingHeaders(headers, "foo")).containsExactly("bar", "baz", null, "baz2"); assertThat(SdkHttpUtils.firstMatchingHeader(headers, "foo")).hasValue("bar"); assertThat(SdkHttpUtils.firstMatchingHeader(headers, "other")).hasValue("foo"); assertThat(SdkHttpUtils.firstMatchingHeader(headers, null)).isNotPresent(); assertThat(SdkHttpUtils.firstMatchingHeader(headers, "nothing")).isNotPresent(); } @Test public void headersFromCollectionWorksCorrectly() { Map<String, List<String>> headers = new HashMap<>(); headers.put("FOO", asList("bar", "baz")); headers.put("foo", singletonList(null)); headers.put("other", singletonList("foo")); headers.put("Foo", singletonList("baz2")); assertThat(SdkHttpUtils.allMatchingHeadersFromCollection(headers, asList("nothing"))).isEmpty(); assertThat(SdkHttpUtils.allMatchingHeadersFromCollection(headers, asList("foo"))) .containsExactlyInAnyOrder("bar", "baz", null, "baz2"); assertThat(SdkHttpUtils.allMatchingHeadersFromCollection(headers, asList("nothing", "foo"))) .containsExactlyInAnyOrder("bar", "baz", null, "baz2"); assertThat(SdkHttpUtils.allMatchingHeadersFromCollection(headers, asList("foo", "nothing"))) .containsExactlyInAnyOrder("bar", "baz", null, "baz2"); assertThat(SdkHttpUtils.allMatchingHeadersFromCollection(headers, asList("foo", "other"))) .containsExactlyInAnyOrder("bar", "baz", null, "foo", "baz2"); assertThat(SdkHttpUtils.firstMatchingHeaderFromCollection(headers, asList("nothing"))).isEmpty(); assertThat(SdkHttpUtils.firstMatchingHeaderFromCollection(headers, asList("foo"))).hasValue("bar"); assertThat(SdkHttpUtils.firstMatchingHeaderFromCollection(headers, asList("nothing", "foo"))).hasValue("bar"); assertThat(SdkHttpUtils.firstMatchingHeaderFromCollection(headers, asList("foo", "nothing"))).hasValue("bar"); assertThat(SdkHttpUtils.firstMatchingHeaderFromCollection(headers, asList("foo", "other"))).hasValue("foo"); } @Test public void isSingleHeader() { assertThat(SdkHttpUtils.isSingleHeader("age")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("authorization")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("content-length")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("content-location")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("content-md5")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("content-range")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("content-type")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("date")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("etag")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("expires")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("from")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("host")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("if-modified-since")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("if-range")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("if-unmodified-since")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("last-modified")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("location")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("max-forwards")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("proxy-authorization")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("range")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("referer")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("retry-after")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("server")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("user-agent")).isTrue(); assertThat(SdkHttpUtils.isSingleHeader("custom")).isFalse(); } @Test public void uriParams() throws URISyntaxException { URI uri = URI.create("https://github.com/aws/aws-sdk-java-v2/issues/2034?reqParam=1234&oParam=3456&reqParam=5678&noval" + "&decoded%26Part=equals%3Dval"); Map<String, List<String>> uriParams = SdkHttpUtils.uriParams(uri); assertThat(uriParams).contains(entry("reqParam", Arrays.asList("1234", "5678")), entry("oParam", Collections.singletonList("3456")), entry("noval", Arrays.asList((String)null)), entry("decoded&Part", Arrays.asList("equals=val"))); } }
3,205
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/BinaryUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.ByteBuffer; import java.util.Arrays; import org.junit.jupiter.api.Test; import software.amazon.awssdk.utils.internal.Base16Lower; public class BinaryUtilsTest { @Test public void testHex() { { String hex = BinaryUtils.toHex(new byte[] {0}); String hex2 = Base16Lower.encodeAsString(new byte[] {0}); assertEquals(hex, hex2); } { String hex = BinaryUtils.toHex(new byte[] {-1}); String hex2 = Base16Lower.encodeAsString(new byte[] {-1}); assertEquals(hex, hex2); } } @Test public void testCopyBytes_Nulls() { assertNull(BinaryUtils.copyAllBytesFrom(null)); assertNull(BinaryUtils.copyBytesFrom(null)); } @Test public void testCopyBytesFromByteBuffer() { byte[] ba = {1, 2, 3, 4, 5}; // capacity: 100 final ByteBuffer b = ByteBuffer.allocate(100); b.put(ba); // limit: 5 b.limit(5); assertTrue(b.capacity() > b.limit()); b.rewind(); assertTrue(b.position() == 0); b.get(); assertTrue(b.position() == 1); // backing array byte[] array = b.array(); assertTrue(array.length == 100); // actual data length byte[] allData = BinaryUtils.copyAllBytesFrom(b); assertTrue(allData.length == 5); // copy, not reference assertFalse(ba == allData); // partial data length byte[] partialData = BinaryUtils.copyBytesFrom(b); assertTrue(partialData.length == 4); } @Test public void testCopyBytesFrom_DirectByteBuffer() { byte[] ba = {1, 2, 3, 4, 5}; // capacity: 100 final ByteBuffer b = ByteBuffer.allocateDirect(100); b.put(ba); // limit: 5 b.limit(5); assertTrue(b.capacity() > b.limit()); b.rewind(); assertTrue(b.position() == 0); b.get(); assertTrue(b.position() == 1); // backing array assertFalse(b.hasArray()); assertTrue(b.capacity() == 100); // actual data length byte[] allData = BinaryUtils.copyAllBytesFrom(b); assertTrue(allData.length == 5); // copy, not reference assertFalse(ba == allData); // partial data length byte[] partialData = BinaryUtils.copyBytesFrom(b); assertTrue(partialData.length == 4); } @Test public void testCopyBytesFromByteBuffer_Idempotent() { byte[] ba = {1, 2, 3, 4, 5}; final ByteBuffer b = ByteBuffer.wrap(ba); b.limit(4); assertTrue(b.limit() == 4); b.rewind(); assertTrue(b.position() == 0); b.get(); assertTrue(b.position() == 1); // copy all bytes should be idempotent byte[] allData1 = BinaryUtils.copyAllBytesFrom(b); assertTrue(b.position() == 1); byte[] allData2 = BinaryUtils.copyAllBytesFrom(b); assertTrue(b.position() == 1); assertFalse(allData1 == allData2); assertTrue(allData1.length == 4); assertTrue(Arrays.equals(new byte[] {1, 2, 3, 4}, allData1)); // copy partial bytes should be idempotent byte[] partial1 = BinaryUtils.copyBytesFrom(b); assertTrue(b.position() == 1); byte[] partial2 = BinaryUtils.copyBytesFrom(b); assertTrue(b.position() == 1); assertFalse(partial1 == partial2); assertTrue(partial1.length == 3); assertTrue(Arrays.equals(new byte[] {2, 3, 4}, partial1)); } @Test public void testCopyBytesFrom_DirectByteBuffer_Idempotent() { byte[] ba = {1, 2, 3, 4, 5}; final ByteBuffer b = ByteBuffer.allocateDirect(ba.length); b.put(ba).rewind(); b.limit(4); assertTrue(b.limit() == 4); b.rewind(); assertTrue(b.position() == 0); b.get(); assertTrue(b.position() == 1); // copy all bytes should be idempotent byte[] allData1 = BinaryUtils.copyAllBytesFrom(b); assertTrue(b.position() == 1); byte[] allData2 = BinaryUtils.copyAllBytesFrom(b); assertTrue(b.position() == 1); assertFalse(allData1 == allData2); assertTrue(allData1.length == 4); assertTrue(Arrays.equals(new byte[] {1, 2, 3, 4}, allData1)); // copy partial bytes should be idempotent byte[] partial1 = BinaryUtils.copyBytesFrom(b); assertTrue(b.position() == 1); byte[] partial2 = BinaryUtils.copyBytesFrom(b); assertTrue(b.position() == 1); assertFalse(partial1 == partial2); assertTrue(partial1.length == 3); assertTrue(Arrays.equals(new byte[] {2, 3, 4}, partial1)); } @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); } @Test public void testImmutableCopyOfByteBuffer() { ByteBuffer sourceBuffer = ByteBuffer.allocate(4); byte[] originalBytesInSource = {1, 2, 3, 4}; sourceBuffer.put(originalBytesInSource); sourceBuffer.flip(); ByteBuffer immutableCopy = BinaryUtils.immutableCopyOf(sourceBuffer); byte[] bytesInSourceAfterCopy = {-1, -2, -3, -4}; sourceBuffer.put(bytesInSourceAfterCopy); sourceBuffer.flip(); assertTrue(immutableCopy.isReadOnly()); byte[] fromImmutableCopy = new byte[originalBytesInSource.length]; immutableCopy.get(fromImmutableCopy); assertArrayEquals(originalBytesInSource, fromImmutableCopy); assertEquals(0, sourceBuffer.position()); byte[] fromSource = new byte[bytesInSourceAfterCopy.length]; sourceBuffer.get(fromSource); assertArrayEquals(bytesInSourceAfterCopy, fromSource); } @Test public void immutableCopyOf_retainsOriginalLimit() { ByteBuffer sourceBuffer = ByteBuffer.allocate(10); byte[] bytes = {1, 2, 3, 4}; sourceBuffer.put(bytes); sourceBuffer.rewind(); sourceBuffer.limit(bytes.length); ByteBuffer copy = BinaryUtils.immutableCopyOf(sourceBuffer); assertThat(copy.limit()).isEqualTo(sourceBuffer.limit()); } @Test public void testImmutableCopyOfByteBuffer_nullBuffer() { assertNull(BinaryUtils.immutableCopyOf(null)); } @Test public void testImmutableCopyOfByteBuffer_partiallyReadBuffer() { ByteBuffer sourceBuffer = ByteBuffer.allocate(4); byte[] bytes = {1, 2, 3, 4}; sourceBuffer.put(bytes); sourceBuffer.position(2); ByteBuffer immutableCopy = BinaryUtils.immutableCopyOf(sourceBuffer); assertEquals(sourceBuffer.position(), immutableCopy.position()); immutableCopy.rewind(); byte[] fromImmutableCopy = new byte[bytes.length]; immutableCopy.get(fromImmutableCopy); assertArrayEquals(bytes, fromImmutableCopy); } @Test public void testImmutableCopyOfRemainingByteBuffer() { ByteBuffer sourceBuffer = ByteBuffer.allocate(4); byte[] originalBytesInSource = {1, 2, 3, 4}; sourceBuffer.put(originalBytesInSource); sourceBuffer.flip(); ByteBuffer immutableCopy = BinaryUtils.immutableCopyOfRemaining(sourceBuffer); byte[] bytesInSourceAfterCopy = {-1, -2, -3, -4}; sourceBuffer.put(bytesInSourceAfterCopy); sourceBuffer.flip(); assertTrue(immutableCopy.isReadOnly()); byte[] fromImmutableCopy = new byte[originalBytesInSource.length]; immutableCopy.get(fromImmutableCopy); assertArrayEquals(originalBytesInSource, fromImmutableCopy); assertEquals(0, sourceBuffer.position()); byte[] fromSource = new byte[bytesInSourceAfterCopy.length]; sourceBuffer.get(fromSource); assertArrayEquals(bytesInSourceAfterCopy, fromSource); } @Test public void testImmutableCopyOfByteBufferRemaining_nullBuffer() { assertNull(BinaryUtils.immutableCopyOfRemaining(null)); } @Test public void testImmutableCopyOfByteBufferRemaining_partiallyReadBuffer() { ByteBuffer sourceBuffer = ByteBuffer.allocate(4); byte[] bytes = {1, 2, 3, 4}; sourceBuffer.put(bytes); sourceBuffer.position(2); ByteBuffer immutableCopy = BinaryUtils.immutableCopyOfRemaining(sourceBuffer); assertEquals(2, immutableCopy.capacity()); assertEquals(2, immutableCopy.remaining()); assertEquals(0, immutableCopy.position()); assertEquals((byte) 3, immutableCopy.get()); assertEquals((byte) 4, immutableCopy.get()); } @Test public void testToNonDirectBuffer() { ByteBuffer bb = ByteBuffer.allocateDirect(4); byte[] expected = {1, 2, 3, 4}; bb.put(expected); bb.flip(); ByteBuffer nonDirectBuffer = BinaryUtils.toNonDirectBuffer(bb); assertFalse(nonDirectBuffer.isDirect()); byte[] bytes = new byte[expected.length]; nonDirectBuffer.get(bytes); assertArrayEquals(expected, bytes); } @Test public void testToNonDirectBuffer_nullBuffer() { assertNull(BinaryUtils.toNonDirectBuffer(null)); } @Test public void testToNonDirectBuffer_partiallyReadBuffer() { ByteBuffer sourceBuffer = ByteBuffer.allocateDirect(4); byte[] bytes = {1, 2, 3, 4}; sourceBuffer.put(bytes); sourceBuffer.position(2); ByteBuffer nonDirectBuffer = BinaryUtils.toNonDirectBuffer(sourceBuffer); assertEquals(sourceBuffer.position(), nonDirectBuffer.position()); nonDirectBuffer.rewind(); byte[] fromNonDirectBuffer = new byte[bytes.length]; nonDirectBuffer.get(fromNonDirectBuffer); assertArrayEquals(bytes, fromNonDirectBuffer); } @Test public void testToNonDirectBuffer_nonDirectBuffer() { ByteBuffer nonDirectBuffer = ByteBuffer.allocate(0); assertThrows(IllegalArgumentException.class, () -> BinaryUtils.toNonDirectBuffer(nonDirectBuffer)); } }
3,206
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/ImmutableMapTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.util.Collections; import java.util.Map; import org.junit.jupiter.api.Test; /** * Unit tests for the ImmutableMapTest class. */ public class ImmutableMapTest { @Test public void testMapBuilder() { Map<Integer, String> builtMap = new ImmutableMap.Builder<Integer, String>() .put(1, "one") .put(2, "two") .put(3, "three") .build(); assertEquals(3, builtMap.size()); assertEquals("one", builtMap.get(1)); assertEquals("two", builtMap.get(2)); assertEquals("three", builtMap.get(3)); } @Test public void testOfBuilder() { Map<Integer, String> builtMap = ImmutableMap.of(1, "one"); assertEquals(1, builtMap.size()); assertEquals("one", builtMap.get(1)); builtMap = ImmutableMap.of(1, "one", 2, "two"); assertEquals(2, builtMap.size()); assertEquals("one", builtMap.get(1)); assertEquals("two", builtMap.get(2)); builtMap = ImmutableMap.of(1, "one", 2, "two", 3, "three"); assertEquals(3, builtMap.size()); assertEquals("one", builtMap.get(1)); assertEquals("two", builtMap.get(2)); assertEquals("three", builtMap.get(3)); builtMap = ImmutableMap.of(1, "one", 2, "two", 3, "three", 4, "four"); assertEquals(4, builtMap.size()); assertEquals("one", builtMap.get(1)); assertEquals("two", builtMap.get(2)); assertEquals("three", builtMap.get(3)); assertEquals("four", builtMap.get(4)); builtMap = ImmutableMap.of(1, "one", 2, "two", 3, "three", 4, "four", 5, "five"); assertEquals(5, builtMap.size()); assertEquals("one", builtMap.get(1)); assertEquals("two", builtMap.get(2)); assertEquals("three", builtMap.get(3)); assertEquals("four", builtMap.get(4)); assertEquals("five", builtMap.get(5)); } @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) { // Ignored or expected. } catch (Exception e) { fail("IllegalArgumentException expected."); } } @Test public void testMapOperations() { Map<Integer, String> builtMap = new ImmutableMap.Builder<Integer, String>() .put(1, "one") .put(2, "two") .put(3, "three") .build(); assertTrue(builtMap.containsKey(1)); assertTrue(builtMap.containsValue("one")); assertTrue(builtMap.values().contains("one")); assertEquals("one", builtMap.get(1)); assertEquals(3, builtMap.entrySet().size()); assertEquals(3, builtMap.values().size()); assertEquals(3, builtMap.size()); /** Unsupported methods **/ try { builtMap.clear(); fail("UnsupportedOperationException expected."); } catch (UnsupportedOperationException iae) { // Ignored or expected. } catch (Exception e) { fail("UnsupportedOperationException expected."); } try { builtMap.put(4, "four"); fail("UnsupportedOperationException expected."); } catch (UnsupportedOperationException iae) { // Ignored or expected. } catch (Exception e) { fail("UnsupportedOperationException expected."); } try { builtMap.putAll(Collections.singletonMap(4, "four")); fail("UnsupportedOperationException expected."); } catch (UnsupportedOperationException iae) { // Ignored or expected. } catch (Exception e) { fail("UnsupportedOperationException expected."); } try { builtMap.remove(1); fail("UnsupportedOperationException expected."); } catch (UnsupportedOperationException iae) { // Ignored or expected. } catch (Exception e) { fail("UnsupportedOperationException expected."); } } }
3,207
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/FunctionalUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import static software.amazon.awssdk.utils.FunctionalUtils.safeConsumer; import static software.amazon.awssdk.utils.FunctionalUtils.safeFunction; import java.io.IOException; import java.io.UncheckedIOException; import java.util.Optional; import java.util.stream.Stream; import org.junit.jupiter.api.Test; public class FunctionalUtilsTest { private static final boolean DONT_THROW_EXCEPTION = false; private static final boolean THROW_EXCEPTION = true; @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 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); } @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); } @Test public void interruptedExceptionShouldSetInterruptedOnTheThread() { assertThatExceptionOfType(RuntimeException.class) .isThrownBy(() -> invokeSafely(this::methodThatThrowsInterruptedException)) .withCauseInstanceOf(InterruptedException.class); assertThat(Thread.currentThread().isInterrupted()).isTrue(); // Clear interrupt flag Thread.interrupted(); } private String methodThatThrows() throws Exception { throw new Exception("Ouch"); } private String methodThatThrowsIOException() throws IOException { throw new IOException("Boom"); } private String methodWithCheckedSignatureThatThrowsRuntimeException() throws Exception { throw new RuntimeException("Uh oh"); } private String methodThatThrowsInterruptedException() throws InterruptedException { throw new InterruptedException(); } private void consumerMethodWithChecked(Boolean shouldThrow) throws Exception { if (shouldThrow) { throw new Exception("Duh, something went wrong"); } } private String functionMethodWithChecked(Boolean shouldThrow) throws Exception { if (shouldThrow) { throw new Exception("Duh, something went wrong"); } return "Hello"; } }
3,208
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/AttributeMapTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.junit.Test; import org.mockito.Mockito; import org.w3c.dom.Attr; public class AttributeMapTest { private static final AttributeMap.Key<String> STRING_KEY = new AttributeMap.Key<String>(String.class) { }; private static final AttributeMap.Key<Integer> INTEGER_KEY = new AttributeMap.Key<Integer>(Integer.class) { }; private static final AttributeMap.Key<AutoCloseable> CLOSEABLE_KEY = new AttributeMap.Key<AutoCloseable>(AutoCloseable.class) { }; private static final AttributeMap.Key<ExecutorService> EXECUTOR_SERVICE_KEY = new AttributeMap.Key<ExecutorService>(ExecutorService.class) { }; @Test public void copyCreatesNewOptionsObject() { AttributeMap orig = AttributeMap.builder() .put(STRING_KEY, "foo") .build(); assertTrue(orig != orig.copy()); assertThat(orig).isEqualTo(orig.copy()); assertThat(orig.get(STRING_KEY)).isEqualTo(orig.copy().get(STRING_KEY)); } @Test public void mergeTreatsThisObjectWithHigherPrecedence() { AttributeMap orig = AttributeMap.builder() .put(STRING_KEY, "foo") .build(); AttributeMap merged = orig.merge(AttributeMap.builder() .put(STRING_KEY, "bar") .put(INTEGER_KEY, 42) .build()); assertThat(merged.containsKey(STRING_KEY)).isTrue(); assertThat(merged.get(STRING_KEY)).isEqualTo("foo"); // Integer key is not in 'this' object so it should be merged in from the lower precedence assertThat(merged.get(INTEGER_KEY)).isEqualTo(42); } /** * Options are optional. */ @Test public void mergeWithOptionNotPresentInBoth_DoesNotThrow() { AttributeMap orig = AttributeMap.builder() .put(STRING_KEY, "foo") .build(); AttributeMap merged = orig.merge(AttributeMap.builder() .put(STRING_KEY, "bar") .build()); assertThat(merged.get(INTEGER_KEY)).isNull(); } @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(); } @Test public void close_closesAll() { SdkAutoCloseable closeable = mock(SdkAutoCloseable.class); ExecutorService executor = mock(ExecutorService.class); AttributeMap.builder() .put(CLOSEABLE_KEY, closeable) .put(EXECUTOR_SERVICE_KEY, executor) .build() .close(); verify(closeable).close(); verify(executor).shutdown(); } @Test public void lazyAttributes_resolvedWhenRead() { AttributeMap map = mapWithLazyString(); assertThat(map.get(STRING_KEY)).isEqualTo("5"); } @Test public void lazyAttributesBuilder_resolvedWhenRead() { AttributeMap.Builder map = mapBuilderWithLazyString(); assertThat(map.get(STRING_KEY)).isEqualTo("5"); map.put(INTEGER_KEY, 6); assertThat(map.get(STRING_KEY)).isEqualTo("6"); } @Test public void lazyAttributes_resultCached() { AttributeMap.Builder map = mapBuilderWithLazyString(); String originalGet = map.get(STRING_KEY); assertThat(map.get(STRING_KEY)).isSameAs(originalGet); map.put(CLOSEABLE_KEY, null); assertThat(map.get(STRING_KEY)).isSameAs(originalGet); } @Test public void lazyAttributesBuilder_resolvedWhenBuilt() { Runnable lazyRead = mock(Runnable.class); AttributeMap.Builder map = mapBuilderWithLazyString(lazyRead); verify(lazyRead, never()).run(); map.build(); verify(lazyRead, Mockito.times(1)).run(); } @Test public void lazyAttributes_notReResolvedAfterToBuilderBuild() { Runnable lazyRead = mock(Runnable.class); AttributeMap.Builder map = mapBuilderWithLazyString(lazyRead); verify(lazyRead, never()).run(); AttributeMap builtMap = map.build(); verify(lazyRead, Mockito.times(1)).run(); builtMap.toBuilder().build().toBuilder().build(); verify(lazyRead, Mockito.times(1)).run(); } @Test public void changesInBuilder_doNotAffectBuiltMap() { AttributeMap.Builder builder = mapBuilderWithLazyString(); AttributeMap map = builder.build(); builder.put(INTEGER_KEY, 6); assertThat(builder.get(INTEGER_KEY)).isEqualTo(6); assertThat(builder.get(STRING_KEY)).isEqualTo("6"); assertThat(map.get(INTEGER_KEY)).isEqualTo(5); assertThat(map.get(STRING_KEY)).isEqualTo("5"); } @Test public void changesInToBuilder_doNotAffectBuiltMap() { AttributeMap map = mapWithLazyString(); AttributeMap.Builder builder = map.toBuilder(); builder.put(INTEGER_KEY, 6); assertThat(builder.get(INTEGER_KEY)).isEqualTo(6); assertThat(builder.get(STRING_KEY)).isEqualTo("6"); assertThat(map.get(INTEGER_KEY)).isEqualTo(5); assertThat(map.get(STRING_KEY)).isEqualTo("5"); } @Test public void close_ExecutorDoesNotDeadlockOnClose() throws Exception { SdkAutoCloseable closeable = mock(SdkAutoCloseable.class); ExecutorService executor = Executors.newSingleThreadExecutor(); AttributeMap attributeMap = AttributeMap.builder() .put(CLOSEABLE_KEY, closeable) .put(EXECUTOR_SERVICE_KEY, executor) .build(); // Previously, running AttributeMap#close from a thread managed by the ExecutorService // that's stored in that AttributeMap instance would result in a deadlock, where this // invocation would time out. This verifies that that scenario no longer happens. CompletableFuture.runAsync(attributeMap::close, executor).get(5L, TimeUnit.SECONDS); verify(closeable).close(); assertThat(executor.isShutdown()).isTrue(); } /** * This tests that the {@link ExecutorService} which as of Java 21 implements the {@link AutoCloseable} * interface, doesn't have its {@link AutoCloseable#close()} method called, but instead the expected * {@link ExecutorService#shutdown()} method is. * * This test scenario can be removed when the SDK upgrades its minimum supported version to Java 21, * whereupon this scenario will be handled by {@link AttributeMapTest#close_closesAll}. */ @Test public void close_shutsDownExecutorService() throws Exception { SdkAutoCloseable closeable = mock(SdkAutoCloseable.class); CloseableExecutorService executor = mock(CloseableExecutorService.class); AttributeMap.builder() .put(CLOSEABLE_KEY, closeable) .put(EXECUTOR_SERVICE_KEY, executor) .build() .close(); verify(closeable).close(); verify(executor, never()).close(); verify(executor).shutdown(); } /** * Simulates the API contract of the ExecutorService as of Java 21, where it extends the * {@link AutoCloseable} interface and is susceptible to being closed by {@link AttributeMap#close()}. */ private interface CloseableExecutorService extends ExecutorService, AutoCloseable {} private static AttributeMap mapWithLazyString() { return mapBuilderWithLazyString().build(); } private static AttributeMap.Builder mapBuilderWithLazyString() { return mapBuilderWithLazyString(() -> {}); } private static AttributeMap.Builder mapBuilderWithLazyString(Runnable runOnLazyRead) { return AttributeMap.builder() .putLazy(STRING_KEY, c -> { runOnLazyRead.run(); return Integer.toString(c.get(INTEGER_KEY)); }) .put(INTEGER_KEY, 5); } }
3,209
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/ReflectionMethodInvokerTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.sameInstance; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.lang.reflect.InvocationTargetException; import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class ReflectionMethodInvokerTest { private final InvokeTestClass invokeTestInstance = new InvokeTestClass(); @Rule public ExpectedException exception = ExpectedException.none(); @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); } // This test assumes that the result of getMethod() may have been cached, and therefore asserts the correctness of // a simple cache put and get. @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)); } @Test public void initialize_methodNotFound_throwsMethodNotFoundException() throws NoSuchMethodException { ReflectionMethodInvoker<String, Integer> invoker = new ReflectionMethodInvoker<String, Integer>(String.class, Integer.class, "foo", String.class, int.class); exception.expect(NoSuchMethodException.class); invoker.initialize(); } @Test public void isInitialized_methodFoundAndInitialized_returnsTrue() throws Exception { ReflectionMethodInvoker<String, Integer> invoker = new ReflectionMethodInvoker<String, Integer>(String.class, Integer.class, "indexOf", String.class, int.class); invoker.initialize(); assertThat(invoker.isInitialized(), is(true)); } @Test public void isInitialized_methodFoundAndNotInitialized_returnsFalse() throws Exception { ReflectionMethodInvoker<String, Integer> invoker = new ReflectionMethodInvoker<String, Integer>(String.class, Integer.class, "indexOf", String.class, int.class); assertThat(invoker.isInitialized(), is(false)); } @Test public void isInitialized_methodNotFoundAndInitialized_returnsFalse() throws Exception { ReflectionMethodInvoker<String, Integer> invoker = new ReflectionMethodInvoker<String, Integer>(String.class, Integer.class, "foo", String.class, int.class); try { invoker.initialize(); fail("Excepted NoSuchMethodException to be thrown"); } catch (NoSuchMethodException ignored) { } assertThat(invoker.isInitialized(), is(false)); } public static class InvokeTestClass { public void throwsException() { throw new RuntimeException(); } private void illegalAccessException() { // should never get here } public void happyVoid() { } } }
3,210
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/ComparableUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.lessThan; import org.junit.jupiter.api.Test; public class ComparableUtilsTest { @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)); } }
3,211
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/DateUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static java.time.ZoneOffset.UTC; import static java.time.format.DateTimeFormatter.ISO_INSTANT; import static java.time.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME; import static java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static software.amazon.awssdk.utils.DateUtils.ALTERNATE_ISO_8601_DATE_FORMAT; import static software.amazon.awssdk.utils.DateUtils.RFC_822_DATE_TIME; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Duration; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.Arrays; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Test; public class DateUtilsTest { private static final boolean DEBUG = false; private static final int MAX_MILLIS_YEAR = 292278994; private static final SimpleDateFormat COMMON_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); private static final SimpleDateFormat LONG_DATE_FORMAT = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US); static { COMMON_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone(UTC)); LONG_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone(UTC)); } private static final Instant INSTANT = Instant.ofEpochMilli(1400284606000L); @Test public void tt0031561767() { String input = "Fri, 16 May 2014 23:56:46 GMT"; Instant instant = DateUtils.parseRfc1123Date(input); assertEquals(input, DateUtils.formatRfc1123Date(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); } @Test public void formatRfc822Date_DateWithTwoDigitDayOfMonth_ReturnsFormattedString() throws ParseException { String string = DateUtils.formatRfc822Date(INSTANT); Instant parsedDateAsInstant = LONG_DATE_FORMAT.parse(string).toInstant(); assertThat(parsedDateAsInstant).isEqualTo(INSTANT); } @Test public void formatRfc822Date_DateWithSingleDigitDayOfMonth_ReturnsFormattedString() throws ParseException { Instant INSTANT_SINGLE_DIGIT_DAY_OF_MONTH = Instant.ofEpochMilli(1399484606000L);; String string = DateUtils.formatRfc822Date(INSTANT_SINGLE_DIGIT_DAY_OF_MONTH); Instant parsedDateAsInstant = LONG_DATE_FORMAT.parse(string).toInstant(); assertThat(parsedDateAsInstant).isEqualTo(INSTANT_SINGLE_DIGIT_DAY_OF_MONTH); } @Test public void formatRfc822Date_DateWithSingleDigitDayOfMonth_ReturnsStringWithZeroLeadingDayOfMonth() throws ParseException { final Instant INSTANT_SINGLE_DIGIT_DAY_OF_MONTH = Instant.ofEpochMilli(1399484606000L);; String string = DateUtils.formatRfc822Date(INSTANT_SINGLE_DIGIT_DAY_OF_MONTH); String expectedString = "Wed, 07 May 2014 17:43:26 GMT"; assertThat(string).isEqualTo(expectedString); } @Test public void parseRfc822Date_DateWithTwoDigitDayOfMonth_ReturnsInstantObject() throws ParseException { String formattedDate = LONG_DATE_FORMAT.format(Date.from(INSTANT)); Instant parsedInstant = DateUtils.parseRfc822Date(formattedDate); assertThat(parsedInstant).isEqualTo(INSTANT); } @Test public void parseRfc822Date_DateWithSingleDigitDayOfMonth_ReturnsInstantObject() throws ParseException { final Instant INSTANT_SINGLE_DIGIT_DAY_OF_MONTH = Instant.ofEpochMilli(1399484606000L);; String formattedDate = LONG_DATE_FORMAT.format(Date.from(INSTANT_SINGLE_DIGIT_DAY_OF_MONTH)); Instant parsedInstant = DateUtils.parseRfc822Date(formattedDate); assertThat(parsedInstant).isEqualTo(INSTANT_SINGLE_DIGIT_DAY_OF_MONTH); } @Test public void parseRfc822Date_DateWithInvalidDayOfMonth_IsParsedWithSmartResolverStyle() { String badDateString = "Wed, 31 Apr 2014 17:43:26 GMT"; String validDateString = "Wed, 30 Apr 2014 17:43:26 GMT"; Instant badDateParsedInstant = DateUtils.parseRfc822Date(badDateString); Instant validDateParsedInstant = DateUtils.parseRfc1123Date(validDateString); assertThat(badDateParsedInstant).isEqualTo(validDateParsedInstant); } @Test public void parseRfc822Date_DateWithInvalidDayOfMonth_MatchesRfc1123Behavior() { String dateString = "Wed, 31 Apr 2014 17:43:26 GMT"; Instant parsedInstantFromRfc822Parser = DateUtils.parseRfc822Date(dateString); Instant parsedInstantFromRfc1123arser = DateUtils.parseRfc1123Date(dateString); assertThat(parsedInstantFromRfc822Parser).isEqualTo(parsedInstantFromRfc1123arser); } @Test public void parseRfc822Date_DateWithDayOfMonthLessThan10th_MatchesRfc1123Behavior() { String rfc822DateString = "Wed, 02 Apr 2014 17:43:26 GMT"; String rfc1123DateString = "Wed, 2 Apr 2014 17:43:26 GMT"; Instant parsedInstantFromRfc822Parser = DateUtils.parseRfc822Date(rfc822DateString); Instant parsedInstantFromRfc1123arser = DateUtils.parseRfc1123Date(rfc1123DateString); assertThat(parsedInstantFromRfc822Parser).isEqualTo(parsedInstantFromRfc1123arser); } @Test public void resolverStyleOfRfc822FormatterMatchesRfc1123Formatter() { assertThat(RFC_822_DATE_TIME.getResolverStyle()).isSameAs(RFC_1123_DATE_TIME.getResolverStyle()); } @Test public void chronologyOfRfc822FormatterMatchesRfc1123Formatter() { assertThat(RFC_822_DATE_TIME.getChronology()).isSameAs(RFC_1123_DATE_TIME.getChronology()); } @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); } @Test public void parseRfc1123Date() 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); } @Test public void parseIso8601Date() throws ParseException { checkParsing(DateTimeFormatter.ISO_INSTANT, COMMON_DATE_FORMAT); } @Test public void parseIso8601Date_withUtcOffset() { String formatted = "2021-05-10T17:12:13-07:00"; Instant expected = ISO_OFFSET_DATE_TIME.parse(formatted, Instant::from); Instant actual = DateUtils.parseIso8601Date(formatted); assertEquals(expected, actual); String actualString = OffsetDateTime.ofInstant(actual, ZoneId.of("-7")).toString(); assertEquals(formatted, actualString); } @Test public void parseIso8601Date_usingAlternativeFormat() throws ParseException { checkParsing(ALTERNATE_ISO_8601_DATE_FORMAT, COMMON_DATE_FORMAT); } private void checkParsing(DateTimeFormatter dateTimeFormatter, SimpleDateFormat dateFormat) throws ParseException { String formatted = dateFormat.format(Date.from(INSTANT)); String alternative = dateTimeFormatter.format(INSTANT); assertEquals(formatted, alternative); Instant expected = dateFormat.parse(formatted).toInstant(); Instant actualDate = DateUtils.parseIso8601Date(formatted); assertEquals(expected, actualDate); } @Test public void alternateIso8601DateFormat() throws ParseException { String expected = COMMON_DATE_FORMAT.format(Date.from(INSTANT)); String actual = ALTERNATE_ISO_8601_DATE_FORMAT.format(INSTANT); assertEquals(expected, actual); Date expectedDate = COMMON_DATE_FORMAT.parse(expected); ZonedDateTime actualDateTime = ZonedDateTime.parse(actual, ALTERNATE_ISO_8601_DATE_FORMAT); assertEquals(expectedDate, Date.from(actualDateTime.toInstant())); } @Test(expected = ParseException.class) public void legacyHandlingOfInvalidDate() throws ParseException { final String input = "2014-03-06T14:28:58.000Z.000Z"; COMMON_DATE_FORMAT.parse(input); } @Test(expected = DateTimeParseException.class) public void invalidDate() { final String input = "2014-03-06T14:28:58.000Z.000Z"; DateUtils.parseIso8601Date(input); } @Test public void testIssue233() throws ParseException { // https://github.com/aws/aws-sdk-java/issues/233 final String edgeCase = String.valueOf(MAX_MILLIS_YEAR) + "-08-17T07:12:00Z"; Instant expected = COMMON_DATE_FORMAT.parse(edgeCase).toInstant(); if (DEBUG) { System.out.println("date: " + expected); } String formatted = DateUtils.formatIso8601Date(expected); if (DEBUG) { System.out.println("formatted: " + formatted); } // we have '+' sign as prefix for years. See java.time.format.SignStyle.EXCEEDS_PAD assertEquals(edgeCase, formatted.substring(1)); Instant parsed = DateUtils.parseIso8601Date(formatted); if (DEBUG) { System.out.println("parsed: " + parsed); } assertEquals(expected, parsed); String reformatted = ISO_INSTANT.format(parsed); // we have '+' sign as prefix for years. See java.time.format.SignStyle.EXCEEDS_PAD assertEquals(edgeCase, reformatted.substring(1)); } @Test public void testIssue233JavaTimeLimit() { // https://github.com/aws/aws-sdk-java/issues/233 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); } @Test public void testIssueDaysDiff() throws ParseException { // https://github.com/aws/aws-sdk-java/issues/233 COMMON_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone(UTC)); String edgeCase = String.valueOf(MAX_MILLIS_YEAR) + "-08-17T07:12:55Z"; String testCase = String.valueOf(MAX_MILLIS_YEAR - 1) + "-08-17T07:12:55Z"; Date edgeDate = COMMON_DATE_FORMAT.parse(edgeCase); Date testDate = COMMON_DATE_FORMAT.parse(testCase); long diff = edgeDate.getTime() - testDate.getTime(); assertTrue(diff == TimeUnit.DAYS.toMillis(365)); } @Test public void numberOfDaysSinceEpoch() { final long now = System.currentTimeMillis(); final long days = DateUtils.numberOfDaysSinceEpoch(now); final long oneDayMilli = Duration.ofDays(1).toMillis(); // Could be equal at 00:00:00. assertTrue(now >= Duration.ofDays(days).toMillis()); assertTrue((now - Duration.ofDays(days).toMillis()) <= oneDayMilli); } /** * Tests the Date marshalling and unmarshalling. Asserts that the value is * same before and after marshalling/unmarshalling */ @Test public void testUnixTimestampRoundtrip() throws Exception { long[] testValues = new long[] {System.currentTimeMillis(), 1L, 0L}; Arrays.stream(testValues) .mapToObj(Instant::ofEpochMilli) .forEach(instant -> { String serverSpecificDateFormat = DateUtils.formatUnixTimestampInstant(instant); Instant parsed = DateUtils.parseUnixTimestampInstant(String.valueOf(serverSpecificDateFormat)); assertEquals(instant, parsed); }); } @Test public void parseUnixTimestampInstant_longerThan20Char_throws() { String largeNum = Stream.generate(() -> "9").limit(21).collect(Collectors.joining()); assertThatThrownBy(() -> DateUtils.parseUnixTimestampInstant(largeNum)) .isInstanceOf(RuntimeException.class) .hasMessageContaining("20"); } }
3,212
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/Base16LowerCodecTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.security.MessageDigest; import java.util.Arrays; import java.util.UUID; import org.junit.jupiter.api.Test; import software.amazon.awssdk.utils.internal.Base16; import software.amazon.awssdk.utils.internal.Base16Lower; /** * @author hchar */ public class Base16LowerCodecTest { @Test public void testVectorsPerRfc4648() throws Exception { String[] testVectors = {"", "f", "fo", "foo", "foob", "fooba", "foobar"}; String[] expected = {"", "66", "666f", "666f6f", "666f6f62", "666f6f6261", "666f6f626172"}; for (int i = 0; i < testVectors.length; i++) { String data = testVectors[i]; byte[] source = data.getBytes("UTF-8"); String b16encoded = Base16Lower.encodeAsString(data.getBytes("UTF-8")); assertEquals(expected[i], b16encoded); byte[] b16 = b16encoded.getBytes("UTF-8"); byte[] decoded = Base16.decode(b16); assertTrue(Arrays.equals(source, decoded)); decoded = Base16Lower.decode(b16); assertTrue(Arrays.equals(source, decoded)); } } @Test public void testCodecConsistency() throws Exception { byte[] decoded = null; for (int h = 0; h < 1000; h++) { byte[] digest = MessageDigest.getInstance("SHA-1").digest( UUID.randomUUID().toString().getBytes("UTF-8") ); String b16Encoded = Base16Lower.encodeAsString(digest); { decoded = Base16.decode(b16Encoded); assertTrue(Arrays.equals(decoded, digest)); decoded = Base16Lower.decode(b16Encoded); assertTrue(Arrays.equals(decoded, digest)); } { // test decoding case insensitivity decoded = Base16.decode(b16Encoded.toLowerCase()); assertTrue(Arrays.equals(decoded, digest)); decoded = Base16Lower.decode(b16Encoded.toLowerCase()); assertTrue(Arrays.equals(decoded, digest)); } } } }
3,213
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/CollectionUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.Test; public class CollectionUtilsTest { @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"))); } @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(); } @Test public void inverseMap_EmptyList_ReturnsNull() { Map<String, String> map = Collections.emptyMap(); assertThat(CollectionUtils.inverseMap(map)).isEmpty(); } @Test public void inverseMap_SingleElementList_InversesKeyAndValue() { assertThat(CollectionUtils.inverseMap(Collections.singletonMap("foo", "bar")).get("bar")).isEqualTo("foo"); } @Test public void inverseMap_MultipleElementList_InversesKeyAndValue() { Map<String, String> map = new HashMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); Map<String, String> inverseMap = CollectionUtils.inverseMap(map); assertThat(inverseMap.get("value1")).isEqualTo("key1"); assertThat(inverseMap.get("value2")).isEqualTo("key2"); assertThat(inverseMap.get("value3")).isEqualTo("key3"); } @Test public void unmodifiableMapOfListsIsUnmodifiable() { assertUnsupported(m -> m.clear()); assertUnsupported(m -> m.compute(null, null)); assertUnsupported(m -> m.computeIfAbsent(null, null)); assertUnsupported(m -> m.computeIfPresent(null, null)); assertUnsupported(m -> m.forEach((k, v) -> v.clear())); assertUnsupported(m -> m.get("foo").clear()); assertUnsupported(m -> m.getOrDefault("", emptyList()).clear()); assertUnsupported(m -> m.getOrDefault("foo", null).clear()); assertUnsupported(m -> m.merge(null, null, null)); assertUnsupported(m -> m.put(null, null)); assertUnsupported(m -> m.putAll(null)); assertUnsupported(m -> m.putIfAbsent(null, null)); assertUnsupported(m -> m.remove(null)); assertUnsupported(m -> m.remove(null, null)); assertUnsupported(m -> m.replace(null, null)); assertUnsupported(m -> m.replace(null, null, null)); assertUnsupported(m -> m.replaceAll(null)); assertUnsupported(m -> m.values().clear()); assertUnsupported(m -> m.keySet().clear()); assertUnsupported(m -> m.keySet().add(null)); assertUnsupported(m -> m.keySet().addAll(null)); assertUnsupported(m -> m.keySet().remove(null)); assertUnsupported(m -> m.keySet().removeAll(null)); assertUnsupported(m -> m.keySet().retainAll(null)); assertUnsupported(m -> m.entrySet().clear()); assertUnsupported(m -> m.entrySet().add(null)); assertUnsupported(m -> m.entrySet().addAll(null)); assertUnsupported(m -> m.entrySet().remove(null)); assertUnsupported(m -> m.entrySet().removeAll(null)); assertUnsupported(m -> m.entrySet().retainAll(null)); assertUnsupported(m -> m.entrySet().iterator().next().setValue(emptyList())); assertUnsupported(m -> m.values().clear()); assertUnsupported(m -> m.values().add(null)); assertUnsupported(m -> m.values().addAll(null)); assertUnsupported(m -> m.values().remove(null)); assertUnsupported(m -> m.values().removeAll(null)); assertUnsupported(m -> m.values().retainAll(null)); assertUnsupported(m -> m.values().iterator().next().clear()); assertUnsupported(m -> { Iterator<Map.Entry<String, List<String>>> i = m.entrySet().iterator(); i.next(); i.remove(); }); assertUnsupported(m -> { Iterator<List<String>> i = m.values().iterator(); i.next(); i.remove(); }); assertUnsupported(m -> { Iterator<String> i = m.keySet().iterator(); i.next(); i.remove(); }); } @Test public void unmodifiableMapOfListsIsReadable() { assertSupported(m -> m.containsKey("foo")); assertSupported(m -> m.containsValue("foo")); assertSupported(m -> m.equals(null)); assertSupported(m -> m.forEach((k, v) -> {})); assertSupported(m -> m.get("foo")); assertSupported(m -> m.getOrDefault("foo", null)); assertSupported(m -> m.hashCode()); assertSupported(m -> m.isEmpty()); assertSupported(m -> m.keySet()); assertSupported(m -> m.size()); assertSupported(m -> m.keySet().contains(null)); assertSupported(m -> m.keySet().containsAll(emptyList())); assertSupported(m -> m.keySet().equals(null)); assertSupported(m -> m.keySet().hashCode()); assertSupported(m -> m.keySet().isEmpty()); assertSupported(m -> m.keySet().size()); assertSupported(m -> m.keySet().spliterator()); assertSupported(m -> m.keySet().toArray()); assertSupported(m -> m.keySet().toArray(new String[0])); assertSupported(m -> m.keySet().stream()); assertSupported(m -> m.entrySet().contains(null)); assertSupported(m -> m.entrySet().containsAll(emptyList())); assertSupported(m -> m.entrySet().equals(null)); assertSupported(m -> m.entrySet().hashCode()); assertSupported(m -> m.entrySet().isEmpty()); assertSupported(m -> m.entrySet().size()); assertSupported(m -> m.entrySet().spliterator()); assertSupported(m -> m.entrySet().toArray()); assertSupported(m -> m.entrySet().toArray(new Map.Entry[0])); assertSupported(m -> m.entrySet().stream()); assertSupported(m -> m.values().contains(null)); assertSupported(m -> m.values().containsAll(emptyList())); assertSupported(m -> m.values().equals(null)); assertSupported(m -> m.values().hashCode()); assertSupported(m -> m.values().isEmpty()); assertSupported(m -> m.values().size()); assertSupported(m -> m.values().spliterator()); assertSupported(m -> m.values().toArray()); assertSupported(m -> m.values().toArray(new Collection[0])); assertSupported(m -> m.values().stream()); assertSupported(m -> m.entrySet().iterator().next()); assertSupported(m -> m.entrySet().iterator().hasNext()); assertSupported(m -> m.values().iterator().next()); assertSupported(m -> m.values().iterator().hasNext()); assertSupported(m -> m.keySet().iterator().next()); assertSupported(m -> m.keySet().iterator().hasNext()); } public void assertUnsupported(Consumer<Map<String, List<String>>> mutation) { Map<String, List<String>> map = new HashMap<>(); map.put("foo", singletonList("bar")); assertThatThrownBy(() -> mutation.accept(CollectionUtils.unmodifiableMapOfLists(map))) .isInstanceOf(UnsupportedOperationException.class); } public void assertSupported(Consumer<Map<String, List<String>>> mutation) { Map<String, List<String>> map = new HashMap<>(); map.put("foo", singletonList("bar")); mutation.accept(map); } @Test public void uniqueIndex_noDuplicateIndices_correctlyIndexes() { Set<String> values = Stream.of("a", "ab", "abc") .collect(Collectors.toSet()); Map<Integer, String> map = CollectionUtils.uniqueIndex(values, String::length); assertThat(map).hasSize(3) .containsEntry(1, "a") .containsEntry(2, "ab") .containsEntry(3, "abc"); } @Test public void uniqueIndex_map_isModifiable() { Set<String> values = Stream.of("a", "ab", "abc") .collect(Collectors.toSet()); Map<Integer, String> map = CollectionUtils.uniqueIndex(values, String::length); map.put(3, "bar"); assertThat(map).containsEntry(3, "bar"); } @Test public void uniqueIndex_duplicateIndices_throws() { Set<String> values = Stream.of("foo", "bar") .collect(Collectors.toSet()); assertThatThrownBy(() -> CollectionUtils.uniqueIndex(values, String::length)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContainingAll("foo", "bar", "3"); } }
3,214
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/ThreadFactoryBuilderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.assertj.core.api.Java6Assertions.assertThat; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class ThreadFactoryBuilderTest { @BeforeEach public void setup() { ThreadFactoryBuilder.resetPoolNumber(); } @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"); // Next factory should cause the pool number to wrap Thread threadAfterWrap = new ThreadFactoryBuilder().build().newThread(this::doNothing); assertThat(threadAfterWrap.getName()).isEqualTo("aws-java-sdk-0-0"); } @Test public void customPrefixAppendsPoolNumber() { Thread thread = new ThreadFactoryBuilder() .threadNamePrefix("custom-name") .build() .newThread(this::doNothing); assertThat(thread.getName()).isEqualTo("custom-name-0-0"); } @Test public void daemonThreadRespected() { Thread thread = new ThreadFactoryBuilder() .daemonThreads(true) .build() .newThread(this::doNothing); assertThat(thread.isDaemon()).isTrue(); } /** * To use as a {@link Runnable} method reference. */ private void doNothing() { } }
3,215
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/UserHomeDirectoryUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.assertj.core.api.Assertions.assertThat; import static software.amazon.awssdk.utils.UserHomeDirectoryUtils.userHomeDirectory; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; public class UserHomeDirectoryUtilsTest { private final Map<String, String> savedEnvironmentVariableValues = new HashMap<>(); private static final List<String> SAVED_ENVIRONMENT_VARIABLES = Arrays.asList("HOME", "USERPROFILE", "HOMEDRIVE", "HOMEPATH"); private EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper(); /** * Save the current state of the environment variables we're messing around with in these tests so that we can restore them * when we are done. */ @BeforeEach public void saveEnvironment() throws Exception { // The tests in this file change the os.home for testing windows vs non-windows loading. We need to load the home // directory that should be used for the stored file before changing the os.home so that it doesn't try to load // the file system separator during the test. If we don't, it'll complain that it doesn't recognize the file system. userHomeDirectory(); for (String variable : SAVED_ENVIRONMENT_VARIABLES) { savedEnvironmentVariableValues.put(variable, System.getenv(variable)); } } /** * Reset the environment variables after each test. */ @AfterEach public void restoreEnvironment() throws Exception { for (String variable : SAVED_ENVIRONMENT_VARIABLES) { String savedValue = savedEnvironmentVariableValues.get(variable); if (savedValue == null) { ENVIRONMENT_VARIABLE_HELPER.remove(variable); } else { ENVIRONMENT_VARIABLE_HELPER.set(variable, savedValue); } } } @Test public void homeDirectoryResolutionPriorityIsCorrectOnWindows() throws Exception { String osName = System.getProperty("os.name"); try { System.setProperty("os.name", "Windows 7"); ENVIRONMENT_VARIABLE_HELPER.set("HOME", "home"); ENVIRONMENT_VARIABLE_HELPER.set("USERPROFILE", "userprofile"); ENVIRONMENT_VARIABLE_HELPER.set("HOMEDRIVE", "homedrive"); ENVIRONMENT_VARIABLE_HELPER.set("HOMEPATH", "homepath"); assertThat(userHomeDirectory()).isEqualTo("home"); ENVIRONMENT_VARIABLE_HELPER.remove("HOME"); assertThat(userHomeDirectory()).isEqualTo("userprofile"); ENVIRONMENT_VARIABLE_HELPER.remove("USERPROFILE"); assertThat(userHomeDirectory()).isEqualTo("homedrivehomepath"); ENVIRONMENT_VARIABLE_HELPER.remove("HOMEDRIVE"); ENVIRONMENT_VARIABLE_HELPER.remove("HOMEPATH"); assertThat(userHomeDirectory()).isEqualTo(System.getProperty("user.home")); } finally { System.setProperty("os.name", osName); } } @Test public void homeDirectoryResolutionPriorityIsCorrectOnNonWindows() throws Exception { String osName = System.getProperty("os.name"); try { System.setProperty("os.name", "Linux"); ENVIRONMENT_VARIABLE_HELPER.set("HOME", "home"); ENVIRONMENT_VARIABLE_HELPER.set("USERPROFILE", "userprofile"); ENVIRONMENT_VARIABLE_HELPER.set("HOMEDRIVE", "homedrive"); ENVIRONMENT_VARIABLE_HELPER.set("HOMEPATH", "homepath"); assertThat(userHomeDirectory()).isEqualTo("home"); ENVIRONMENT_VARIABLE_HELPER.remove("HOME"); assertThat(userHomeDirectory()).isEqualTo(System.getProperty("user.home")); ENVIRONMENT_VARIABLE_HELPER.remove("USERPROFILE"); assertThat(userHomeDirectory()).isEqualTo(System.getProperty("user.home")); ENVIRONMENT_VARIABLE_HELPER.remove("HOMEDRIVE"); ENVIRONMENT_VARIABLE_HELPER.remove("HOMEPATH"); assertThat(userHomeDirectory()).isEqualTo(System.getProperty("user.home")); } finally { System.setProperty("os.name", osName); } } }
3,216
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/PairTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; public class PairTest { @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"); } @Test public void prettyToString() { assertThat(Pair.of("Hello", "World").toString()).isEqualTo("Pair(left=Hello, right=World)"); } }
3,217
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/ToStringTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Collections; import org.junit.jupiter.api.Test; /** * Validate the functionality of {@link ToString}. */ public class ToStringTest { @Test public void createIsCorrect() { assertThat(ToString.create("Foo")).isEqualTo("Foo()"); } @Test public void buildIsCorrect() { assertThat(ToString.builder("Foo").build()).isEqualTo("Foo()"); assertThat(ToString.builder("Foo").add("a", "a").build()).isEqualTo("Foo(a=a)"); assertThat(ToString.builder("Foo").add("a", "a").add("b", "b").build()).isEqualTo("Foo(a=a, b=b)"); assertThat(ToString.builder("Foo").add("a", 1).build()).isEqualTo("Foo(a=1)"); assertThat(ToString.builder("Foo").add("a", 'a').build()).isEqualTo("Foo(a=a)"); assertThat(ToString.builder("Foo").add("a", Arrays.asList("a", "b")).build()).isEqualTo("Foo(a=[a, b])"); assertThat(ToString.builder("Foo").add("a", new String[] {"a", "b"}).build()).isEqualTo("Foo(a=[a, b])"); assertThat(ToString.builder("Foo").add("a", Collections.singletonMap("a", "b")).build()).isEqualTo("Foo(a={a=b})"); } }
3,218
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/CompletableFutureUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class CompletableFutureUtilsTest { private static ExecutorService executors; @BeforeClass public static void setup() { executors = Executors.newFixedThreadPool(2); } @AfterClass public static void tearDown() { executors.shutdown(); } @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); } } @Test(timeout = 1000) public void forwardResultTo_srcCompletesSuccessfully_shouldCompleteDstFuture() { CompletableFuture<String> src = new CompletableFuture<>(); CompletableFuture<String> dst = new CompletableFuture<>(); CompletableFuture<String> returnedFuture = CompletableFutureUtils.forwardResultTo(src, dst, executors); assertThat(returnedFuture).isEqualTo(src); src.complete("foobar"); assertThat(dst.join()).isEqualTo("foobar"); } @Test(timeout = 1000) public void forwardResultTo_srcCompletesExceptionally_shouldCompleteDstFuture() { CompletableFuture<String> src = new CompletableFuture<>(); CompletableFuture<String> dst = new CompletableFuture<>(); RuntimeException exception = new RuntimeException("foobar"); CompletableFutureUtils.forwardResultTo(src, dst, executors); src.completeExceptionally(exception); assertThatThrownBy(dst::join).hasCause(exception); } @Test(timeout = 1000) public void forwardTransformedResultTo_srcCompletesSuccessfully_shouldCompleteDstFuture() { CompletableFuture<Integer> src = new CompletableFuture<>(); CompletableFuture<String> dst = new CompletableFuture<>(); CompletableFuture<Integer> returnedFuture = CompletableFutureUtils.forwardTransformedResultTo(src, dst, String::valueOf); assertThat(returnedFuture).isSameAs(src); src.complete(123); assertThat(dst.join()).isEqualTo("123"); } @Test(timeout = 1000) public void forwardTransformedResultTo_srcCompletesExceptionally_shouldCompleteDstFuture() { CompletableFuture<Integer> src = new CompletableFuture<>(); CompletableFuture<String> dst = new CompletableFuture<>(); RuntimeException exception = new RuntimeException("foobar"); CompletableFutureUtils.forwardTransformedResultTo(src, dst, String::valueOf); src.completeExceptionally(exception); assertThatThrownBy(dst::join).hasCause(exception); } @Test(timeout = 1000) public void anyFail_shouldCompleteWhenAnyFutureFails() { RuntimeException exception = new RuntimeException("blah"); CompletableFuture[] completableFutures = new CompletableFuture[2]; completableFutures[0] = new CompletableFuture(); completableFutures[1] = new CompletableFuture(); CompletableFuture<Void> anyFail = CompletableFutureUtils.anyFail(completableFutures); completableFutures[0] = CompletableFuture.completedFuture("test"); completableFutures[1].completeExceptionally(exception); assertThatThrownBy(anyFail::join).hasCause(exception); } @Test(timeout = 1000) public void anyFail_shouldNotCompleteWhenAllFuturesSucceed() { CompletableFuture[] completableFutures = new CompletableFuture[2]; completableFutures[0] = new CompletableFuture(); completableFutures[1] = new CompletableFuture(); CompletableFuture<Void> anyFail = CompletableFutureUtils.anyFail(completableFutures); completableFutures[0] = CompletableFuture.completedFuture("test"); completableFutures[1] = CompletableFuture.completedFuture("test"); assertThat(anyFail.isDone()).isFalse(); } @Test(timeout = 1000) public void allOfExceptionForwarded_anyFutureFails_shouldForwardExceptionToOthers() { RuntimeException exception = new RuntimeException("blah"); CompletableFuture[] completableFutures = new CompletableFuture[2]; completableFutures[0] = new CompletableFuture(); completableFutures[1] = new CompletableFuture(); CompletableFuture<Void> resultFuture = CompletableFutureUtils.allOfExceptionForwarded(completableFutures); completableFutures[0].completeExceptionally(exception); assertThatThrownBy(resultFuture::join).hasCause(exception); assertThatThrownBy(completableFutures[1]::join).hasCause(exception); } @Test(timeout = 1000) public void allOfExceptionForwarded_allFutureSucceed_shouldComplete() { RuntimeException exception = new RuntimeException("blah"); CompletableFuture[] completableFutures = new CompletableFuture[2]; completableFutures[0] = new CompletableFuture(); completableFutures[1] = new CompletableFuture(); CompletableFuture<Void> resultFuture = CompletableFutureUtils.allOfExceptionForwarded(completableFutures); completableFutures[0].complete("test"); completableFutures[1].complete("test"); assertThat(resultFuture.isDone()).isTrue(); assertThat(resultFuture.isCompletedExceptionally()).isFalse(); } @Test(timeout = 1000) public void joinLikeSync_completesExceptionally_throwsUnderlyingException() { Exception e = new RuntimeException("BOOM"); CompletableFuture future = new CompletableFuture(); future.completeExceptionally(e); assertThatThrownBy(() -> CompletableFutureUtils.joinLikeSync(future)) .hasSuppressedException(new RuntimeException("Task failed.")) .isEqualTo(e); } @Test(timeout = 1000) public void joinLikeSync_completesExceptionallyChecked_throwsCompletionException() { Exception e = new Exception("BOOM"); CompletableFuture future = new CompletableFuture(); future.completeExceptionally(e); assertThatThrownBy(() -> CompletableFutureUtils.joinLikeSync(future)) .hasNoSuppressedExceptions() .hasCause(e) .isInstanceOf(CompletionException.class); } @Test(timeout = 1000) public void joinLikeSync_completesExceptionallyWithError_throwsError() { Error e = new Error("BOOM"); CompletableFuture future = new CompletableFuture(); future.completeExceptionally(e); assertThatThrownBy(() -> CompletableFutureUtils.joinLikeSync(future)) .hasNoSuppressedExceptions() .isEqualTo(e); } @Test(timeout = 1000) public void joinLikeSync_canceled_throwsCancellationException() { Exception e = new Exception("BOOM"); CompletableFuture future = new CompletableFuture(); future.cancel(false); assertThatThrownBy(() -> CompletableFutureUtils.joinLikeSync(future)) .hasNoSuppressedExceptions() .hasNoCause() .isInstanceOf(CancellationException.class); }}
3,219
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/Base64UtilsCodecTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.security.MessageDigest; import java.util.Arrays; import java.util.UUID; import org.junit.jupiter.api.Test; public class Base64UtilsCodecTest { @Test public void testVectorsPerRfc4648() throws Exception { String[] testVectors = {"", "f", "fo", "foo", "foob", "fooba", "foobar"}; String[] expected = {"", "Zg==", "Zm8=", "Zm9v", "Zm9vYg==", "Zm9vYmE=", "Zm9vYmFy"}; for (int i = 0; i < testVectors.length; i++) { String data = testVectors[i]; byte[] source = data.getBytes("UTF-8"); String b64encoded = BinaryUtils.toBase64(data.getBytes("UTF-8")); assertEquals(expected[i], b64encoded); byte[] b64 = b64encoded.getBytes("UTF-8"); byte[] decoded = BinaryUtils.fromBase64Bytes(b64); assertTrue(Arrays.equals(source, decoded)); } } @Test public void testCodecConsistency() throws Exception { byte[] decoded = null; for (int h = 0; h < 1000; h++) { byte[] digest = MessageDigest.getInstance("SHA-1").digest(UUID.randomUUID().toString().getBytes("UTF-8")); String b64Encoded = BinaryUtils.toBase64(digest); decoded = BinaryUtils.fromBase64(b64Encoded); assertTrue(Arrays.equals(decoded, digest)); } } }
3,220
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/NumericUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static software.amazon.awssdk.utils.NumericUtils.max; import static software.amazon.awssdk.utils.NumericUtils.min; import java.time.Duration; import org.junit.jupiter.api.Test; public class NumericUtilsTest { private final Duration SHORT_DURATION = Duration.ofMillis(10); private final Duration SHORT_SAME_DURATION = Duration.ofMillis(10); private final Duration LONG_DURATION = Duration.ofMillis(100); private final Duration NEGATIVE_SHORT_DURATION = Duration.ofMillis(-10); private final Duration NEGATIVE_SHORT_SAME_DURATION = Duration.ofMillis(-10); private final Duration NEGATIVE_LONG_DURATION = Duration.ofMillis(-100); @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)); } @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)); } }
3,221
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/StringUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static software.amazon.awssdk.utils.StringUtils.replacePrefixIgnoreCase; import org.assertj.core.api.Assertions; import org.junit.Test; /** * Unit tests for methods of {@link StringUtils}. * * Adapted from https://github.com/apache/commons-lang. */ public class StringUtilsTest { private static final String FOO_UNCAP = "foo"; private static final String FOO_CAP = "Foo"; private static final String SENTENCE_UNCAP = "foo bar baz"; private static final String SENTENCE_CAP = "Foo Bar Baz"; @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("")); } @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("")); } @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")); // Javadoc examples assertNull(StringUtils.capitalize(null)); assertEquals("", StringUtils.capitalize("")); assertEquals("Cat", StringUtils.capitalize("cat")); assertEquals("CAt", StringUtils.capitalize("cAt")); assertEquals("'cat'", StringUtils.capitalize("'cat'")); } @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")); // Examples from uncapitalize Javadoc assertEquals("cat", StringUtils.uncapitalize("cat")); assertEquals("cat", StringUtils.uncapitalize("Cat")); assertEquals("cAT", StringUtils.uncapitalize("CAT")); } @Test public void testReCapitalize() { // reflection type of tests: Sentences. assertEquals("uncapitalize(capitalize(String)) failed", SENTENCE_UNCAP, StringUtils.uncapitalize(StringUtils.capitalize(SENTENCE_UNCAP))); assertEquals("capitalize(uncapitalize(String)) failed", SENTENCE_CAP, StringUtils.capitalize(StringUtils.uncapitalize(SENTENCE_CAP))); // reflection type of tests: One word. assertEquals("uncapitalize(capitalize(String)) failed", FOO_UNCAP, StringUtils.uncapitalize(StringUtils.capitalize(FOO_UNCAP))); assertEquals("capitalize(uncapitalize(String)) failed", FOO_CAP, StringUtils.capitalize(StringUtils.uncapitalize(FOO_CAP))); } @Test public void testStartsWithIgnoreCase() { assertTrue(StringUtils.startsWithIgnoreCase("helloworld", "hello")); assertTrue(StringUtils.startsWithIgnoreCase("hELlOwOrlD", "hello")); assertFalse(StringUtils.startsWithIgnoreCase("hello", "world")); } @Test public void testReplacePrefixIgnoreCase() { assertEquals("lloWorld" ,replacePrefixIgnoreCase("helloWorld", "he", "")); assertEquals("lloWORld" ,replacePrefixIgnoreCase("helloWORld", "He", "")); assertEquals("llOwOrld" ,replacePrefixIgnoreCase("HEllOwOrld", "he", "")); } @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", ':')); } @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")); } @Test public void testRepeat() { assertNull(StringUtils.repeat(null, 0)); assertNull(StringUtils.repeat(null, 1)); assertNull(StringUtils.repeat(null, 2)); assertEquals("", StringUtils.repeat("", 0)); assertEquals("", StringUtils.repeat("", 1)); assertEquals("", StringUtils.repeat("", 2)); assertEquals("", StringUtils.repeat("ab", 0)); assertEquals("ab", StringUtils.repeat("ab", 1)); assertEquals("abab", StringUtils.repeat("ab", 2)); assertEquals("ababab", StringUtils.repeat("ab", 3)); } @Test(expected = IllegalArgumentException.class) public void repeat_negativeCount_shouldThrowIae() { StringUtils.repeat("a", -1); } @Test(expected = OutOfMemoryError.class) public void repeat_maxCount_shouldThrowOom() { StringUtils.repeat("a", Integer.MAX_VALUE); } }
3,222
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/ValidateTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; /** * Unit tests {@link Validate}. * * Adapted from https://github.com/apache/commons-lang. */ public class ValidateTest { @Rule public ExpectedException expected = ExpectedException.none(); //----------------------------------------------------------------------- @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()); } } //----------------------------------------------------------------------- @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); } //----------------------------------------------------------------------- @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); } //----------------------------------------------------------------------- @Test public void testNotBlankMsgNullStringShouldThrow() { //given final String string = null; try { //when Validate.notBlank(string, "Message"); fail("Expecting NullPointerException"); } catch (final NullPointerException e) { //then assertEquals("Message", e.getMessage()); } } //----------------------------------------------------------------------- @Test public void testNotBlankMsgBlankStringShouldThrow() { //given final String string = " \n \t \r \n "; try { //when Validate.notBlank(string, "Message"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException e) { //then assertEquals("Message", e.getMessage()); } } //----------------------------------------------------------------------- @Test public void testNotBlankMsgBlankStringWithWhitespacesShouldThrow() { //given final String string = " "; try { //when Validate.notBlank(string, "Message"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException e) { //then assertEquals("Message", e.getMessage()); } } //----------------------------------------------------------------------- @Test public void testNotBlankMsgEmptyStringShouldThrow() { //given final String string = ""; try { //when Validate.notBlank(string, "Message"); fail("Expecting IllegalArgumentException"); } catch (final IllegalArgumentException e) { //then assertEquals("Message", e.getMessage()); } } //----------------------------------------------------------------------- @Test public void testNotBlankMsgNotBlankStringShouldNotThrow() { //given final String string = "abc"; //when Validate.notBlank(string, "Message"); //then should not throw } //----------------------------------------------------------------------- @Test public void testNotBlankMsgNotBlankStringWithWhitespacesShouldNotThrow() { //given final String string = " abc "; //when Validate.notBlank(string, "Message"); //then should not throw } //----------------------------------------------------------------------- @Test public void testNotBlankMsgNotBlankStringWithNewlinesShouldNotThrow() { //given final String string = " \n \t abc \r \n "; //when Validate.notBlank(string, "Message"); //then should not throw } //----------------------------------------------------------------------- @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); } @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()); } } @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()); } } @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()); } } @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()); } } @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")); } @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); } @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"); } @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"); } @Test public void isPositiveOrNullDouble_null_returnsNull() { assertNull(Validate.isPositiveOrNull((Double) null, "foo")); } @Test public void isPositiveOrNullDouble_positive_returnsInteger() { Double num = 100.0; assertEquals(num, Validate.isPositiveOrNull(num, "foo")); } @Test public void isPositiveOrNullDouble_zero_throws() { expected.expect(IllegalArgumentException.class); expected.expectMessage("foo"); Validate.isPositiveOrNull(0.0, "foo"); } @Test public void isPositiveOrNullDouble_negative_throws() { expected.expect(IllegalArgumentException.class); expected.expectMessage("foo"); Validate.isPositiveOrNull(-1.0, "foo"); } @Test public void isNull_notNull_shouldThrow() { expected.expect(IllegalArgumentException.class); expected.expectMessage("not null"); Validate.isNull("string", "not null"); } @Test public void isNotNegativeOrNull_negative_throws() { expected.expect(IllegalArgumentException.class); expected.expectMessage("foo"); Validate.isNotNegativeOrNull(-1L, "foo"); } @Test public void isNotNegativeOrNull_notNegative_notThrow() { assertThat(Validate.isNotNegativeOrNull(5L, "foo")).isEqualTo(5L); assertThat(Validate.isNotNegativeOrNull(0L, "foo")).isEqualTo(0L); } @Test public void isNull_null_shouldPass() { Validate.isNull(null, "not null"); } }
3,223
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/EitherTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import org.junit.Test; public class EitherTest { @Test(expected = NullPointerException.class) public void leftValueNull_ThrowsException() { Either.left(null); } @Test(expected = NullPointerException.class) public void rightValueNull_ThrowsException() { Either.right(null); } @Test public void mapWhenLeftValuePresent_OnlyCallsLeftFunction() { final Either<String, Integer> either = Either.left("left val"); final Boolean mapped = either.map(s -> { assertThat(s).isEqualTo("left val"); return Boolean.TRUE; }, this::assertNotCalled); assertThat(mapped).isTrue(); } @Test public void mapWhenRightValuePresent_OnlyCallsRightFunction() { final Either<String, Integer> either = Either.right(42); final Boolean mapped = either.map(this::assertNotCalled, i -> { assertThat(i).isEqualTo(42); return Boolean.TRUE; }); assertThat(mapped).isTrue(); } @Test public void mapLeftWhenLeftValuePresent_OnlyMapsLeftValue() { final String value = "left val"; final Either<String, Integer> either = Either.left(value); either.mapLeft(String::hashCode) .apply(l -> assertThat(l).isEqualTo(value.hashCode()), this::assertNotCalled); } @Test public void mapLeftWhenLeftValueNotPresent_DoesNotMapValue() { final Integer value = 42; final Either<String, Integer> either = Either.right(value); either.mapLeft(this::assertNotCalled) .apply(this::assertNotCalled, i -> assertThat(i).isEqualTo(42)); } @Test public void mapRightWhenRightValuePresent_OnlyMapsLeftValue() { final Integer value = 42; final Either<String, Integer> either = Either.right(value); either.mapRight(i -> "num=" + i) .apply(this::assertNotCalled, v -> assertThat(v).isEqualTo("num=42")); } @Test public void mapRightWhenRightValueNotPresent_DoesNotMapValue() { final String value = "left val"; final Either<String, Integer> either = Either.left(value); either.mapRight(this::assertNotCalled) .apply(s -> assertThat(s).isEqualTo(value), this::assertNotCalled); } @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); } @Test public void eitherLeft_returnLeft() { assertThat(Either.left("test").left()).contains("test"); assertThat(Either.left("test").right()).isEmpty(); } @Test public void eitherRight_returnRight() { assertThat(Either.right("test").right()).contains("test"); assertThat(Either.right("test").left()).isEmpty(); } private <InT, OutT> OutT assertNotCalled(InT in) { fail("Mapping function should not have been called"); return null; } }
3,224
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/LazyTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.times; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.Supplier; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; public class LazyTest { private Lazy<String> lazy; private Supplier<String> mockDelegate; @Before public void setup() { mockDelegate = Mockito.mock(Supplier.class); lazy = new Lazy<>(mockDelegate); } @Test public void delegateNotCalledOnCreation() { Mockito.verifyNoMoreInteractions(mockDelegate); } @Test public void nullIsNotCached() { Mockito.when(mockDelegate.get()).thenReturn(null); lazy.getValue(); lazy.getValue(); Mockito.verify(mockDelegate, times(2)).get(); } @Test public void exceptionsAreNotCached() { IllegalStateException exception = new IllegalStateException(); Mockito.when(mockDelegate.get()).thenThrow(exception); assertThatThrownBy(lazy::getValue).isEqualTo(exception); assertThatThrownBy(lazy::getValue).isEqualTo(exception); 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(); } } }
3,225
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/ConditionalDecoratorTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.jupiter.api.Test; public class ConditionalDecoratorTest { @Test void basicTransform_directlyCalled_isSuccessful() { ConditionalDecorator<Integer> decorator = ConditionalDecorator.create(i -> true, i -> i + 1); assertThat(decorator.transform().apply(3)).isEqualTo(4); } @Test void listOfOrderedTransforms_singleTransformAlwaysTrue_isSuccessful() { ConditionalDecorator<Integer> d1 = ConditionalDecorator.create(i -> true, i -> i + 1); assertThat(ConditionalDecorator.decorate(2, Collections.singletonList(d1))).isEqualTo(3); } @Test void listOfOrderedTransforms_alwaysTrue_isSuccessful() { ConditionalDecorator<Integer> d1 = ConditionalDecorator.create(i -> true, i -> i + 1); ConditionalDecorator<Integer> d2 = ConditionalDecorator.create(i -> true, i -> i * 2); assertThat(ConditionalDecorator.decorate(2, Arrays.asList(d1, d2))).isEqualTo(6); } @Test void listOfOrderedTransformsInReverse_alwaysTrue_isSuccessful() { ConditionalDecorator<Integer> d1 = ConditionalDecorator.create(i -> true, i -> i + 1); ConditionalDecorator<Integer> d2 = ConditionalDecorator.create(i -> true, i -> i * 2); assertThat(ConditionalDecorator.decorate(2, Arrays.asList(d2, d1))).isEqualTo(5); } @Test void listOfOrderedTransforms_onlyAddsEvenNumbers_isSuccessful() { List<ConditionalDecorator<Integer>> decorators = IntStream.range(0, 9) .<ConditionalDecorator<Integer>>mapToObj(i -> ConditionalDecorator.create(j -> i % 2 == 0, j -> j + i)) .collect(Collectors.toList()); assertThat(ConditionalDecorator.decorate(0, decorators)).isEqualTo(20); } }
3,226
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/proxy/ProxyConfigurationTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.proxy; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import software.amazon.awssdk.testutils.EnvironmentVariableHelper; import software.amazon.awssdk.utils.ProxyConfigProvider; import software.amazon.awssdk.utils.Pair; public class ProxyConfigurationTest { private static final EnvironmentVariableHelper ENVIRONMENT_VARIABLE_HELPER = new EnvironmentVariableHelper(); public static Stream<Arguments> proxyConfigurationSetting() { return Stream.of( Arguments.of(Arrays.asList( Pair.of("%s.proxyHost", "foo.com"), Pair.of("%s.proxyPort", "555"), Pair.of("http.nonProxyHosts", "bar.com"), Pair.of("%s.proxyUser", "UserOne"), Pair.of("%s.proxyPassword", "passwordSecret")), Arrays.asList( Pair.of("%s_proxy", "http://UserOne:passwordSecret@foo.com:555/"), Pair.of("no_proxy", "bar.com") ), new ExpectedProxySetting().host("foo.com") .port(555).userName("UserOne") .password("passwordSecret") .nonProxyHost("bar.com"), "All Proxy Parameters are Set"), Arguments.of(Arrays.asList( Pair.of("%s.proxyHost", "foo.com"), Pair.of("%s.proxyPort", "555")), Collections.singletonList( Pair.of("%s_proxy", "http://foo.com:555/") ), new ExpectedProxySetting().host("foo.com").port(555), "Optional Parameters are not set"), Arguments.of(Collections.singletonList( Pair.of("proxy", "")), Arrays.asList( Pair.of("%s_proxy", ""), Pair.of("no_proxy", "") ), new ExpectedProxySetting().port(0), "All parameters are Blank"), Arguments.of(Collections.singletonList( Pair.of("http.nonProxyHosts", "one,two,three")), Collections.singletonList( Pair.of("no_proxy", "one,two,three") ), new ExpectedProxySetting().port(0).nonProxyHost("one,two,three"), "Only Non Proxy Hosts are set with multiple value"), Arguments.of(Arrays.asList( Pair.of("%s.proxyVaildHost", "foo.com"), Pair.of("%s.proxyPorts", "555")), Collections.singletonList( Pair.of("%s_proxy", "http://foo:com:Incorrects:555/") ), new ExpectedProxySetting().port(0), "Incorrect local Setting"), Arguments.of(Arrays.asList( Pair.of("%s.proxyHost", "foo.com"), Pair.of("%s.proxyPort", "555"), Pair.of("http.nonProxyHosts", "bar.com"), Pair.of("%s.proxyUser", ""), Pair.of("%s.proxyPassword", "passwordSecret")), Arrays.asList( Pair.of("%s_proxy", "http://:passwordSecret@foo.com:555/"), Pair.of("no_proxy", "bar.com") ), new ExpectedProxySetting().host("foo.com").userName("").port(555).password("passwordSecret").nonProxyHost("bar.com"), "No User is left empty"), Arguments.of(Arrays.asList( Pair.of("%s.proxyHost", "foo.com"), Pair.of("%s.proxyPort", "555"), Pair.of("http.nonProxyHosts", "bar.com"), Pair.of("%s.proxyUser", "UserOne") ), Arrays.asList( Pair.of("%s_proxy", "http://UserOne@foo.com:555/"), Pair.of("no_proxy", "bar.com") ), new ExpectedProxySetting().host("foo.com").port(555).userName("UserOne").nonProxyHost("bar.com"), "Password not present"), Arguments.of(Arrays.asList( Pair.of("%s.proxyHost", "555"), Pair.of("%s.proxyPort", "-1"), Pair.of("http.nonProxyHosts", "bar.com") ), Arrays.asList( Pair.of("%s_proxy", "http://555/"), Pair.of("no_proxy", "bar.com") ), new ExpectedProxySetting().host("555").port(-1).nonProxyHost("bar.com"), "Host name is just a number"), Arguments.of(Arrays.asList( Pair.of("%s.proxyHost", "foo.com"), Pair.of("%s.proxyPort", "abcde"), Pair.of("http.nonProxyHosts", "bar.com"), Pair.of("%s.proxyUser", "UserOne"), Pair.of("%s.proxyPassword", "passwordSecret")), Arrays.asList( Pair.of("%s_proxy", "http://UserOne:passwordSecret@foo.com:0/"), Pair.of("no_proxy", "bar.com") ), new ExpectedProxySetting().host("foo.com").port(0).userName("UserOne").password("passwordSecret").nonProxyHost("bar.com"), "Number format exception for SystemProperty is handled by defaulting it to 0") ); } private static void assertProxyEquals(ProxyConfigProvider actualConfiguration, ExpectedProxySetting expectedProxySetting) { assertThat(actualConfiguration.port()).isEqualTo(expectedProxySetting.port); assertThat(actualConfiguration.host()).isEqualTo(expectedProxySetting.host); assertThat(actualConfiguration.nonProxyHosts()).isEqualTo(expectedProxySetting.nonProxyHosts); assertThat(actualConfiguration.userName().orElse(null)).isEqualTo(expectedProxySetting.userName); assertThat(actualConfiguration.password().orElse(null)).isEqualTo(expectedProxySetting.password); } static void setSystemProperties(List<Pair<String, String>> settingsPairs, String protocol) { settingsPairs.forEach(settingsPair -> System.setProperty(String.format(settingsPair.left(), protocol), settingsPair.right())); } static void setEnvironmentProperties(List<Pair<String, String>> settingsPairs, String protocol) { settingsPairs.forEach(settingsPair -> ENVIRONMENT_VARIABLE_HELPER.set(String.format(settingsPair.left(), protocol), settingsPair.right())); } @BeforeEach void setUp() { Stream.of("http", "https").forEach(protocol -> Stream.of("%s.proxyHost", "%s.proxyPort", "%s.nonProxyHosts", "%s.proxyUser", "%s.proxyPassword") .forEach(property -> System.clearProperty(String.format(property, protocol))) ); ENVIRONMENT_VARIABLE_HELPER.reset(); } @ParameterizedTest(name = "{index} - {3}.") @MethodSource("proxyConfigurationSetting") void given_LocalSetting_when_httpProtocol_then_correctProxyConfiguration(List<Pair<String, String>> systemSettingsPair, List<Pair<String, String>> envSystemSetting, ExpectedProxySetting expectedProxySetting, String testCaseName) { setSystemProperties(systemSettingsPair, "http"); setEnvironmentProperties(envSystemSetting, "http"); assertProxyEquals(ProxyConfigProvider.fromSystemPropertySettings("http"), expectedProxySetting); assertProxyEquals(ProxyConfigProvider.fromEnvironmentSettings("http"), expectedProxySetting); } @ParameterizedTest(name = "{index} - {3}.") @MethodSource("proxyConfigurationSetting") void given_LocalSetting_when_httpsProtocol_then_correctProxyConfiguration(List<Pair<String, String>> systemSettingsPair, List<Pair<String, String>> envSystemSetting, ExpectedProxySetting expectedProxySetting, String testCaseName) { setSystemProperties(systemSettingsPair, "https"); setEnvironmentProperties(envSystemSetting, "https"); assertProxyEquals(ProxyConfigProvider.fromSystemPropertySettings("https"), expectedProxySetting); assertProxyEquals(ProxyConfigProvider.fromEnvironmentSettings("https"), expectedProxySetting); } private static class ExpectedProxySetting { private int port; private String host; private String userName; private String password; private Set<String> nonProxyHosts = new HashSet<>(); public ExpectedProxySetting port(int port) { this.port = port; return this; } public ExpectedProxySetting host(String host) { this.host = host; return this; } public ExpectedProxySetting userName(String userName) { this.userName = userName; return this; } public ExpectedProxySetting password(String password) { this.password = password; return this; } public ExpectedProxySetting nonProxyHost(String... nonProxyHosts) { this.nonProxyHosts = nonProxyHosts != null ? Arrays.stream(nonProxyHosts) .collect(Collectors.toSet()) : new HashSet<>(); return this; } } }
3,227
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/cache/CachedSupplierTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.cache; import static java.time.Instant.now; import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import static software.amazon.awssdk.utils.cache.CachedSupplier.StaleValueBehavior.ALLOW; import static software.amazon.awssdk.utils.cache.CachedSupplier.StaleValueBehavior.STRICT; import java.io.Closeable; import java.time.Clock; import java.time.Instant; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.utils.cache.CachedSupplier.StaleValueBehavior; /** * Validate the functionality of {@link CachedSupplier}. */ public class CachedSupplierTest { /** * An executor for performing "get" on the cached supplier asynchronously. This, along with the {@link WaitingSupplier} allows * near-manual scheduling of threads so that we can test that the cache is only calling the underlying supplier when we want * it to. */ private ExecutorService executorService; /** * All executions added to the {@link #executorService} since the beginning of an individual test method. */ private List<Future<?>> allExecutions; /** * Create an executor service for async testing. */ @BeforeEach public void setup() { executorService = Executors.newFixedThreadPool(50); allExecutions = new ArrayList<>(); } /** * Shut down the executor service when we're done. */ @AfterEach public void shutdown() { executorService.shutdown(); } private static class MutableSupplier implements Supplier<RefreshResult<String>> { private volatile RuntimeException thingToThrow; private volatile RefreshResult<String> thingToReturn; @Override public RefreshResult<String> get() { if (thingToThrow != null) { throw thingToThrow; } return thingToReturn; } private MutableSupplier set(RuntimeException exception) { this.thingToThrow = exception; this.thingToReturn = null; return this; } private MutableSupplier set(RefreshResult<String> value) { this.thingToThrow = null; this.thingToReturn = value; return this; } } /** * An implementation of {@link Supplier} that allows us to (more or less) manually schedule threads so that we can make sure * the CachedSupplier is only calling the underlying supplier when we expect it to. */ private static class WaitingSupplier implements Supplier<RefreshResult<String>>, Closeable { /** * A semaphore that is counted up each time a "get" is started. This is useful during testing for waiting for a certain * number of "gets" to start. */ private final Semaphore startedGetPermits = new Semaphore(0); /** * A semaphore that is counted down each time a "get" is started. This is useful during testing for blocking the threads * performing the "get" until it is time for them to complete. */ private final Semaphore permits = new Semaphore(0); /** * A semaphore that is counted up each time a "get" is finished. This is useful during testing for waiting for a certain * number of "gets" to finish. */ private final Semaphore finishedGetPermits = new Semaphore(0); private final Supplier<Instant> staleTime; private final Supplier<Instant> prefetchTime; private WaitingSupplier(Instant staleTime, Instant prefetchTime) { this(() -> staleTime, () -> prefetchTime); } private WaitingSupplier(Supplier<Instant> staleTime, Supplier<Instant> prefetchTime) { this.staleTime = staleTime; this.prefetchTime = prefetchTime; } @Override public RefreshResult<String> get() { startedGetPermits.release(1); try { permits.acquire(1); } catch (InterruptedException e) { e.printStackTrace(); fail(); } finishedGetPermits.release(1); return RefreshResult.builder("value") .staleTime(staleTime.get()) .prefetchTime(prefetchTime.get()) .build(); } /** * Wait for a certain number of "gets" to have started. This will time out and fail the test after a certain amount of * time if the "gets" never actually start. */ public void waitForGetsToHaveStarted(int numExpectedGets) { assertTrue(invokeSafely(() -> startedGetPermits.tryAcquire(numExpectedGets, 10, TimeUnit.SECONDS))); } /** * Wait for a certain number of "gets" to have finished. This will time out and fail the test after a certain amount of * time if the "gets" never finish. */ public void waitForGetsToHaveFinished(int numExpectedGets) { assertTrue(invokeSafely(() -> finishedGetPermits.tryAcquire(numExpectedGets, 10, TimeUnit.SECONDS))); } /** * Release all threads blocked in this supplier. */ @Override public void close() { permits.release(50); } } @Test public void allCallsBeforeInitializationBlock() { try (WaitingSupplier waitingSupplier = new WaitingSupplier(future(), future())) { CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier).build(); // Perform two "gets". performAsyncGets(cachedSupplier, 2); // Make sure both "gets" are started. waitingSupplier.waitForGetsToHaveStarted(2); } } @Test public void staleValueBlocksAllCalls() throws InterruptedException { AdjustableClock clock = new AdjustableClock(); try (WaitingSupplier waitingSupplier = new WaitingSupplier(() -> now().plus(1, ChronoUnit.MINUTES), this::future)) { CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier) .clock(clock) .build(); // Perform one successful "get". waitingSupplier.permits.release(1); clock.time = now(); waitFor(performAsyncGet(cachedSupplier)); // Perform two "get"s that will attempt to refresh the value, and wait for them to get stuck. clock.time = now().plus(61, ChronoUnit.SECONDS); List<Future<?>> futures = performAsyncGets(cachedSupplier, 2); waitingSupplier.waitForGetsToHaveStarted(3); Thread.sleep(1_000); assertThat(futures).allMatch(f -> !f.isDone()); // Release any "gets" that blocked and wait for them to finish. waitingSupplier.permits.release(50); waitForAsyncGetsToFinish(); // Make extra sure all 3 "gets" actually happened. waitingSupplier.waitForGetsToHaveFinished(3); } } @Test public void staleValueBlocksAllCallsEvenWithStaleValuesAllowed() throws InterruptedException { // This test case may seem unintuitive: why block for a stale value refresh if we allow stale values to be used? We do // this because values may become stale from disuse in sync prefetch strategies. If there's a new value available, we'd // still like to hold threads a little to give them a chance at a non-stale value. AdjustableClock clock = new AdjustableClock(); try (WaitingSupplier waitingSupplier = new WaitingSupplier(() -> now().plus(1, ChronoUnit.MINUTES), this::future)) { CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier) .clock(clock) .staleValueBehavior(ALLOW) .build(); // Perform one successful "get". waitingSupplier.permits.release(1); clock.time = now(); waitFor(performAsyncGet(cachedSupplier)); // Perform two "get"s that will attempt to refresh the value, and wait for them to get stuck. clock.time = now().plus(61, ChronoUnit.SECONDS); List<Future<?>> futures = performAsyncGets(cachedSupplier, 2); waitingSupplier.waitForGetsToHaveStarted(3); Thread.sleep(1_000); assertThat(futures).allMatch(f -> !f.isDone()); // Release any "gets" that blocked and wait for them to finish. waitingSupplier.permits.release(50); waitForAsyncGetsToFinish(); // Make extra sure all 3 "gets" actually happened. waitingSupplier.waitForGetsToHaveFinished(3); } } @Test public void firstRetrieveFailureThrowsForStrictStaleMode() { firstRetrievalFails(STRICT); } @Test public void firstRetrieveFailureThrowsForAllowStaleMode() { firstRetrievalFails(ALLOW); } private void firstRetrievalFails(StaleValueBehavior staleValueBehavior) { RuntimeException e = new RuntimeException(); try (CachedSupplier<?> cachedSupplier = CachedSupplier.builder(() -> { throw e; }) .staleValueBehavior(staleValueBehavior) .build()) { assertThatThrownBy(cachedSupplier::get).isEqualTo(e); } } @Test public void prefetchThrowIsHiddenIfValueIsNotStaleForStrictMode() { prefetchThrowIsHiddenIfValueIsNotStale(STRICT); } @Test public void prefetchThrowIsHiddenIfValueIsNotStaleForAllowMode() { prefetchThrowIsHiddenIfValueIsNotStale(ALLOW); } private void prefetchThrowIsHiddenIfValueIsNotStale(StaleValueBehavior staleValueBehavior) { MutableSupplier supplier = new MutableSupplier(); try (CachedSupplier<?> cachedSupplier = CachedSupplier.builder(supplier) .staleValueBehavior(staleValueBehavior) .build()) { supplier.set(RefreshResult.builder("") .prefetchTime(now()) .build()); assertThat(cachedSupplier.get()).isEqualTo(""); supplier.set(new RuntimeException()); assertThat(cachedSupplier.get()).isEqualTo(""); } } @Test public void valueIsCachedForAShortTimeIfValueIsStaleInStrictMode() throws Throwable { MutableSupplier supplier = new MutableSupplier(); try (CachedSupplier<?> cachedSupplier = CachedSupplier.builder(supplier) .staleValueBehavior(STRICT) .build()) { supplier.set(RefreshResult.builder("") .staleTime(now()) .build()); assertThat(cachedSupplier.get()).isEqualTo(""); RuntimeException e = new RuntimeException(); supplier.set(e); assertThat(cachedSupplier.get()).isEqualTo(""); } } @Test public void throwIsPropagatedIfValueIsStaleInStrictMode() throws InterruptedException { MutableSupplier supplier = new MutableSupplier(); try (CachedSupplier<?> cachedSupplier = CachedSupplier.builder(supplier) .staleValueBehavior(STRICT) .build()) { supplier.set(RefreshResult.builder("") .staleTime(now()) .build()); assertThat(cachedSupplier.get()).isEqualTo(""); RuntimeException e = new RuntimeException(); supplier.set(e); Thread.sleep(1001); // Wait to avoid the light rate-limiting we apply assertThatThrownBy(cachedSupplier::get).isEqualTo(e); } } @Test public void throwIsHiddenIfValueIsStaleInAllowMode() throws InterruptedException { MutableSupplier supplier = new MutableSupplier(); try (CachedSupplier<?> cachedSupplier = CachedSupplier.builder(supplier) .staleValueBehavior(ALLOW) .build()) { supplier.set(RefreshResult.builder("") .staleTime(now().plusSeconds(1)) .build()); assertThat(cachedSupplier.get()).isEqualTo(""); RuntimeException e = new RuntimeException(); supplier.set(e); Thread.sleep(1000); assertThat(cachedSupplier.get()).isEqualTo(""); } } @Test public void basicCachingWorks() { try (WaitingSupplier waitingSupplier = new WaitingSupplier(future(), future())) { CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier).build(); // Perform 5 "gets". waitingSupplier.permits.release(5); waitFor(performAsyncGets(cachedSupplier, 5)); // Make extra sure only 1 "get" actually happened. 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()) .jitterEnabled(false) .build(); // Perform one successful "get" to prime the cache. waitingSupplier.permits.release(1); waitFor(performAsyncGet(cachedSupplier)); // Perform one "get" that will attempt to refresh the value, and wait for that one to get stuck. performAsyncGet(cachedSupplier); waitingSupplier.waitForGetsToHaveStarted(2); // Perform a successful "get" because one is already blocked to refresh. waitFor(performAsyncGet(cachedSupplier)); // Release any "gets" that blocked and wait for them to finish. waitingSupplier.permits.release(50); waitForAsyncGetsToFinish(); // Make extra sure only 2 "gets" actually happened. 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")) .jitterEnabled(false) .build()) { // Perform one successful "get" to prime the cache. waitingSupplier.permits.release(1); waitFor(performAsyncGet(cachedSupplier)); // Perform one successful "get" to kick off the async refresh. waitFor(performAsyncGet(cachedSupplier)); // Wait for the async "get" in the background to start (if it hasn't already). waitingSupplier.waitForGetsToHaveStarted(2); // Make sure only one "get" has actually happened (the async get is currently waiting to be released). waitingSupplier.waitForGetsToHaveFinished(1); } } @Test public void nonBlockingPrefetchStrategyRefreshesInBackground() { try (WaitingSupplier waitingSupplier = new WaitingSupplier(now().plusSeconds(62), now().plusSeconds(1)); CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier) .prefetchStrategy(new NonBlocking("test-%s")) .jitterEnabled(false) .build()) { waitingSupplier.permits.release(2); cachedSupplier.get(); // Ensure two "get"s happens even though we only made one call to the cached supplier. waitingSupplier.waitForGetsToHaveStarted(2); assertThat(cachedSupplier.get()).isNotNull(); } } @Test public void nonBlockingPrefetchStrategyHasOneMinuteMinimumByDefault() { try (WaitingSupplier waitingSupplier = new WaitingSupplier(now().plusSeconds(60), now()); CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier) .prefetchStrategy(new NonBlocking("test-%s")) .build()) { waitingSupplier.permits.release(2); cachedSupplier.get(); // Ensure two "get"s happens even though we only made one call to the cached supplier. assertThat(invokeSafely(() -> waitingSupplier.startedGetPermits.tryAcquire(2, 2, TimeUnit.SECONDS))).isFalse(); } } @Test public void nonBlockingPrefetchStrategyBackgroundRefreshesHitCache() throws InterruptedException { try (WaitingSupplier waitingSupplier = new WaitingSupplier(future(), future()); CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier) .prefetchStrategy(new NonBlocking("test-%s")) .build()) { waitingSupplier.permits.release(5); cachedSupplier.get(); Thread.sleep(1_000); assertThat(waitingSupplier.permits.availablePermits()).isEqualTo(4); // Only 1 call to supplier } } @Test public void nonBlockingPrefetchStrategyDoesNotRefreshUntilItIsCalled() throws InterruptedException { try (WaitingSupplier waitingSupplier = new WaitingSupplier(future(), past()); CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier) .prefetchStrategy(new NonBlocking("test-%s")) .build()) { waitingSupplier.startedGetPermits.release(); Thread.sleep(1_000); assertThat(waitingSupplier.startedGetPermits.availablePermits()).isEqualTo(1); } } @Test public void threadsAreSharedBetweenNonBlockingInstances() throws InterruptedException { int maxActive = runAndCountThreads(() -> { List<CachedSupplier<?>> css = new ArrayList<>(); for (int i = 0; i < 99; i++) { CachedSupplier<?> supplier = CachedSupplier.builder(() -> RefreshResult.builder("foo") .prefetchTime(now().plusMillis(10)) .staleTime(future()) .build()) .prefetchStrategy(new NonBlocking("test")) .jitterEnabled(false) .build(); supplier.get(); css.add(supplier); } return css; }); assertThat(maxActive).isBetween(1, 99); } @Test public void activeThreadsHaveMaxCount() throws InterruptedException { ExecutorService executor = Executors.newCachedThreadPool(); try { int maxActive = runAndCountThreads(() -> { List<CachedSupplier<?>> css = new ArrayList<>(); // Create 1000 concurrent non-blocking instances for (int i = 0; i < 1000; i++) { CachedSupplier<String> supplier = CachedSupplier.builder(() -> { invokeSafely(() -> Thread.sleep(100)); return RefreshResult.builder("foo") .prefetchTime(now().plusMillis(10)) .staleTime(now().plusSeconds(60)) .build(); }).prefetchStrategy(new NonBlocking("test")) .jitterEnabled(false) .build(); executor.submit(supplier::get); css.add(supplier); } executor.shutdown(); assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); return css; }); assertThat(maxActive).isBetween(2, 150); } finally { executor.shutdownNow(); } } /** * Run the provided supplier, measure the non-blocking executor thread count, and return the result. If the result is 0, * try again. This makes our stochastic tests ~100% reliable instead of ~99%. */ private int runAndCountThreads(ThrowingSupplier suppliersConstructor) throws InterruptedException { for (int attempt = 0; attempt < 10; attempt++) { Collection<CachedSupplier<?>> suppliers = emptyList(); try { suppliers = suppliersConstructor.get(); int maxActive = 0; for (int j = 0; j < 1000; j++) { maxActive = Math.max(maxActive, NonBlocking.executor().getActiveCount()); Thread.sleep(1); } if (maxActive != 0) { return maxActive; } } finally { suppliers.forEach(CachedSupplier::close); } } throw new AssertionError("Thread count never exceeded 0."); } @FunctionalInterface interface ThrowingSupplier { Collection<CachedSupplier<?>> get() throws InterruptedException; } /** * Asynchronously perform a "get" on the provided supplier, returning the future that will be completed when the "get" * finishes. */ private Future<?> performAsyncGet(CachedSupplier<?> supplier) { return executorService.submit(supplier::get); } /** * Asynchronously perform multiple "gets" on the provided supplier, returning the collection of futures to be completed when * the "get" finishes. */ private List<Future<?>> performAsyncGets(CachedSupplier<?> supplier, int count) { List<Future<?>> futures = new ArrayList<>(); for (int i = 0; i < count; ++i) { futures.add(performAsyncGet(supplier)); } allExecutions.addAll(futures); return futures; } /** * Wait for the provided future to complete, failing the test if it does not. */ private void waitFor(Future<?> future) { invokeSafely(() -> future.get(10, TimeUnit.SECONDS)); } /** * Wait for all futures in the provided collection fo complete, failing the test if they do not all complete. */ private void waitFor(Collection<Future<?>> futures) { futures.forEach(this::waitFor); } /** * Wait for all async gets ever created by this class to complete, failing the test if they do not all complete. */ private void waitForAsyncGetsToFinish() { waitFor(allExecutions); } private Instant past() { return now().minusSeconds(1); } private Instant future() { return Instant.MAX; } private static class AdjustableClock extends Clock { private Instant time; @Override public ZoneId getZone() { return ZoneOffset.UTC; } @Override public Clock withZone(ZoneId zone) { throw new UnsupportedOperationException(); } @Override public Instant instant() { return time; } } }
3,228
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/cache
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/cache/lru/LruCacheTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.cache.lru; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) public class LruCacheTest { private static final int MAX_SIMPLE_TEST_ENTRIES = 10; private static final int MAX_SIMPLE_CACHE_SIZE = 3; private static final List<Integer> simpleTestKeys = IntStream.range(0, MAX_SIMPLE_TEST_ENTRIES) .boxed() .collect(Collectors.toList()); private static final List<String> simpleTestValues = IntStream.range(0, MAX_SIMPLE_TEST_ENTRIES) .mapToObj(Integer::toString) .map(String::new) .collect(Collectors.toList()); @Spy private Function<Integer, String> simpleValueSupplier = new SimpleValueSupplier(simpleTestValues); private final Function<Integer, String> identitySupplier = key -> Integer.toString(key); private final Supplier<LruCache<Integer, String>> simpleCache = () -> LruCache.builder(simpleValueSupplier) .maxSize(MAX_SIMPLE_CACHE_SIZE) .build(); @Test void when_cacheHasMiss_ValueIsCalculatedAndCached() { LruCache<Integer, String> cache = simpleCache.get(); primeAndVerifySimpleCache(cache, 1); } @Test void when_cacheHasHit_ValueIsRetrievedFromCache() { LruCache<Integer, String> cache = simpleCache.get(); primeAndVerifySimpleCache(cache, MAX_SIMPLE_CACHE_SIZE); //get 2, the last added value. Should get it from cache String result = cache.get(simpleTestKeys.get(2)); assertThat(cache.size()).isEqualTo(MAX_SIMPLE_CACHE_SIZE); assertThat(result).isNotNull(); assertThat(result).isEqualTo(simpleTestValues.get(2)); //item 2 was only retrieved once from the supplier, but twice from cache verify(simpleValueSupplier, times(1)).apply(simpleTestKeys.get(2)); } @Test void when_cacheFillsUp_ValuesAreEvictedFromCache() { LruCache<Integer, String> cache = simpleCache.get(); //fill cache [2, 1, 0] primeAndVerifySimpleCache(cache, MAX_SIMPLE_CACHE_SIZE); //new item requested, evict 0 -> [3, 2, 1] String result = cache.get(simpleTestKeys.get(3)); assertCacheState(cache, result, MAX_SIMPLE_CACHE_SIZE, 3); //move 2 up -> [2, 3, 1] cache.get(simpleTestKeys.get(2)); //evict 1 -> [4, 2, 3] cache.get(simpleTestKeys.get(4)); //move 2 up -> [2, 4, 3] cache.get(simpleTestKeys.get(2)); //get 1 back -> [1, 2, 4] result = cache.get(simpleTestKeys.get(1)); assertCacheState(cache, result, MAX_SIMPLE_CACHE_SIZE, 1); //each item in the test is only retrieved once except for 1 verify(simpleValueSupplier, times(1)).apply(simpleTestKeys.get(0)); verify(simpleValueSupplier, times(2)).apply(simpleTestKeys.get(1)); verify(simpleValueSupplier, times(1)).apply(simpleTestKeys.get(2)); verify(simpleValueSupplier, times(1)).apply(simpleTestKeys.get(3)); verify(simpleValueSupplier, times(1)).apply(simpleTestKeys.get(4)); } @Test void when_closeableValuesAreEvicted_CloseMethodIsCalled() { int cacheSize = 3; int evictNum = 2; LruCache<Integer, CloseableClass> cache = LruCache.builder(CloseableClass::new) .maxSize(cacheSize) .build(); CloseableClass.reset(); for (int i = 0; i < cacheSize + evictNum; i++) { cache.get(i); } assertThat(CloseableClass.evictedItems()).isNotEmpty(); assertThat(CloseableClass.evictedItems()).hasSize(evictNum); assertThat(CloseableClass.evictedItems().get(0)).isEqualTo(0); assertThat(CloseableClass.evictedItems().get(1)).isEqualTo(1); } @Test void when_closeableValuesAreEvicted_NoExceptionsAreThrownIfCloseFails() { int cacheSize = 3; int evictNum = 2; LruCache<Integer, FaultyCloseableClass> cache = LruCache.builder(FaultyCloseableClass::new) .maxSize(cacheSize) .build(); CloseableClass.reset(); for (int i = 0; i < cacheSize + evictNum; i++) { cache.get(i); } assertThat(CloseableClass.evictedItems()).isEmpty(); } @Test void when_mostRecentValueIsHit_ValuesAreReorderedCorrectly() { LruCache<Integer, String> cache = simpleCache.get(); //fill cache [2, 1, 0] primeAndVerifySimpleCache(cache, MAX_SIMPLE_CACHE_SIZE); //get current mru (most recently used). Cache should stay the same: [2, 1, 0] cache.get(simpleTestKeys.get(2)); //evict items 1,2 -> [3, 4, 2] cache.get(simpleTestKeys.get(3)); cache.get(simpleTestKeys.get(4)); //get 2, it should come from cache -> [2, 3, 4] cache.get(simpleTestKeys.get(2)); //each value in the test is only retrieved once verify(simpleValueSupplier, times(1)).apply(simpleTestKeys.get(0)); verify(simpleValueSupplier, times(1)).apply(simpleTestKeys.get(1)); verify(simpleValueSupplier, times(1)).apply(simpleTestKeys.get(2)); verify(simpleValueSupplier, times(1)).apply(simpleTestKeys.get(3)); verify(simpleValueSupplier, times(1)).apply(simpleTestKeys.get(4)); } @Test void when_leastRecentValueIsHit_ValuesAreReorderedCorrectly() { LruCache<Integer, String> cache = simpleCache.get(); //fill cache [2, 1, 0] primeAndVerifySimpleCache(cache, MAX_SIMPLE_CACHE_SIZE); //get current lru (least recently used) and move up cache.get(simpleTestKeys.get(0)); //evict items 1, 2 -> [3, 4, 0] cache.get(simpleTestKeys.get(3)); cache.get(simpleTestKeys.get(4)); //get 0, should return cached value -> [0, 3, 4] cache.get(simpleTestKeys.get(0)); //get 1, should get from supplier cache.get(simpleTestKeys.get(1)); //get 2, should get from supplier cache.get(simpleTestKeys.get(2)); //1, 2 fell out of cache and were retrieved verify(simpleValueSupplier, times(1)).apply(simpleTestKeys.get(0)); verify(simpleValueSupplier, times(2)).apply(simpleTestKeys.get(1)); verify(simpleValueSupplier, times(2)).apply(simpleTestKeys.get(2)); } @Test void when_cacheHasMiss_AndNoValueIsFound_ReturnsNull() { LruCache<Integer, String> cache = simpleCache.get(); primeAndVerifySimpleCache(cache, 1); Integer keyMissingValue = 200; String value = cache.get(keyMissingValue); assertThat(value).isNull(); cache.get(keyMissingValue); verify(simpleValueSupplier, times(1)).apply(keyMissingValue); } @ParameterizedTest @MethodSource("concurrencyTestValues") void when_multipleThreadsAreCallingCache_WorksAsExpected(Integer numThreads, Integer numGetsPerThread, boolean sleep, Integer cacheSize) throws Exception { ExecutorService executor = Executors.newCachedThreadPool(); try { Function<Integer, String> sleepySupplier = num -> { if (sleep) { invokeSafely(() -> Thread.sleep(ThreadLocalRandom.current().nextInt(0, 5))); } return identitySupplier.apply(num); }; LruCache<Integer, String> cache = LruCache.builder(sleepySupplier) .maxSize(cacheSize) .build(); List<Future<?>> results = new ArrayList<>(); for (int i = 0; i < numThreads; i++) { results.add(executor.submit(() -> { for (int j = 0; j < numGetsPerThread; j++) { int key = ThreadLocalRandom.current().nextInt(cacheSize * 2); String value = cache.get(key); assertThat(value).isEqualTo(Integer.toString(key)); } })); } for (Future<?> result : results) { result.get(20, TimeUnit.SECONDS); } } finally { executor.shutdownNow(); } } private static Stream<Arguments> concurrencyTestValues() { // numThreads, numGetsPerThreads, sleepDurationMillis, cacheSize return Stream.of(Arguments.of(1000, 5000, false, 5), Arguments.of(1000, 5000, false, 50), Arguments.of(100, 1000, true, 5) ); } private void assertCacheState(LruCache<Integer, String> cache, String result, int size, int index) { assertThat(cache.size()).isEqualTo(size); assertThat(result).isNotNull(); assertThat(result).isEqualTo(simpleTestValues.get(index)); } private void primeAndVerifySimpleCache(LruCache<Integer, String> cache, int numEntries) { IntStream.range(0, numEntries).forEach(i -> { String result = cache.get(simpleTestKeys.get(i)); assertThat(cache.size()).isEqualTo(i + 1); assertThat(result).isNotNull(); assertThat(result).isEqualTo(simpleTestValues.get(i)); verify(simpleValueSupplier).apply(simpleTestKeys.get(i)); }); } private static class SimpleValueSupplier implements Function<Integer, String> { List<String> values; SimpleValueSupplier(List<String> values) { this.values = values; } @Override public String apply(Integer key) { String value = null; try { value = values.get(key); } catch (Exception ignored) { } return value; } } private static class CloseableClass implements AutoCloseable { private static List<Integer> evictedList = new ArrayList<>(); private final Integer key; CloseableClass(Integer key) { this.key = key; } public Integer get() throws Exception { return key; } public static void reset() { evictedList = new ArrayList<>(); } public static List<Integer> evictedItems() { return Collections.unmodifiableList(evictedList); } @Override public void close() { evictedList.add(key); } } private static class FaultyCloseableClass extends CloseableClass { FaultyCloseableClass(Integer key) { super(key); } @Override public void close() { throw new RuntimeException("Could not close resources!"); } } }
3,229
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/InputStreamConsumingPublisherTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static software.amazon.awssdk.utils.async.ByteBufferStoringSubscriber.TransferResult.END_OF_STREAM; import static software.amazon.awssdk.utils.async.ByteBufferStoringSubscriber.TransferResult.SUCCESS; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.nio.ByteBuffer; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.utils.ThreadFactoryBuilder; public class InputStreamConsumingPublisherTest { private static final ExecutorService EXECUTOR = Executors.newCachedThreadPool(new ThreadFactoryBuilder().daemonThreads(true).build()); private ByteBufferStoringSubscriber subscriber; private InputStreamConsumingPublisher publisher; @BeforeEach public void setup() { this.subscriber = new ByteBufferStoringSubscriber(Long.MAX_VALUE); this.publisher = new InputStreamConsumingPublisher(); } @Test public void subscribeAfterWrite_completes() throws InterruptedException { EXECUTOR.submit(() -> publisher.doBlockingWrite(streamOfLength(0))); Thread.sleep(200); publisher.subscribe(subscriber); assertThat(subscriber.transferTo(ByteBuffer.allocate(0))).isEqualTo(END_OF_STREAM); } @Test public void zeroKb_completes() { publisher.subscribe(subscriber); assertThat(publisher.doBlockingWrite(streamOfLength(0))).isEqualTo(0); assertThat(subscriber.transferTo(ByteBuffer.allocate(0))).isEqualTo(END_OF_STREAM); } @Test public void oneKb_writesAndCompletes() { publisher.subscribe(subscriber); assertThat(publisher.doBlockingWrite(streamOfLength(1024))).isEqualTo(1024); assertThat(subscriber.transferTo(ByteBuffer.allocate(1023))).isEqualTo(SUCCESS); assertThat(subscriber.transferTo(ByteBuffer.allocate(1))).isEqualTo(END_OF_STREAM); } @Test public void bytesAreDeliveredInOrder() { publisher.subscribe(subscriber); assertThat(publisher.doBlockingWrite(streamWithAllBytesInOrder())).isEqualTo(256); ByteBuffer output = ByteBuffer.allocate(256); assertThat(subscriber.transferTo(output)).isEqualTo(END_OF_STREAM); output.flip(); for (int i = 0; i < 256; i++) { assertThat(output.get()).isEqualTo((byte) i); } } @Test public void failedRead_signalsOnError() { publisher.subscribe(subscriber); assertThatThrownBy(() -> publisher.doBlockingWrite(streamWithFailedReadAfterLength(1024))) .isInstanceOf(UncheckedIOException.class); } @Test public void cancel_signalsOnError() { publisher.subscribe(subscriber); publisher.cancel(); assertThatThrownBy(() -> subscriber.transferTo(ByteBuffer.allocate(0))).isInstanceOf(CancellationException.class); } @Test public void cancel_stopsRunningWrites() { publisher.subscribe(subscriber); Future<?> write = EXECUTOR.submit(() -> publisher.doBlockingWrite(streamOfLength(Integer.MAX_VALUE))); publisher.cancel(); assertThatThrownBy(write::get).hasRootCauseInstanceOf(CancellationException.class); } @Test public void cancel_beforeWrite_stopsWrite() { publisher.subscribe(subscriber); publisher.cancel(); assertThatThrownBy(() -> publisher.doBlockingWrite(streamOfLength(Integer.MAX_VALUE))) .hasRootCauseInstanceOf(CancellationException.class); } @Test public void cancel_beforeSubscribe_stopsWrite() { publisher.cancel(); publisher.subscribe(subscriber); assertThatThrownBy(() -> publisher.doBlockingWrite(streamOfLength(Integer.MAX_VALUE))) .hasRootCauseInstanceOf(CancellationException.class); } public InputStream streamOfLength(int length) { return new InputStream() { int i = 0; @Override public int read() throws IOException { if (i >= length) { return -1; } ++i; return 1; } }; } public InputStream streamWithAllBytesInOrder() { return new InputStream() { int i = 0; @Override public int read() throws IOException { if (i > 255) { return -1; } return i++; } }; } public InputStream streamWithFailedReadAfterLength(int length) { return new InputStream() { int i = 0; @Override public int read() throws IOException { if (i > length) { throw new IOException("Failed to read!"); } ++i; return 1; } }; } }
3,230
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/FlatteningSubscriberTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import static java.time.temporal.ChronoUnit.SECONDS; import static org.mockito.Mockito.times; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; public class FlatteningSubscriberTest { private Subscriber<String> mockDelegate; private Subscription mockUpstream; private FlatteningSubscriber<String> flatteningSubscriber; @BeforeEach @SuppressWarnings("unchecked") public void setup() { mockDelegate = Mockito.mock(Subscriber.class); mockUpstream = Mockito.mock(Subscription.class); flatteningSubscriber = new FlatteningSubscriber<>(mockDelegate); } @Test public void requestOne() { flatteningSubscriber.onSubscribe(mockUpstream); Subscription downstream = getDownstreamFromDelegate(); downstream.request(1); Mockito.verify(mockUpstream).request(1); flatteningSubscriber.onNext(Arrays.asList("foo", "bar")); Mockito.verify(mockDelegate).onNext("foo"); Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate); } @Test public void requestTwo() { flatteningSubscriber.onSubscribe(mockUpstream); Subscription downstream = getDownstreamFromDelegate(); downstream.request(2); Mockito.verify(mockUpstream).request(1); flatteningSubscriber.onNext(Arrays.asList("foo", "bar")); Mockito.verify(mockDelegate).onNext("foo"); Mockito.verify(mockDelegate).onNext("bar"); Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate); } @Test public void requestThree() { flatteningSubscriber.onSubscribe(mockUpstream); Subscription downstream = getDownstreamFromDelegate(); downstream.request(3); Mockito.verify(mockUpstream, times(1)).request(1); Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate); Mockito.reset(mockUpstream, mockDelegate); flatteningSubscriber.onNext(Arrays.asList("foo", "bar")); Mockito.verify(mockDelegate).onNext("foo"); Mockito.verify(mockDelegate).onNext("bar"); Mockito.verify(mockUpstream).request(1); Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate); Mockito.reset(mockUpstream, mockDelegate); flatteningSubscriber.onNext(Arrays.asList("baz")); Mockito.verify(mockDelegate).onNext("baz"); Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate); } @Test public void requestInfinite() { flatteningSubscriber.onSubscribe(mockUpstream); Subscription downstream = getDownstreamFromDelegate(); downstream.request(1); downstream.request(Long.MAX_VALUE); downstream.request(Long.MAX_VALUE); downstream.request(Long.MAX_VALUE); downstream.request(Long.MAX_VALUE); Mockito.verify(mockUpstream, times(1)).request(1); flatteningSubscriber.onNext(Arrays.asList("foo", "bar")); flatteningSubscriber.onComplete(); Mockito.verify(mockDelegate).onNext("foo"); Mockito.verify(mockDelegate).onNext("bar"); Mockito.verify(mockDelegate).onComplete(); Mockito.verifyNoMoreInteractions(mockDelegate); } @Test public void onCompleteDelayedUntilAllDataDelivered() { flatteningSubscriber.onSubscribe(mockUpstream); Subscription downstream = getDownstreamFromDelegate(); downstream.request(1); Mockito.verify(mockUpstream).request(1); flatteningSubscriber.onNext(Arrays.asList("foo", "bar")); flatteningSubscriber.onComplete(); Mockito.verify(mockDelegate).onNext("foo"); Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate); Mockito.reset(mockUpstream, mockDelegate); downstream.request(1); Mockito.verify(mockDelegate).onNext("bar"); Mockito.verify(mockDelegate).onComplete(); Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate); } @Test public void onErrorDropsBufferedData() { Throwable t = new Throwable(); flatteningSubscriber.onSubscribe(mockUpstream); Subscription downstream = getDownstreamFromDelegate(); downstream.request(1); Mockito.verify(mockUpstream).request(1); flatteningSubscriber.onNext(Arrays.asList("foo", "bar")); flatteningSubscriber.onError(t); Mockito.verify(mockDelegate).onNext("foo"); Mockito.verify(mockDelegate).onError(t); Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate); } @Test public void requestsFromDownstreamDoNothingAfterOnComplete() { flatteningSubscriber.onSubscribe(mockUpstream); Subscription downstream = getDownstreamFromDelegate(); downstream.request(1); Mockito.verify(mockUpstream).request(1); flatteningSubscriber.onComplete(); Mockito.verify(mockDelegate).onComplete(); Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate); downstream.request(1); Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate); } @Test public void requestsFromDownstreamDoNothingAfterOnError() { Throwable t = new Throwable(); flatteningSubscriber.onSubscribe(mockUpstream); Subscription downstream = getDownstreamFromDelegate(); downstream.request(1); Mockito.verify(mockUpstream).request(1); flatteningSubscriber.onError(t); Mockito.verify(mockDelegate).onError(t); Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate); downstream.request(1); Mockito.verifyNoMoreInteractions(mockUpstream, mockDelegate); } @Test public void stochastic_dataFlushedBeforeOnComplete() { ExecutorService exec = Executors.newSingleThreadExecutor(); Instant end = Instant.now().plus(10, SECONDS); try { while (Instant.now().isBefore(end)) { Publisher<List<String>> iterablePublisher = subscriber -> subscriber.onSubscribe(new Subscription() { @Override public void request(long l) { exec.submit(() -> { subscriber.onNext(Collections.singletonList("data")); subscriber.onComplete(); }); } @Override public void cancel() { } }); AtomicInteger seen = new AtomicInteger(0); CompletableFuture<Void> finished = new CompletableFuture<>(); FlatteningSubscriber<String> elementSubscriber = new FlatteningSubscriber<>(new Subscriber<String>() { @Override public void onSubscribe(Subscription subscription) { subscription.request(1); } @Override public void onNext(String s) { seen.incrementAndGet(); } @Override public void onError(Throwable e) { finished.completeExceptionally(e); } @Override public void onComplete() { if (seen.get() != 1) { finished.completeExceptionally( new RuntimeException("Should have gotten 1 element before onComplete")); } else { finished.complete(null); } } }); iterablePublisher.subscribe(elementSubscriber); finished.join(); } } finally { exec.shutdown(); } } private Subscription getDownstreamFromDelegate() { ArgumentCaptor<Subscription> subscriptionCaptor = ArgumentCaptor.forClass(Subscription.class); Mockito.verify(mockDelegate).onSubscribe(subscriptionCaptor.capture()); return subscriptionCaptor.getValue(); } }
3,231
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/ByteBufferStoringSubscriberTckTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import java.nio.ByteBuffer; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import org.reactivestreams.tck.SubscriberWhiteboxVerification; import org.reactivestreams.tck.TestEnvironment; public class ByteBufferStoringSubscriberTckTest extends SubscriberWhiteboxVerification<ByteBuffer> { protected ByteBufferStoringSubscriberTckTest() { super(new TestEnvironment()); } @Override public Subscriber<ByteBuffer> createSubscriber(WhiteboxSubscriberProbe<ByteBuffer> probe) { return new ByteBufferStoringSubscriber(16) { @Override public void onError(Throwable throwable) { super.onError(throwable); probe.registerOnError(throwable); } @Override public void onSubscribe(Subscription subscription) { super.onSubscribe(subscription); probe.registerOnSubscribe(new SubscriberPuppet() { @Override public void triggerRequest(long elements) { subscription.request(elements); } @Override public void signalCancel() { subscription.cancel(); } }); } @Override public void onNext(ByteBuffer next) { super.onNext(next); probe.registerOnNext(next); } @Override public void onComplete() { super.onComplete(); probe.registerOnComplete(); } }; } @Override public ByteBuffer createElement(int element) { return ByteBuffer.wrap(new byte[0]); } }
3,232
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/SimplePublisherTckTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import org.reactivestreams.Publisher; import org.reactivestreams.tck.PublisherVerification; import org.reactivestreams.tck.TestEnvironment; public class SimplePublisherTckTest extends PublisherVerification<Integer> { public SimplePublisherTckTest() { super(new TestEnvironment()); } @Override public Publisher<Integer> createPublisher(long elements) { SimplePublisher<Integer> publisher = new SimplePublisher<>(); for (int i = 0; i < elements; i++) { publisher.send(i); } publisher.complete(); return publisher; } @Override public Publisher<Integer> createFailedPublisher() { SimplePublisher<Integer> publisher = new SimplePublisher<>(); publisher.error(new RuntimeException()); return publisher; } @Override public long maxElementsFromPublisher() { return 256L; } }
3,233
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/AddingTrailingDataSubscriberTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CompletableFuture; import org.junit.jupiter.api.Test; import org.reactivestreams.Subscriber; public class AddingTrailingDataSubscriberTest { @Test void trailingDataSupplierNull_shouldThrowException() { SequentialSubscriber<Integer> downstreamSubscriber = new SequentialSubscriber<Integer>(i -> {}, new CompletableFuture()); assertThatThrownBy(() -> new AddingTrailingDataSubscriber<>(downstreamSubscriber, null)) .hasMessageContaining("must not be null"); } @Test void subscriberNull_shouldThrowException() { assertThatThrownBy(() -> new AddingTrailingDataSubscriber<>(null, () -> Arrays.asList(1, 2))) .hasMessageContaining("must not be null"); } @Test void trailingDataHasItems_shouldSendAdditionalData() { List<Integer> result = new ArrayList<>(); CompletableFuture future = new CompletableFuture(); SequentialSubscriber<Integer> downstreamSubscriber = new SequentialSubscriber<Integer>(i -> result.add(i), future); Subscriber<Integer> subscriber = new AddingTrailingDataSubscriber<>(downstreamSubscriber, () -> Arrays.asList(Integer.MAX_VALUE, Integer.MIN_VALUE)); publishData(subscriber); future.join(); assertThat(result).containsExactly(0, 1, 2, Integer.MAX_VALUE, Integer.MIN_VALUE); } @Test void trailingDataEmpty_shouldNotSendAdditionalData() { List<Integer> result = new ArrayList<>(); CompletableFuture future = new CompletableFuture(); SequentialSubscriber<Integer> downstreamSubscriber = new SequentialSubscriber<Integer>(i -> result.add(i), future); Subscriber<Integer> subscriber = new AddingTrailingDataSubscriber<>(downstreamSubscriber, () -> new ArrayList<>()); publishData(subscriber); future.join(); assertThat(result).containsExactly(0, 1, 2); } @Test void trailingDataNull_shouldCompleteNormally() { List<Integer> result = new ArrayList<>(); CompletableFuture future = new CompletableFuture(); SequentialSubscriber<Integer> downstreamSubscriber = new SequentialSubscriber<Integer>(i -> result.add(i), future); Subscriber<Integer> subscriber = new AddingTrailingDataSubscriber<>(downstreamSubscriber, () -> null); publishData(subscriber); future.join(); assertThat(result).containsExactly(0, 1, 2); } private void publishData(Subscriber<Integer> subscriber) { SimplePublisher<Integer> simplePublisher = new SimplePublisher<>(); simplePublisher.subscribe(subscriber); for (int i = 0; i < 3; i++) { simplePublisher.send(i); } simplePublisher.complete(); } }
3,234
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/OutputStreamPublisherTckTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import java.nio.ByteBuffer; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.reactivestreams.Publisher; import org.reactivestreams.tck.PublisherVerification; import org.reactivestreams.tck.TestEnvironment; import software.amazon.awssdk.utils.ThreadFactoryBuilder; public class OutputStreamPublisherTckTest extends PublisherVerification<ByteBuffer> { private final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().daemonThreads(true).build()); public OutputStreamPublisherTckTest() { super(new TestEnvironment()); } @Override public Publisher<ByteBuffer> createPublisher(long elements) { OutputStreamPublisher publisher = new OutputStreamPublisher(); executor.submit(() -> { for (int i = 0; i < elements; i++) { publisher.write(new byte[1]); } publisher.close(); }); return publisher; } @Override public Publisher<ByteBuffer> createFailedPublisher() { OutputStreamPublisher publisher = new OutputStreamPublisher(); executor.submit(publisher::cancel); return publisher; } }
3,235
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/SimplePublisherTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.Test; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.utils.Pair; import software.amazon.awssdk.utils.async.StoringSubscriber.Event; import software.amazon.awssdk.utils.async.StoringSubscriber.EventType; public class SimplePublisherTest { /** * This class has tests that try to break things for a fixed period of time, and then make sure nothing broke. * This flag controls how long those tests run. Longer values provider a better guarantee of catching an issue, but * increase the build time. 5 seconds seems okay for now, but if a flaky test is found try increasing the duration to make * it reproduce more reliably. */ private static final Duration STOCHASTIC_TEST_DURATION = Duration.ofSeconds(5); @Test public void immediateSuccessWorks() { SimplePublisher<Integer> publisher = new SimplePublisher<>(); StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(1); publisher.subscribe(subscriber); publisher.complete(); assertThat(subscriber.poll().get().type()).isEqualTo(EventType.ON_COMPLETE); assertThat(subscriber.poll()).isNotPresent(); } @Test public void immediateFailureWorks() { RuntimeException error = new RuntimeException(); SimplePublisher<Integer> publisher = new SimplePublisher<>(); StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(1); publisher.subscribe(subscriber); publisher.error(error); assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_ERROR); assertThat(subscriber.peek().get().runtimeError()).isEqualTo(error); subscriber.poll(); assertThat(subscriber.poll()).isNotPresent(); } @Test public void writeAfterCompleteFails() { SimplePublisher<Integer> publisher = new SimplePublisher<>(); publisher.subscribe(new StoringSubscriber<>(1)); publisher.complete(); assertThat(publisher.send(5)).isCompletedExceptionally(); } @Test public void writeAfterErrorFails() { SimplePublisher<Integer> publisher = new SimplePublisher<>(); publisher.subscribe(new StoringSubscriber<>(1)); publisher.error(new Throwable()); assertThat(publisher.send(5)).isCompletedExceptionally(); } @Test public void completeAfterCompleteFails() { SimplePublisher<Integer> publisher = new SimplePublisher<>(); publisher.subscribe(new StoringSubscriber<>(1)); publisher.complete(); assertThat(publisher.complete()).isCompletedExceptionally(); } @Test public void completeAfterErrorFails() { SimplePublisher<Integer> publisher = new SimplePublisher<>(); publisher.subscribe(new StoringSubscriber<>(1)); publisher.error(new Throwable()); assertThat(publisher.complete()).isCompletedExceptionally(); } @Test public void errorAfterCompleteFails() { SimplePublisher<Integer> publisher = new SimplePublisher<>(); publisher.subscribe(new StoringSubscriber<>(1)); publisher.complete(); assertThat(publisher.error(new Throwable())).isCompletedExceptionally(); } @Test public void errorAfterErrorFails() { SimplePublisher<Integer> publisher = new SimplePublisher<>(); publisher.subscribe(new StoringSubscriber<>(1)); publisher.error(new Throwable()); assertThat(publisher.error(new Throwable())).isCompletedExceptionally(); } @Test public void oneDemandWorks() { SimplePublisher<Integer> publisher = new SimplePublisher<>(); StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(1); publisher.subscribe(subscriber); publisher.send(1); publisher.send(2); publisher.complete(); assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_NEXT); assertThat(subscriber.peek().get().value()).isEqualTo(1); subscriber.poll(); assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_NEXT); assertThat(subscriber.peek().get().value()).isEqualTo(2); subscriber.poll(); assertThat(subscriber.poll().get().type()).isEqualTo(EventType.ON_COMPLETE); assertThat(subscriber.poll()).isNotPresent(); } @Test public void highDemandWorks() { SimplePublisher<Integer> publisher = new SimplePublisher<>(); ControllableSubscriber<Integer> subscriber = new ControllableSubscriber<>(); publisher.subscribe(subscriber); subscriber.subscription.request(Long.MAX_VALUE); publisher.send(1); subscriber.subscription.request(Long.MAX_VALUE); publisher.send(2); subscriber.subscription.request(Long.MAX_VALUE); publisher.complete(); subscriber.subscription.request(Long.MAX_VALUE); assertThat(subscriber.eventQueue.peek().get().type()).isEqualTo(EventType.ON_NEXT); assertThat(subscriber.eventQueue.peek().get().value()).isEqualTo(1); subscriber.eventQueue.poll(); assertThat(subscriber.eventQueue.peek().get().type()).isEqualTo(EventType.ON_NEXT); assertThat(subscriber.eventQueue.peek().get().value()).isEqualTo(2); subscriber.eventQueue.poll(); assertThat(subscriber.eventQueue.peek().get().type()).isEqualTo(EventType.ON_COMPLETE); subscriber.eventQueue.poll(); assertThat(subscriber.eventQueue.poll()).isNotPresent(); } @Test public void writeFuturesDoNotCompleteUntilAfterOnNext() { SimplePublisher<Integer> publisher = new SimplePublisher<>(); ControllableSubscriber<Integer> subscriber = new ControllableSubscriber<>(); publisher.subscribe(subscriber); CompletableFuture<Void> writeFuture = publisher.send(5); assertThat(subscriber.eventQueue.peek()).isNotPresent(); assertThat(writeFuture).isNotCompleted(); subscriber.subscription.request(1); assertThat(subscriber.eventQueue.peek().get().type()).isEqualTo(EventType.ON_NEXT); assertThat(subscriber.eventQueue.peek().get().value()).isEqualTo(5); assertThat(writeFuture).isCompletedWithValue(null); } @Test public void completeFuturesDoNotCompleteUntilAfterOnComplete() { SimplePublisher<Integer> publisher = new SimplePublisher<>(); ControllableSubscriber<Integer> subscriber = new ControllableSubscriber<>(); publisher.subscribe(subscriber); publisher.send(5); CompletableFuture<Void> completeFuture = publisher.complete(); assertThat(subscriber.eventQueue.peek()).isNotPresent(); assertThat(completeFuture).isNotCompleted(); subscriber.subscription.request(1); subscriber.eventQueue.poll(); // Drop the 5 value assertThat(subscriber.eventQueue.peek().get().type()).isEqualTo(EventType.ON_COMPLETE); assertThat(completeFuture).isCompletedWithValue(null); } @Test public void errorFuturesDoNotCompleteUntilAfterOnError() { RuntimeException error = new RuntimeException(); SimplePublisher<Integer> publisher = new SimplePublisher<>(); ControllableSubscriber<Integer> subscriber = new ControllableSubscriber<>(); publisher.subscribe(subscriber); publisher.send(5); CompletableFuture<Void> errorFuture = publisher.error(error); assertThat(subscriber.eventQueue.peek()).isNotPresent(); assertThat(errorFuture).isNotCompleted(); subscriber.subscription.request(1); subscriber.eventQueue.poll(); // Drop the 5 value assertThat(subscriber.eventQueue.peek().get().type()).isEqualTo(EventType.ON_ERROR); assertThat(subscriber.eventQueue.peek().get().runtimeError()).isEqualTo(error); assertThat(errorFuture).isCompletedWithValue(null); } @Test public void completeBeforeSubscribeIsDeliveredOnSubscribe() { SimplePublisher<Integer> publisher = new SimplePublisher<>(); StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(Integer.MAX_VALUE); publisher.complete(); publisher.subscribe(subscriber); assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_COMPLETE); } @Test public void errorBeforeSubscribeIsDeliveredOnSubscribe() { SimplePublisher<Integer> publisher = new SimplePublisher<>(); StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(Integer.MAX_VALUE); RuntimeException error = new RuntimeException(); publisher.error(error); publisher.subscribe(subscriber); assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_ERROR); assertThat(subscriber.peek().get().runtimeError()).isEqualTo(error); } @Test public void writeBeforeSubscribeIsDeliveredOnSubscribe() { SimplePublisher<Integer> publisher = new SimplePublisher<>(); StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(Integer.MAX_VALUE); publisher.send(5); publisher.subscribe(subscriber); assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_NEXT); assertThat(subscriber.peek().get().value()).isEqualTo(5); } @Test public void cancelFailsAnyInFlightFutures() { SimplePublisher<Integer> publisher = new SimplePublisher<>(); ControllableSubscriber<Integer> subscriber = new ControllableSubscriber<>(); publisher.subscribe(subscriber); CompletableFuture<Void> writeFuture = publisher.send(5); CompletableFuture<Void> completeFuture = publisher.complete(); subscriber.subscription.cancel(); assertThat(writeFuture).isCompletedExceptionally(); assertThat(completeFuture).isCompletedExceptionally(); } @Test public void newCallsAfterCancelFail() { SimplePublisher<Integer> publisher = new SimplePublisher<>(); ControllableSubscriber<Integer> subscriber = new ControllableSubscriber<>(); publisher.subscribe(subscriber); subscriber.subscription.cancel(); assertThat(publisher.send(5)).isCompletedExceptionally(); assertThat(publisher.complete()).isCompletedExceptionally(); assertThat(publisher.error(new Throwable())).isCompletedExceptionally(); } @Test public void negativeDemandSkipsOutstandingMessages() { SimplePublisher<Integer> publisher = new SimplePublisher<>(); ControllableSubscriber<Integer> subscriber = new ControllableSubscriber<>(); publisher.subscribe(subscriber); CompletableFuture<Void> sendFuture = publisher.send(0); CompletableFuture<Void> completeFuture = publisher.complete(); subscriber.subscription.request(-1); assertThat(sendFuture).isCompletedExceptionally(); assertThat(completeFuture).isCompletedExceptionally(); assertThat(subscriber.eventQueue.poll().get().type()).isEqualTo(EventType.ON_ERROR); } @Test public void evilDownstreamPublisherThrowingInOnNextStillCancelsInFlightFutures() { SimplePublisher<Integer> publisher = new SimplePublisher<>(); ControllableSubscriber<Integer> subscriber = new ControllableSubscriber<>(); subscriber.failureInOnNext = new RuntimeException(); CompletableFuture<Void> writeFuture = publisher.send(5); CompletableFuture<Void> completeFuture = publisher.complete(); publisher.subscribe(subscriber); subscriber.subscription.request(1); assertThat(writeFuture).isCompletedExceptionally(); assertThat(completeFuture).isCompletedExceptionally(); } @Test public void stochastic_onNext_singleProducerSeemsThreadSafe() throws Exception { // Single-producer is interesting because we can validate the ordering of messages, unlike with multi-producer. seemsThreadSafeWithProducerCount(1); } @Test public void stochastic_onNext_multiProducerSeemsThreadSafe() throws Exception { seemsThreadSafeWithProducerCount(3); } @Test public void stochastic_completeAndError_seemThreadSafe() throws Exception { assertTimeoutPreemptively(STOCHASTIC_TEST_DURATION.plusSeconds(5), () -> { Instant start = Instant.now(); Instant end = start.plus(STOCHASTIC_TEST_DURATION); ExecutorService executor = Executors.newCachedThreadPool(); while (end.isAfter(Instant.now())) { SimplePublisher<Integer> publisher = new SimplePublisher<>(); ControllableSubscriber<Integer> subscriber = new ControllableSubscriber<>(); publisher.subscribe(subscriber); subscriber.subscription.request(1); AtomicBoolean scenarioStart = new AtomicBoolean(false); CountDownLatch allAreWaiting = new CountDownLatch(3); Runnable waitForStart = () -> { allAreWaiting.countDown(); while (!scenarioStart.get()) { Thread.yield(); } }; Future<?> writeCall = executor.submit(() -> { waitForStart.run(); publisher.send(0).join(); }); Future<?> completeCall = executor.submit(() -> { waitForStart.run(); publisher.complete().join(); }); Future<?> errorCall = executor.submit(() -> { Throwable t = new Throwable(); waitForStart.run(); publisher.error(t).join(); }); allAreWaiting.await(); scenarioStart.set(true); List<Pair<String, Throwable>> failures = new ArrayList<>(); addIfFailed(failures, "write", writeCall); boolean writeSucceeded = failures.isEmpty(); addIfFailed(failures, "complete", completeCall); addIfFailed(failures, "error", errorCall); int expectedFailures = writeSucceeded ? 1 : 2; assertThat(failures).hasSize(expectedFailures); } }); } private void addIfFailed(List<Pair<String, Throwable>> failures, String callName, Future<?> call) { try { call.get(); } catch (Throwable t) { failures.add(Pair.of(callName, t)); } } private void seemsThreadSafeWithProducerCount(int producerCount) { assertTimeoutPreemptively(STOCHASTIC_TEST_DURATION.plusSeconds(5), () -> { AtomicBoolean runProducers = new AtomicBoolean(true); AtomicBoolean runConsumers = new AtomicBoolean(true); AtomicInteger completesReceived = new AtomicInteger(0); AtomicLong messageSendCount = new AtomicLong(0); AtomicLong messageReceiveCount = new AtomicLong(0); CountDownLatch producersDone = new CountDownLatch(producerCount); Semaphore productionLimiter = new Semaphore(101); Semaphore requestLimiter = new Semaphore(57); ExecutorService executor = Executors.newFixedThreadPool(2 + producerCount); SimplePublisher<Long> publisher = new SimplePublisher<>(); ControllableSubscriber<Long> subscriber = new ControllableSubscriber<>(); publisher.subscribe(subscriber); // Producer tasks CompletableFuture<?> completed = new CompletableFuture<>(); List<Future<?>> producers = new ArrayList<>(); for (int i = 0; i < producerCount; i++) { producers.add(executor.submit(() -> { while (runProducers.get()) { productionLimiter.acquire(); publisher.send(messageSendCount.getAndIncrement()); } // Complete once all producers are done producersDone.countDown(); producersDone.await(); publisher.complete().thenRun(() -> completed.complete(null)); // All but one producer sending this will fail. return null; })); } // Requester Task Future<?> requester = executor.submit(() -> { while (runConsumers.get()) { requestLimiter.acquire(); subscriber.subscription.request(1); } return null; }); // Consumer Task Future<?> consumer = executor.submit(() -> { int expectedEvent = 0; while (runConsumers.get() || subscriber.eventQueue.peek().isPresent()) { Optional<Event<Long>> event = subscriber.eventQueue.poll(); if (!event.isPresent()) { continue; } // When we only have 1 producer, we can verify the messages are in order. if (producerCount == 1 && event.get().type() == EventType.ON_NEXT) { assertThat(event.get().value()).isEqualTo(expectedEvent); expectedEvent++; } if (event.get().type() == EventType.ON_NEXT) { messageReceiveCount.incrementAndGet(); productionLimiter.release(); requestLimiter.release(); } if (event.get().type() == EventType.ON_COMPLETE) { completesReceived.incrementAndGet(); } } }); Thread.sleep(STOCHASTIC_TEST_DURATION.toMillis()); // Shut down producers runProducers.set(false); productionLimiter.release(producerCount); for (Future<?> producer : producers) { producer.get(); } // Make sure to flush out everything left in the queue. completed.get(); subscriber.subscription.request(Long.MAX_VALUE); // Shut down consumers runConsumers.set(false); requestLimiter.release(); requester.get(); consumer.get(); assertThat(messageReceiveCount.get()).isEqualTo(messageSendCount.get()); assertThat(completesReceived.get()).isEqualTo(1); // Make sure we actually tested something assertThat(messageSendCount.get()).isGreaterThan(10); }); } private class ControllableSubscriber<T> implements Subscriber<T> { private final StoringSubscriber<T> eventQueue = new StoringSubscriber<>(Integer.MAX_VALUE); private Subscription subscription; private RuntimeException failureInOnNext; @Override public void onSubscribe(Subscription s) { this.subscription = new ControllableSubscription(s); // Give the event queue a subscription we just ignore. We are the captain of the subscription! eventQueue.onSubscribe(new Subscription() { @Override public void request(long n) { } @Override public void cancel() { } }); } @Override public void onNext(T o) { if (failureInOnNext != null) { throw failureInOnNext; } eventQueue.onNext(o); } @Override public void onError(Throwable t) { eventQueue.onError(t); } @Override public void onComplete() { eventQueue.onComplete(); } private class ControllableSubscription implements Subscription { private final Subscription delegate; private ControllableSubscription(Subscription s) { delegate = s; } @Override public void request(long n) { delegate.request(n); } @Override public void cancel() { delegate.cancel(); } } } }
3,236
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/ByteBufferStoringSubscriberTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.reactivestreams.Subscription; import software.amazon.awssdk.utils.ThreadFactoryBuilder; import software.amazon.awssdk.utils.async.ByteBufferStoringSubscriber.TransferResult; public class ByteBufferStoringSubscriberTest { @Test public void constructorCalled_withNonPositiveSize_throwsException() { assertThatCode(() -> new ByteBufferStoringSubscriber(1)).doesNotThrowAnyException(); assertThatCode(() -> new ByteBufferStoringSubscriber(Integer.MAX_VALUE)).doesNotThrowAnyException(); assertThatThrownBy(() -> new ByteBufferStoringSubscriber(0)).isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> new ByteBufferStoringSubscriber(-1)).isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> new ByteBufferStoringSubscriber(Integer.MIN_VALUE)).isInstanceOf(IllegalArgumentException.class); } @Test public void doesNotRequestMoreThanMaxBytes() { ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(3); Subscription subscription = mock(Subscription.class); subscriber.onSubscribe(subscription); verify(subscription).request(1); subscriber.onNext(fullByteBufferOfSize(2)); verify(subscription, times(2)).request(1); subscriber.onNext(fullByteBufferOfSize(0)); verify(subscription, times(3)).request(1); subscriber.onNext(fullByteBufferOfSize(1)); verifyNoMoreInteractions(subscription); } @Test public void canStoreMoreThanMaxBytesButWontAskForMoreUntilBelowMax() { ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(3); Subscription subscription = mock(Subscription.class); subscriber.onSubscribe(subscription); verify(subscription).request(1); subscriber.onNext(fullByteBufferOfSize(1)); // After: Storing 1 verify(subscription, times(2)).request(1); // It should request more subscriber.onNext(fullByteBufferOfSize(50)); // After: Storing 51 subscriber.transferTo(emptyByteBufferOfSize(48)); // After: Storing 3 verifyNoMoreInteractions(subscription); // It should NOT request more subscriber.transferTo(emptyByteBufferOfSize(1)); // After: Storing 2 verify(subscription, times(3)).request(1); // It should request more } @Test @Timeout(10) public void blockingTransfer_waitsForFullOutputBuffer() throws InterruptedException, ExecutionException { int outputBufferSize = 256; ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().daemonThreads(true).build()); try { ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(1); Subscription subscription = mock(Subscription.class); AtomicInteger bufferNumber = new AtomicInteger(0); doAnswer(i -> { int bufferN = bufferNumber.getAndIncrement(); for (long j = 0; j < i.<Long>getArgument(0); j++) { if (bufferN <= outputBufferSize + 1) { subscriber.onNext(byteBufferWithContent(bufferN)); } } return null; }).when(subscription).request(anyLong()); subscriber.onSubscribe(subscription); Future<ByteBuffer> blockingRead = executor.submit(() -> { ByteBuffer out = ByteBuffer.allocate(outputBufferSize); TransferResult transferResult = subscriber.blockingTransferTo(out); assertThat(transferResult).isEqualTo(TransferResult.SUCCESS); return out; }); ByteBuffer output = blockingRead.get(); output.flip(); for (int i = 0; i < outputBufferSize; i++) { assertThat(output.get()).isEqualTo((byte) i); } } finally { executor.shutdownNow(); } } @Test @Timeout(10) public void blockingTransfer_stopsOnComplete() throws ExecutionException, InterruptedException { ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().daemonThreads(true).build()); try { ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(Long.MAX_VALUE); subscriber.onSubscribe(mock(Subscription.class)); Future<ByteBuffer> blockingRead = executor.submit(() -> { ByteBuffer out = ByteBuffer.allocate(1024); TransferResult transferResult = subscriber.blockingTransferTo(out); assertThat(transferResult).isEqualTo(TransferResult.END_OF_STREAM); return out; }); ByteBuffer input = fullByteBufferOfSize(1); subscriber.onNext(input); subscriber.onComplete(); ByteBuffer output = blockingRead.get(); output.flip(); assertThat(output.get()).isEqualTo(input.get()); } finally { executor.shutdownNow(); } } @Test @Timeout(10) public void blockingTransfer_stopsOnError() throws ExecutionException, InterruptedException { ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().daemonThreads(true).build()); try { ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(Long.MAX_VALUE); subscriber.onSubscribe(mock(Subscription.class)); Future<?> blockingRead = executor.submit(() -> { subscriber.blockingTransferTo(ByteBuffer.allocate(1024)); // Expected to throw return null; }); ByteBuffer input = fullByteBufferOfSize(1); IllegalStateException exception = new IllegalStateException(); subscriber.onNext(input); subscriber.onError(exception); assertThatThrownBy(blockingRead::get).hasRootCause(exception); } finally { executor.shutdownNow(); } } @Test @Timeout(10) public void blockingTransfer_stopsOnInterrupt() throws InterruptedException { ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(Long.MAX_VALUE); AtomicBoolean threadIsInterruptedInCatch = new AtomicBoolean(false); AtomicReference<Throwable> failureReason = new AtomicReference<>(); subscriber.onSubscribe(mock(Subscription.class)); CountDownLatch threadIsRunning = new CountDownLatch(1); Thread thread = new Thread(() -> { try { threadIsRunning.countDown(); subscriber.blockingTransferTo(ByteBuffer.allocate(1024)); } catch (Throwable t) { threadIsInterruptedInCatch.set(Thread.currentThread().isInterrupted()); failureReason.set(t); } }); thread.setDaemon(true); thread.start(); threadIsRunning.await(); thread.interrupt(); thread.join(); assertThat(threadIsInterruptedInCatch).isTrue(); assertThat(failureReason.get()).hasRootCauseInstanceOf(InterruptedException.class); } @Test @Timeout(10) public void blockingTransfer_returnsEndOfStreamWithRepeatedCalls() { ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(Long.MAX_VALUE); subscriber.onSubscribe(mock(Subscription.class)); subscriber.onComplete(); ByteBuffer buffer = ByteBuffer.allocate(0); assertThat(subscriber.blockingTransferTo(buffer)).isEqualTo(TransferResult.END_OF_STREAM); assertThat(subscriber.blockingTransferTo(buffer)).isEqualTo(TransferResult.END_OF_STREAM); assertThat(subscriber.blockingTransferTo(buffer)).isEqualTo(TransferResult.END_OF_STREAM); } @Test public void noDataTransferredIfNoDataBuffered() { ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(2); subscriber.onSubscribe(mock(Subscription.class)); ByteBuffer out = emptyByteBufferOfSize(1); assertThat(subscriber.transferTo(out)).isEqualTo(TransferResult.SUCCESS); assertThat(out.remaining()).isEqualTo(1); } @Test public void noDataTransferredIfComplete() { ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(2); subscriber.onSubscribe(mock(Subscription.class)); subscriber.onComplete(); ByteBuffer out = emptyByteBufferOfSize(1); assertThat(subscriber.transferTo(out)).isEqualTo(TransferResult.END_OF_STREAM); assertThat(out.remaining()).isEqualTo(1); } @Test public void noDataTransferredIfError() { RuntimeException error = new RuntimeException(); ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(2); subscriber.onSubscribe(mock(Subscription.class)); subscriber.onError(error); ByteBuffer out = emptyByteBufferOfSize(1); assertThatThrownBy(() -> subscriber.transferTo(out)).isEqualTo(error); assertThat(out.remaining()).isEqualTo(1); } @Test public void checkedExceptionsAreWrapped() { Exception error = new Exception(); ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(2); subscriber.onSubscribe(mock(Subscription.class)); subscriber.onError(error); ByteBuffer out = emptyByteBufferOfSize(1); assertThatThrownBy(() -> subscriber.transferTo(out)).hasCause(error); assertThat(out.remaining()).isEqualTo(1); } @Test public void completeIsReportedEvenWithExactOutSize() { ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(2); subscriber.onSubscribe(mock(Subscription.class)); subscriber.onNext(fullByteBufferOfSize(2)); subscriber.onComplete(); ByteBuffer out = emptyByteBufferOfSize(2); assertThat(subscriber.transferTo(out)).isEqualTo(TransferResult.END_OF_STREAM); assertThat(out.remaining()).isEqualTo(0); } @Test public void completeIsReportedEvenWithExtraOutSize() { ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(2); subscriber.onSubscribe(mock(Subscription.class)); subscriber.onNext(fullByteBufferOfSize(2)); subscriber.onComplete(); ByteBuffer out = emptyByteBufferOfSize(3); assertThat(subscriber.transferTo(out)).isEqualTo(TransferResult.END_OF_STREAM); assertThat(out.remaining()).isEqualTo(1); } @Test public void errorIsReportedEvenWithExactOutSize() { RuntimeException error = new RuntimeException(); ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(2); subscriber.onSubscribe(mock(Subscription.class)); subscriber.onNext(fullByteBufferOfSize(2)); subscriber.onError(error); ByteBuffer out = emptyByteBufferOfSize(2); assertThatThrownBy(() -> subscriber.transferTo(out)).isEqualTo(error); assertThat(out.remaining()).isEqualTo(0); } @Test public void errorIsReportedEvenWithExtraOutSize() { RuntimeException error = new RuntimeException(); ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(2); subscriber.onSubscribe(mock(Subscription.class)); subscriber.onNext(fullByteBufferOfSize(2)); subscriber.onError(error); ByteBuffer out = emptyByteBufferOfSize(3); assertThatThrownBy(() -> subscriber.transferTo(out)).isEqualTo(error); assertThat(out.remaining()).isEqualTo(1); } @Test public void dataIsDeliveredInTheRightOrder() { ByteBuffer buffer1 = fullByteBufferOfSize(1); ByteBuffer buffer2 = fullByteBufferOfSize(1); ByteBuffer buffer3 = fullByteBufferOfSize(1); ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(3); subscriber.onSubscribe(mock(Subscription.class)); subscriber.onNext(buffer1); subscriber.onNext(buffer2); subscriber.onNext(buffer3); subscriber.onComplete(); ByteBuffer out = emptyByteBufferOfSize(4); subscriber.transferTo(out); out.flip(); assertThat(out.get()).isEqualTo(buffer1.get()); assertThat(out.get()).isEqualTo(buffer2.get()); assertThat(out.get()).isEqualTo(buffer3.get()); assertThat(out.hasRemaining()).isFalse(); } @Test @Timeout(30) public void stochastic_subscriberSeemsThreadSafe() throws Throwable { ExecutorService producer = Executors.newFixedThreadPool(1); ExecutorService consumer = Executors.newFixedThreadPool(1); try { ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(50); AtomicBoolean testRunning = new AtomicBoolean(true); AtomicInteger messageNumber = new AtomicInteger(0); AtomicReference<Throwable> producerFailure = new AtomicReference<>(); Subscription subscription = new Subscription() { @Override public void request(long n) { producer.submit(() -> { try { for (int i = 0; i < n; i++) { ByteBuffer buffer = ByteBuffer.allocate(4); buffer.putInt(messageNumber.getAndIncrement()); buffer.flip(); subscriber.onNext(buffer); } } catch (Throwable t) { producerFailure.set(t); } }); } @Override public void cancel() { producerFailure.set(new AssertionError("Cancel not expected.")); } }; subscriber.onSubscribe(subscription); Future<Object> consumerFuture = consumer.submit(() -> { ByteBuffer carryOver = ByteBuffer.allocate(4); int expectedMessageNumber = 0; while (testRunning.get()) { Thread.sleep(1); ByteBuffer out = ByteBuffer.allocate(4 + expectedMessageNumber); subscriber.transferTo(out); out.flip(); if (carryOver.position() > 0) { int oldOutLimit = out.limit(); out.limit(carryOver.remaining()); carryOver.put(out); out.limit(oldOutLimit); carryOver.flip(); assertThat(carryOver.getInt()).isEqualTo(expectedMessageNumber); ++expectedMessageNumber; carryOver.clear(); } while (out.remaining() >= 4) { assertThat(out.getInt()).isEqualTo(expectedMessageNumber); ++expectedMessageNumber; } if (out.hasRemaining()) { carryOver.put(out); } } return null; }); Thread.sleep(5_000); testRunning.set(false); consumerFuture.get(); if (producerFailure.get() != null) { throw producerFailure.get(); } assertThat(messageNumber.get()).isGreaterThan(10); // ensure we actually tested something } finally { producer.shutdownNow(); consumer.shutdownNow(); } } @Test @Timeout(30) public void stochastic_blockingTransferSeemsThreadSafe() throws Throwable { ExecutorService producer = Executors.newFixedThreadPool(1); ExecutorService consumer = Executors.newFixedThreadPool(1); try { ByteBufferStoringSubscriber subscriber = new ByteBufferStoringSubscriber(50); AtomicBoolean testRunning = new AtomicBoolean(true); AtomicInteger messageNumber = new AtomicInteger(0); AtomicReference<Throwable> producerFailure = new AtomicReference<>(); Subscription subscription = new Subscription() { @Override public void request(long n) { producer.submit(() -> { if (!testRunning.get()) { return; } try { for (int i = 0; i < n; i++) { ByteBuffer buffer = ByteBuffer.allocate(4); buffer.putInt(messageNumber.getAndIncrement()); buffer.flip(); subscriber.onNext(buffer); } } catch (Throwable t) { producerFailure.set(t); } }); } @Override public void cancel() { producerFailure.set(new AssertionError("Cancel not expected.")); } }; subscriber.onSubscribe(subscription); Future<Object> consumerFuture = consumer.submit(() -> { int expectedMessageNumber = 0; while (testRunning.get()) { ByteBuffer out = ByteBuffer.allocate(12); // 4 integers at a time seems good subscriber.blockingTransferTo(out); out.flip(); while (out.hasRemaining()) { assertThat(out.getInt()).isEqualTo(expectedMessageNumber); ++expectedMessageNumber; } } return null; }); Thread.sleep(5_000); testRunning.set(false); producer.submit(subscriber::onComplete); consumerFuture.get(); if (producerFailure.get() != null) { throw producerFailure.get(); } assertThat(messageNumber.get()).isGreaterThan(10); // ensure we actually tested something } finally { producer.shutdownNow(); consumer.shutdownNow(); } } private ByteBuffer fullByteBufferOfSize(int size) { byte[] data = new byte[size]; ThreadLocalRandom.current().nextBytes(data); return ByteBuffer.wrap(data); } private ByteBuffer byteBufferWithContent(int b) { return ByteBuffer.wrap(new byte[] { (byte) b }); } private ByteBuffer emptyByteBufferOfSize(int size) { return ByteBuffer.allocate(size); } }
3,237
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/InputStreamConsumingPublisherTckTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.reactivestreams.Publisher; import org.reactivestreams.tck.PublisherVerification; import org.reactivestreams.tck.TestEnvironment; import software.amazon.awssdk.utils.ThreadFactoryBuilder; public class InputStreamConsumingPublisherTckTest extends PublisherVerification<ByteBuffer> { private final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().daemonThreads(true).build()); public InputStreamConsumingPublisherTckTest() { super(new TestEnvironment()); } @Override public Publisher<ByteBuffer> createPublisher(long elements) { InputStreamConsumingPublisher publisher = new InputStreamConsumingPublisher(); executor.submit(() -> { publisher.doBlockingWrite(new InputStream() { int i = 0; @Override public int read() throws IOException { throw new IOException(); } @Override public int read(byte[] b) throws IOException { if (i >= elements) { return -1; } ++i; assert b.length > 0; return 1; } }); }); return publisher; } @Override public Publisher<ByteBuffer> createFailedPublisher() { InputStreamConsumingPublisher publisher = new InputStreamConsumingPublisher(); executor.submit(publisher::cancel); return publisher; } }
3,238
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/InputStreamSubscriberTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CancellationException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.function.Consumer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.utils.ThreadFactoryBuilder; public class InputStreamSubscriberTest { private SimplePublisher<ByteBuffer> publisher; private InputStreamSubscriber subscriber; @BeforeEach public void setup() { publisher = new SimplePublisher<>(); subscriber = new InputStreamSubscriber(); } @Test public void onComplete_returnsEndOfStream_onRead() { publisher.subscribe(subscriber); publisher.complete(); assertThat(subscriber.read()).isEqualTo(-1); assertThat(subscriber.read(new byte[1])).isEqualTo(-1); assertThat(subscriber.read(new byte[1], 0, 1)).isEqualTo(-1); } @Test public void onError_throws_onRead() { IllegalStateException exception = new IllegalStateException(); publisher.subscribe(subscriber); publisher.error(exception); assertThatThrownBy(() -> subscriber.read()).isEqualTo(exception); assertThatThrownBy(() -> subscriber.read(new byte[1])).isEqualTo(exception); assertThatThrownBy(() -> subscriber.read(new byte[1], 0, 1)).isEqualTo(exception); } @Test public void onComplete_afterOnNext_returnsEndOfStream() { publisher.subscribe(subscriber); publisher.send(byteBufferOfLength(1)); publisher.complete(); assertThat(subscriber.read()).isEqualTo(0); assertThat(subscriber.read()).isEqualTo(-1); } @Test public void onComplete_afterEmptyOnNext_returnsEndOfStream() { publisher.subscribe(subscriber); publisher.send(byteBufferOfLength(0)); publisher.send(byteBufferOfLength(0)); publisher.send(byteBufferOfLength(0)); publisher.complete(); assertThat(subscriber.read()).isEqualTo(-1); } @Test public void read_afterOnNext_returnsData() { publisher.subscribe(subscriber); publisher.send(byteBufferWithByte(10)); assertThat(subscriber.read()).isEqualTo(10); } @Test public void readBytes_afterOnNext_returnsData() { publisher.subscribe(subscriber); publisher.send(byteBufferWithByte(10)); publisher.send(byteBufferWithByte(20)); byte[] bytes = new byte[2]; assertThat(subscriber.read(bytes)).isEqualTo(2); assertThat(bytes[0]).isEqualTo((byte) 10); assertThat(bytes[1]).isEqualTo((byte) 20); } @Test public void readBytesWithOffset_afterOnNext_returnsData() { publisher.subscribe(subscriber); publisher.send(byteBufferWithByte(10)); publisher.send(byteBufferWithByte(20)); byte[] bytes = new byte[3]; assertThat(subscriber.read(bytes, 1, 2)).isEqualTo(2); assertThat(bytes[1]).isEqualTo((byte) 10); assertThat(bytes[2]).isEqualTo((byte) 20); } @Test public void read_afterClose_fails() { publisher.subscribe(subscriber); subscriber.close(); assertThatThrownBy(() -> subscriber.read()).isInstanceOf(CancellationException.class); assertThatThrownBy(() -> subscriber.read(new byte[1])).isInstanceOf(CancellationException.class); assertThatThrownBy(() -> subscriber.read(new byte[1], 0, 1)).isInstanceOf(CancellationException.class); } @Test public void readByteArray_0Len_returns0() { publisher.subscribe(subscriber); assertThat(subscriber.read(new byte[1], 0, 0)).isEqualTo(0); } public static List<Arguments> stochastic_methodCallsSeemThreadSafe_parameters() { Object[][] inputStreamOperations = { { "read();", subscriberRead1() }, { "read(); close();", subscriberRead1().andThen(subscriberClose()) }, { "read(byte[]); close();", subscriberReadArray().andThen(subscriberClose()) }, { "read(byte[]); read(byte[]);", subscriberReadArray().andThen(subscriberReadArray()) } }; Object[][] publisherOperations = { { "onNext(...);", subscriberOnNext() }, { "onNext(...); onComplete();", subscriberOnNext().andThen(subscriberOnComplete()) }, { "onNext(...); onError(...);", subscriberOnNext().andThen(subscriberOnError()) }, { "onComplete();", subscriberOnComplete() }, { "onError(...);", subscriberOnError() } }; List<Arguments> result = new ArrayList<>(); for (Object[] iso : inputStreamOperations) { for (Object[] po : publisherOperations) { result.add(Arguments.of(iso[1], po[1], iso[0] + " and " + po[0] + " in parallel")); } } return result; } @ParameterizedTest(name = "{2}") @MethodSource("stochastic_methodCallsSeemThreadSafe_parameters") @Timeout(10) public void stochastic_methodCallsSeemThreadSafe(Consumer<InputStreamSubscriber> inputStreamOperation, Consumer<InputStreamSubscriber> publisherOperation, String testName) throws InterruptedException, ExecutionException { int numIterations = 100; // Read/close aren't mutually thread safe, and onNext/onComplete/onError aren't mutually thread safe, but one // group of functions might be executed in parallel with the others. We try to make sure that this is safe. ExecutorService executor = Executors.newFixedThreadPool(10, new ThreadFactoryBuilder().daemonThreads(true).build()); try { List<Future<?>> futures = new ArrayList<>(); for (int i = 0; i < numIterations; i++) { CountDownLatch waitingAtStartLine = new CountDownLatch(2); CountDownLatch startLine = new CountDownLatch(1); InputStreamSubscriber subscriber = new InputStreamSubscriber(); subscriber.onSubscribe(mockSubscription(subscriber)); futures.add(executor.submit(() -> { waitingAtStartLine.countDown(); startLine.await(); inputStreamOperation.accept(subscriber); return null; })); futures.add(executor.submit(() -> { waitingAtStartLine.countDown(); startLine.await(); publisherOperation.accept(subscriber); return null; })); waitingAtStartLine.await(); startLine.countDown(); } for (Future<?> future : futures) { future.get(); } } finally { executor.shutdownNow(); } } public static Consumer<InputStreamSubscriber> subscriberOnNext() { return s -> s.onNext(ByteBuffer.allocate(1)); } public static Consumer<InputStreamSubscriber> subscriberOnComplete() { return s -> s.onComplete(); } public static Consumer<InputStreamSubscriber> subscriberOnError() { return s -> s.onError(new Throwable()); } public static Consumer<InputStreamSubscriber> subscriberRead1() { return s -> s.read(); } public static Consumer<InputStreamSubscriber> subscriberReadArray() { return s -> s.read(new byte[4]); } public static Consumer<InputStreamSubscriber> subscriberClose() { return s -> s.close(); } private Subscription mockSubscription(Subscriber<ByteBuffer> subscriber) { Subscription subscription = mock(Subscription.class); doAnswer(new Answer<Void>() { boolean done = false; @Override public Void answer(InvocationOnMock invocation) { if (!done) { subscriber.onNext(ByteBuffer.wrap(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 })); subscriber.onComplete(); done = true; } return null; } }).when(subscription).request(anyLong()); return subscription; } private ByteBuffer byteBufferOfLength(int length) { return ByteBuffer.allocate(length); } public ByteBuffer byteBufferWithByte(int b) { ByteBuffer buffer = ByteBuffer.allocate(1); buffer.put((byte) b); buffer.flip(); return buffer; } }
3,239
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/OutputStreamPublisherTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.ByteBuffer; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import software.amazon.awssdk.utils.ThreadFactoryBuilder; import software.amazon.awssdk.utils.async.ByteBufferStoringSubscriber.TransferResult; public class OutputStreamPublisherTest { private StoringSubscriber<ByteBuffer> storingSubscriber; private ByteBufferStoringSubscriber byteStoringSubscriber; private OutputStreamPublisher publisher; @BeforeEach public void setup() { storingSubscriber = new StoringSubscriber<>(Integer.MAX_VALUE); byteStoringSubscriber = new ByteBufferStoringSubscriber(Integer.MAX_VALUE); publisher = new OutputStreamPublisher(); } @Test public void oneByteWritesAreBuffered() { publisher.subscribe(storingSubscriber); publisher.write(0); assertThat(storingSubscriber.poll()).isNotPresent(); } @Test public void oneByteWritesAreFlushedEventually() { publisher.subscribe(storingSubscriber); for (int i = 0; i < 1024 * 1024; i++) { publisher.write(0); } assertThat(storingSubscriber.poll()).hasValueSatisfying(e -> { assertThat(e.value().get()).isEqualTo((byte) 0); }); } @Test public void flushDrainsBufferedBytes() { publisher.subscribe(storingSubscriber); publisher.write(0); publisher.flush(); assertThat(storingSubscriber.poll()).hasValueSatisfying(v -> { assertThat(v.value().remaining()).isEqualTo(1); }); } @Test public void emptyFlushDoesNothing() { publisher.subscribe(storingSubscriber); publisher.flush(); assertThat(storingSubscriber.poll()).isNotPresent(); } @Test public void oneByteWritesAreSentInOrder() { publisher.subscribe(storingSubscriber); for (int i = 0; i < 256; i++) { publisher.write(i); } publisher.flush(); assertThat(storingSubscriber.poll()).hasValueSatisfying(e -> { assertThat(e.value().get()).isEqualTo((byte) 0); }); } @Test @Timeout(30) public void writesBeforeSubscribeBlockUntilSubscribe() throws InterruptedException, ExecutionException { ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().daemonThreads(true).build()); try { Future<?> writes = executor.submit(() -> { publisher.write(new byte[256]); publisher.close(); }); Thread.sleep(200); assertThat(storingSubscriber.poll()).isNotPresent(); assertThat(writes.isDone()).isFalse(); publisher.subscribe(storingSubscriber); assertThat(storingSubscriber.poll()).isPresent(); writes.get(); } finally { executor.shutdownNow(); } } @Test public void mixedWriteTypesAreSentInOrder() { publisher.subscribe(byteStoringSubscriber); AtomicInteger i = new AtomicInteger(0); writeByte(i); writeBytes(i); writeOffsetBytes(i); writeByte(i); writeOffsetBytes(i); writeBytes(i); writeBytes(i); writeByte(i); writeOffsetBytes(i); writeBytes(i); writeOffsetBytes(i); writeByte(i); writeOffsetBytes(i); writeByte(i); writeBytes(i); writeOffsetBytes(i); writeByte(i); writeBytes(i); publisher.close(); ByteBuffer out = ByteBuffer.allocate(i.get() + 1); assertThat(byteStoringSubscriber.blockingTransferTo(out)).isEqualTo(TransferResult.END_OF_STREAM); out.flip(); for (int j = 0; j < i.get(); j++) { assertThat(out.get()).isEqualTo((byte) j); } } @Test public void cancel_preventsSingleByteWrites() { publisher.subscribe(byteStoringSubscriber); publisher.cancel(); assertThatThrownBy(() -> publisher.write(1)).isInstanceOf(IllegalStateException.class); } @Test public void cancel_preventsMultiByteWrites() { publisher.subscribe(byteStoringSubscriber); publisher.cancel(); assertThatThrownBy(() -> publisher.write(new byte[8])).hasRootCauseInstanceOf(IllegalStateException.class); } @Test public void cancel_preventsOffsetByteWrites() { publisher.subscribe(byteStoringSubscriber); publisher.cancel(); assertThatThrownBy(() -> publisher.write(new byte[8], 0, 1)).hasRootCauseInstanceOf(IllegalStateException.class); } @Test public void close_preventsSingleByteWrites() { publisher.subscribe(byteStoringSubscriber); publisher.close(); assertThatThrownBy(() -> publisher.write(1)).isInstanceOf(IllegalStateException.class); } @Test public void close_preventsMultiByteWrites() { publisher.subscribe(byteStoringSubscriber); publisher.close(); assertThatThrownBy(() -> publisher.write(new byte[8])).hasRootCauseInstanceOf(IllegalStateException.class); } @Test public void close_preventsOffsetByteWrites() { publisher.subscribe(byteStoringSubscriber); publisher.close(); assertThatThrownBy(() -> publisher.write(new byte[8], 0, 1)).hasRootCauseInstanceOf(IllegalStateException.class); } private void writeByte(AtomicInteger i) { publisher.write(i.getAndIncrement()); } private void writeBytes(AtomicInteger i) { publisher.write(new byte[] { (byte) i.getAndIncrement(), (byte) i.getAndIncrement() }); } private void writeOffsetBytes(AtomicInteger i) { publisher.write(new byte[] { 0, 0, (byte) i.getAndIncrement(), (byte) i.getAndIncrement(), (byte) i.getAndIncrement() }, 2, 3); } }
3,240
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/InputStreamSubscriberTckTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import java.nio.ByteBuffer; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import org.reactivestreams.tck.SubscriberWhiteboxVerification; import org.reactivestreams.tck.TestEnvironment; public class InputStreamSubscriberTckTest extends SubscriberWhiteboxVerification<ByteBuffer> { protected InputStreamSubscriberTckTest() { super(new TestEnvironment()); } @Override public Subscriber<ByteBuffer> createSubscriber(WhiteboxSubscriberProbe<ByteBuffer> probe) { return new ByteBufferStoringSubscriber(16) { @Override public void onError(Throwable throwable) { super.onError(throwable); probe.registerOnError(throwable); } @Override public void onSubscribe(Subscription subscription) { super.onSubscribe(subscription); probe.registerOnSubscribe(new SubscriberPuppet() { @Override public void triggerRequest(long elements) { subscription.request(elements); } @Override public void signalCancel() { subscription.cancel(); } }); } @Override public void onNext(ByteBuffer next) { super.onNext(next); probe.registerOnNext(next); } @Override public void onComplete() { super.onComplete(); probe.registerOnComplete(); } }; } @Override public ByteBuffer createElement(int element) { return ByteBuffer.wrap(new byte[0]); } }
3,241
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/StoringSubscriberTckTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import org.reactivestreams.tck.SubscriberWhiteboxVerification; import org.reactivestreams.tck.TestEnvironment; public class StoringSubscriberTckTest extends SubscriberWhiteboxVerification<Integer> { protected StoringSubscriberTckTest() { super(new TestEnvironment()); } @Override public Subscriber<Integer> createSubscriber(WhiteboxSubscriberProbe<Integer> probe) { return new StoringSubscriber<Integer>(16) { @Override public void onError(Throwable throwable) { super.onError(throwable); probe.registerOnError(throwable); } @Override public void onSubscribe(Subscription subscription) { super.onSubscribe(subscription); probe.registerOnSubscribe(new SubscriberPuppet() { @Override public void triggerRequest(long elements) { subscription.request(elements); } @Override public void signalCancel() { subscription.cancel(); } }); } @Override public void onNext(Integer nextItems) { super.onNext(nextItems); probe.registerOnNext(nextItems); } @Override public void onComplete() { super.onComplete(); probe.registerOnComplete(); } }; } @Override public Integer createElement(int element) { return element; } }
3,242
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/BufferingSubscriberTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.util.stream.IntStream; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; @RunWith(MockitoJUnitRunner.class) public class BufferingSubscriberTest { private static final int BUFFER_SIZE = 6; private static final Object data = new Object(); @Mock private Subscriber mockSubscriber; @Mock private Subscription mockSubscription; private Subscriber bufferingSubscriber; @Before public void setup() { doNothing().when(mockSubscriber).onSubscribe(any()); doNothing().when(mockSubscriber).onNext(any()); doNothing().when(mockSubscriber).onComplete(); doNothing().when(mockSubscription).request(anyLong()); bufferingSubscriber = new BufferingSubscriber(mockSubscriber, BUFFER_SIZE); bufferingSubscriber.onSubscribe(mockSubscription); } @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()); } @Test public void onNextIsCalled_DuringOnComplete_WhenBufferNotEmpty() { int count = 8; callOnNext(count); bufferingSubscriber.onComplete(); verify(mockSubscriber, times(count/BUFFER_SIZE + 1)).onNext(any()); } private void callOnNext(int times) { IntStream.range(0, times).forEach(i -> bufferingSubscriber.onNext(data)); } }
3,243
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/StoringSubscriberTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.reactivestreams.Subscription; import software.amazon.awssdk.utils.async.StoringSubscriber.Event; import software.amazon.awssdk.utils.async.StoringSubscriber.EventType; public class StoringSubscriberTest { @Test public void constructorCalled_withNonPositiveSize_throwsException() { assertThatCode(() -> new StoringSubscriber<>(1)).doesNotThrowAnyException(); assertThatCode(() -> new StoringSubscriber<>(Integer.MAX_VALUE)).doesNotThrowAnyException(); assertThatThrownBy(() -> new StoringSubscriber<>(0)).isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> new StoringSubscriber<>(-1)).isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> new StoringSubscriber<>(Integer.MIN_VALUE)).isInstanceOf(IllegalArgumentException.class); } @Test public void doesNotStoreMoreThanMaxElements() { StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(2); Subscription subscription = mock(Subscription.class); subscriber.onSubscribe(subscription); verify(subscription).request(2); subscriber.onNext(0); subscriber.onNext(0); subscriber.peek(); verifyNoMoreInteractions(subscription); subscriber.poll(); subscriber.poll(); verify(subscription, times(2)).request(1); assertThat(subscriber.peek()).isNotPresent(); verifyNoMoreInteractions(subscription); } @Test public void returnsEmptyEventWithOutstandingDemand() { StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(2); subscriber.onSubscribe(mock(Subscription.class)); assertThat(subscriber.peek()).isNotPresent(); } @Test public void returnsCompleteOnComplete() { StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(2); subscriber.onSubscribe(mock(Subscription.class)); subscriber.onComplete(); assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_COMPLETE); } @Test public void returnsErrorOnError() { RuntimeException error = new RuntimeException(); StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(2); subscriber.onSubscribe(mock(Subscription.class)); subscriber.onError(error); assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_ERROR); assertThat(subscriber.peek().get().runtimeError()).isEqualTo(error); } @Test public void errorWrapsCheckedExceptions() { Exception error = new Exception(); StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(2); subscriber.onSubscribe(mock(Subscription.class)); subscriber.onError(error); assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_ERROR); assertThat(subscriber.peek().get().runtimeError()).hasCause(error); } @Test public void deliversMessagesInTheCorrectOrder() { StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(2); Subscription subscription = mock(Subscription.class); subscriber.onSubscribe(subscription); subscriber.onNext(1); subscriber.onNext(2); subscriber.onComplete(); assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_NEXT); assertThat(subscriber.peek().get().value()).isEqualTo(1); subscriber.poll(); assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_NEXT); assertThat(subscriber.peek().get().value()).isEqualTo(2); subscriber.poll(); assertThat(subscriber.peek().get().type()).isEqualTo(EventType.ON_COMPLETE); subscriber.poll(); assertThat(subscriber.peek()).isNotPresent(); } @Test @Timeout(30) public void stochastic_subscriberSeemsThreadSafe() throws Throwable { ExecutorService producer = Executors.newFixedThreadPool(1); ExecutorService consumer = Executors.newFixedThreadPool(1); try { StoringSubscriber<Integer> subscriber = new StoringSubscriber<>(10); AtomicBoolean testRunning = new AtomicBoolean(true); AtomicInteger messageNumber = new AtomicInteger(0); AtomicReference<Throwable> producerFailure = new AtomicReference<>(); Subscription subscription = new Subscription() { @Override public void request(long n) { producer.submit(() -> { try { for (int i = 0; i < n; i++) { subscriber.onNext(messageNumber.getAndIncrement()); } } catch (Throwable t) { producerFailure.set(t); } }); } @Override public void cancel() { producerFailure.set(new AssertionError("Cancel not expected.")); } }; subscriber.onSubscribe(subscription); Future<Object> consumerFuture = consumer.submit(() -> { int expectedMessageNumber = 0; while (testRunning.get()) { Thread.sleep(1); Optional<Event<Integer>> current = subscriber.peek(); Optional<Event<Integer>> current2 = subscriber.peek(); if (current.isPresent()) { assertThat(current.get()).isSameAs(current2.get()); Event<Integer> event = current.get(); assertThat(event.type()).isEqualTo(EventType.ON_NEXT); assertThat(event.value()).isEqualTo(expectedMessageNumber); expectedMessageNumber++; } subscriber.poll(); } return null; }); Thread.sleep(5_000); testRunning.set(false); consumerFuture.get(); if (producerFailure.get() != null) { throw producerFailure.get(); } assertThat(messageNumber.get()).isGreaterThan(10); // ensure we actually tested something } finally { producer.shutdownNow(); consumer.shutdownNow(); } } }
3,244
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/FlatteningSubscriberTckTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import java.util.Arrays; import java.util.concurrent.CompletableFuture; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import org.reactivestreams.tck.SubscriberWhiteboxVerification; import org.reactivestreams.tck.TestEnvironment; public class FlatteningSubscriberTckTest extends SubscriberWhiteboxVerification<Iterable<Integer>> { protected FlatteningSubscriberTckTest() { super(new TestEnvironment()); } @Override public Subscriber<Iterable<Integer>> createSubscriber(WhiteboxSubscriberProbe<Iterable<Integer>> probe) { Subscriber<Integer> foo = new SequentialSubscriber<>(s -> {}, new CompletableFuture<>()); return new FlatteningSubscriber<Integer>(foo) { @Override public void onError(Throwable throwable) { super.onError(throwable); probe.registerOnError(throwable); } @Override public void onSubscribe(Subscription subscription) { super.onSubscribe(subscription); probe.registerOnSubscribe(new SubscriberPuppet() { @Override public void triggerRequest(long elements) { subscription.request(elements); } @Override public void signalCancel() { subscription.cancel(); } }); } @Override public void onNext(Iterable<Integer> nextItems) { super.onNext(nextItems); probe.registerOnNext(nextItems); } @Override public void onComplete() { super.onComplete(); probe.registerOnComplete(); } }; } @Override public Iterable<Integer> createElement(int element) { return Arrays.asList(element, element); } }
3,245
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/async/AddingTrailingDataSubscriberTckTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import java.util.Arrays; import java.util.concurrent.CompletableFuture; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import org.reactivestreams.tck.SubscriberWhiteboxVerification; import org.reactivestreams.tck.TestEnvironment; public class AddingTrailingDataSubscriberTckTest extends SubscriberWhiteboxVerification<Integer> { protected AddingTrailingDataSubscriberTckTest() { super(new TestEnvironment()); } @Override public Subscriber<Integer> createSubscriber(WhiteboxSubscriberProbe<Integer> probe) { Subscriber<Integer> foo = new SequentialSubscriber<>(s -> {}, new CompletableFuture<>()); return new AddingTrailingDataSubscriber<Integer>(foo, () -> Arrays.asList(0, 1, 2)) { @Override public void onError(Throwable throwable) { super.onError(throwable); probe.registerOnError(throwable); } @Override public void onSubscribe(Subscription subscription) { super.onSubscribe(subscription); probe.registerOnSubscribe(new SubscriberPuppet() { @Override public void triggerRequest(long elements) { subscription.request(elements); } @Override public void signalCancel() { subscription.cancel(); } }); } @Override public void onNext(Integer nextItem) { super.onNext(nextItem); probe.registerOnNext(nextItem); } @Override public void onComplete() { super.onComplete(); probe.registerOnComplete(); } }; } @Override public Integer createElement(int i) { return i; } }
3,246
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/internal/SystemSettingUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.internal; import static org.assertj.core.api.Java6Assertions.assertThat; import org.junit.jupiter.api.Test; import software.amazon.awssdk.utils.SystemSetting; public class SystemSettingUtilsTest { @Test public void resolveNonDefaultSetting_doesNotReturnDefaultValue() { TestSystemSetting setting = new TestSystemSetting("prop", "env", "default"); assertThat(SystemSettingUtils.resolveNonDefaultSetting(setting).isPresent()).isFalse(); } private static class TestSystemSetting implements SystemSetting { private final String property; private final String environmentVariable; private final String defaultValue; public TestSystemSetting(String property, String environmentVariable, String defaultValue) { this.property = property; this.environmentVariable = environmentVariable; this.defaultValue = defaultValue; } @Override public String property() { return property; } @Override public String environmentVariable() { return environmentVariable; } @Override public String defaultValue() { return defaultValue; } } }
3,247
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/internal/ReflectionUtilsTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.internal; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import org.junit.jupiter.api.Test; public class ReflectionUtilsTest { @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))); } }
3,248
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/internal/MappingSubscriberTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.internal; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; @RunWith(MockitoJUnitRunner.class) public class MappingSubscriberTest { @Mock private Subscription mockSubscription; @Mock private Subscriber<String> mockSubscriber; @Test public void verifyNormalFlow() { MappingSubscriber<String, String> mappingSubscriber = MappingSubscriber.create(mockSubscriber, String::toUpperCase); mappingSubscriber.onSubscribe(mockSubscription); verify(mockSubscriber).onSubscribe(mockSubscription); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); mappingSubscriber.onNext("one"); verify(mockSubscriber).onNext("ONE"); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); mappingSubscriber.onNext("two"); verify(mockSubscriber).onNext("TWO"); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); mappingSubscriber.onComplete(); verify(mockSubscriber).onComplete(); verifyNoMoreInteractions(mockSubscriber); } @Test public void verifyMappingExceptionFlow() { RuntimeException exception = new IllegalArgumentException("Twos are not supported"); MappingSubscriber<String, String> mappingSubscriber = MappingSubscriber.create(mockSubscriber, s -> { if ("two".equals(s)) { throw exception; } return s.toUpperCase(); }); mappingSubscriber.onSubscribe(mockSubscription); verify(mockSubscriber).onSubscribe(mockSubscription); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); mappingSubscriber.onNext("one"); verify(mockSubscriber).onNext("ONE"); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); mappingSubscriber.onNext("two"); verify(mockSubscriber).onError(exception); verifyNoMoreInteractions(mockSubscriber); verify(mockSubscription).cancel(); reset(mockSubscriber); mappingSubscriber.onNext("three"); verifyNoMoreInteractions(mockSubscriber); reset(mockSubscriber); mappingSubscriber.onComplete(); verifyNoMoreInteractions(mockSubscriber); } }
3,249
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/utils/builder/CopyableBuilderTest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.builder; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; public class CopyableBuilderTest { @Test public void canApplyAFunctionToTheBuilder() { ClassToBuild builtClass = ClassToBuild.builder().name("jeffery").applyMutation(this::upperCaseName).build(); assertThat(builtClass.name).isEqualTo("JEFFERY"); } @Test public void canCopyABuilder() { ClassToBuild.Builder builder = ClassToBuild.builder().name("Stanley"); ClassToBuild.Builder copied = builder.copy().name("Alexander"); assertThat(builder.build().name).isEqualTo("Stanley"); assertThat(copied.build().name).isEqualTo("Alexander"); } private ClassToBuild.Builder upperCaseName(ClassToBuild.Builder builder) { return builder.name(builder.name.toUpperCase()); } private static class ClassToBuild implements ToCopyableBuilder<ClassToBuild.Builder, ClassToBuild> { private final String name; private ClassToBuild(Builder builder) { this.name = builder.name; } @Override public Builder toBuilder() { return new Builder(this); } public static Builder builder() { return new Builder(); } static class Builder implements CopyableBuilder<Builder, ClassToBuild> { private String name; private Builder() {} private Builder(ClassToBuild source) { this.name = source.name; } public Builder name(String name) { this.name = name; return this; } @Override public ClassToBuild build() { return new ClassToBuild(this); } } } }
3,250
0
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/test/java/software/amazon/awssdk/testutils/EnvironmentVariableHelper.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.testutils; import java.util.function.Consumer; import org.junit.rules.ExternalResource; import software.amazon.awssdk.utils.SystemSetting; import software.amazon.awssdk.utils.internal.SystemSettingUtilsTestBackdoor; /** * A utility that can temporarily forcibly set environment variables and then allows resetting them to the original values. * * This only works for environment variables read by the SDK. */ public class EnvironmentVariableHelper extends ExternalResource { public void remove(SystemSetting setting) { remove(setting.environmentVariable()); } public void remove(String key) { SystemSettingUtilsTestBackdoor.addEnvironmentVariableOverride(key, null); } public void set(SystemSetting setting, String value) { set(setting.environmentVariable(), value); } public void set(String key, String value) { SystemSettingUtilsTestBackdoor.addEnvironmentVariableOverride(key, value); } public void reset() { SystemSettingUtilsTestBackdoor.clearEnvironmentVariableOverrides(); } @Override protected void after() { reset(); } /** * Static run method that allows for "single-use" environment variable modification. * * Example use: * <pre> * {@code * EnvironmentVariableHelper.run(helper -> { * helper.set("variable", "value"); * //run some test that uses "variable" * }); * } * </pre> * * Will call {@link #reset} at the end of the block (even if the block exits exceptionally). * * @param helperConsumer a code block to run that gets an {@link EnvironmentVariableHelper} as an argument */ public static void run(Consumer<EnvironmentVariableHelper> helperConsumer) { EnvironmentVariableHelper helper = new EnvironmentVariableHelper(); try { helperConsumer.accept(helper); } finally { helper.reset(); } } }
3,251
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/DaemonThreadFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.concurrent.ThreadFactory; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * An decorator for {@link ThreadFactory} that sets all threads it creates to be daemon threads. */ @SdkProtectedApi public class DaemonThreadFactory implements ThreadFactory { private final ThreadFactory delegate; public DaemonThreadFactory(ThreadFactory delegate) { this.delegate = Validate.notNull(delegate, "delegate must not be null"); } @Override public Thread newThread(Runnable runnable) { Thread thread = delegate.newThread(runnable); thread.setDaemon(true); return thread; } }
3,252
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/IoUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Utilities for IO operations. */ @SdkProtectedApi public final class IoUtils { private static final int BUFFER_SIZE = 1024 * 4; private static final Logger DEFAULT_LOG = LoggerFactory.getLogger(IoUtils.class); private IoUtils() { } /** * Reads and returns the rest of the given input stream as a byte array. * Caller is responsible for closing the given input stream. */ public static byte[] toByteArray(InputStream is) throws IOException { try (ByteArrayOutputStream output = new ByteArrayOutputStream()) { byte[] b = new byte[BUFFER_SIZE]; int n = 0; while ((n = is.read(b)) != -1) { output.write(b, 0, n); } return output.toByteArray(); } } /** * Reads and returns the rest of the given input stream as a string. * Caller is responsible for closing the given input stream. */ public static String toUtf8String(InputStream is) throws IOException { return new String(toByteArray(is), StandardCharsets.UTF_8); } /** * Closes the given Closeable quietly. * @param is the given closeable * @param log logger used to log any failure should the close fail */ public static void closeQuietly(AutoCloseable is, Logger log) { if (is != null) { try { is.close(); } catch (Exception ex) { Logger logger = log == null ? DEFAULT_LOG : log; if (logger.isDebugEnabled()) { logger.debug("Ignore failure in closing the Closeable", ex); } } } } /** * Closes the given Closeable quietly. * @param maybeCloseable the given closeable * @param log logger used to log any failure should the close fail */ public static void closeIfCloseable(Object maybeCloseable, Logger log) { if (maybeCloseable instanceof AutoCloseable) { IoUtils.closeQuietly((AutoCloseable) maybeCloseable, log); } } /** * Copies all bytes from the given input stream to the given output stream. * Caller is responsible for closing the streams. * * @throws IOException * if there is any IO exception during read or write. */ public static long copy(InputStream in, OutputStream out) throws IOException { return copy(in, out, Long.MAX_VALUE); } /** * Copies all bytes from the given input stream to the given output stream. * Caller is responsible for closing the streams. * * @throws IOException if there is any IO exception during read or write or the read limit is exceeded. */ public static long copy(InputStream in, OutputStream out, long readLimit) throws IOException { byte[] buf = new byte[BUFFER_SIZE]; long count = 0; int n = 0; while ((n = in.read(buf)) > -1) { out.write(buf, 0, n); count += n; if (count >= readLimit) { throw new IOException("Read limit exceeded: " + readLimit); } } return count; } /** * Read all remaining data in the stream. * * @param in InputStream to read. */ public static void drainInputStream(InputStream in) { try { while (in.read() != -1) { // Do nothing. } } catch (IOException ignored) { // Stream may be self closed by HTTP client so we ignore any failures. } } /** * If the stream supports marking, marks the stream at the current position with a {@code readLimit} value of * 128 KiB. * * @param s The stream. */ public static void markStreamWithMaxReadLimit(InputStream s) { if (s.markSupported()) { s.mark(1 << 17); } } /** * If the stream supports marking, marks the stream at the current position with a read limit specified in {@code * maxReadLimit}. * * @param maxReadLimit the maxReadLimit, if it's null, 128 KiB will be used. * @param s The stream. */ public static void markStreamWithMaxReadLimit(InputStream s, Integer maxReadLimit) { Validate.isPositiveOrNull(maxReadLimit, "maxReadLimit"); if (s.markSupported()) { int maxLimit = maxReadLimit == null ? 1 << 17 : maxReadLimit; s.mark(maxLimit); } } }
3,253
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/StringUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.io.UncheckedIOException; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.util.Locale; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * <p>Operations on {@link java.lang.String} that are * {@code null} safe.</p> * * <ul> * <li><b>IsEmpty/IsBlank</b> * - checks if a String contains text</li> * <li><b>Trim/Strip</b> * - removes leading and trailing whitespace</li> * <li><b>Equals/Compare</b> * - compares two strings null-safe</li> * <li><b>startsWith</b> * - check if a String starts with a prefix null-safe</li> * <li><b>endsWith</b> * - check if a String ends with a suffix null-safe</li> * <li><b>IndexOf/LastIndexOf/Contains</b> * - null-safe index-of checks * <li><b>IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut</b> * - index-of any of a set of Strings</li> * <li><b>ContainsOnly/ContainsNone/ContainsAny</b> * - does String contains only/none/any of these characters</li> * <li><b>Substring/Left/Right/Mid</b> * - null-safe substring extractions</li> * <li><b>SubstringBefore/SubstringAfter/SubstringBetween</b> * - substring extraction relative to other strings</li> * <li><b>Split/Join</b> * - splits a String into an array of substrings and vice versa</li> * <li><b>Remove/Delete</b> * - removes part of a String</li> * <li><b>Replace/Overlay</b> * - Searches a String and replaces one String with another</li> * <li><b>Chomp/Chop</b> * - removes the last part of a String</li> * <li><b>AppendIfMissing</b> * - appends a suffix to the end of the String if not present</li> * <li><b>PrependIfMissing</b> * - prepends a prefix to the start of the String if not present</li> * <li><b>LeftPad/RightPad/Center/Repeat</b> * - pads a String</li> * <li><b>UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize</b> * - changes the case of a String</li> * <li><b>CountMatches</b> * - counts the number of occurrences of one String in another</li> * <li><b>IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable</b> * - checks the characters in a String</li> * <li><b>DefaultString</b> * - protects against a null input String</li> * <li><b>Rotate</b> * - rotate (circular shift) a String</li> * <li><b>Reverse/ReverseDelimited</b> * - reverses a String</li> * <li><b>Abbreviate</b> * - abbreviates a string using ellipsis or another given String</li> * <li><b>Difference</b> * - compares Strings and reports on their differences</li> * <li><b>LevenshteinDistance</b> * - the number of changes needed to change one String into another</li> * </ul> * * <p>The {@code StringUtils} class defines certain words related to * String handling.</p> * * <ul> * <li>null - {@code null}</li> * <li>empty - a zero-length string ({@code ""})</li> * <li>space - the space character ({@code ' '}, char 32)</li> * <li>whitespace - the characters defined by {@link Character#isWhitespace(char)}</li> * <li>trim - the characters &lt;= 32 as in {@link String#trim()}</li> * </ul> * * <p>{@code StringUtils} handles {@code null} input Strings quietly. * That is to say that a {@code null} input will return {@code null}. * Where a {@code boolean} or {@code int} is being returned * details vary by method.</p> * * <p>A side effect of the {@code null} handling is that a * {@code NullPointerException} should be considered a bug in * {@code StringUtils}.</p> * * <p>This class's source was modified from the Apache commons-lang library: https://github.com/apache/commons-lang/</p> * * <p>#ThreadSafe#</p> * @see java.lang.String */ @SdkProtectedApi public final class StringUtils { // Performance testing notes (JDK 1.4, Jul03, scolebourne) // Whitespace: // Character.isWhitespace() is faster than WHITESPACE.indexOf() // where WHITESPACE is a string of all whitespace characters // // Character access: // String.charAt(n) versus toCharArray(), then array[n] // String.charAt(n) is about 15% worse for a 10K string // They are about equal for a length 50 string // String.charAt(n) is about 4 times better for a length 3 string // String.charAt(n) is best bet overall // // Append: // String.concat about twice as fast as StringBuffer.append // (not sure who tested this) /** * The empty String {@code ""}. */ private static final String EMPTY = ""; /** * <p>{@code StringUtils} instances should NOT be constructed in * standard programming. Instead, the class should be used as * {@code StringUtils.trim(" foo ");}.</p> */ private StringUtils() { } // Empty checks //----------------------------------------------------------------------- /** * <p>Checks if a CharSequence is empty ("") or null.</p> * * <pre> * StringUtils.isEmpty(null) = true * StringUtils.isEmpty("") = true * StringUtils.isEmpty(" ") = false * StringUtils.isEmpty("bob") = false * StringUtils.isEmpty(" bob ") = false * </pre> * * <p>NOTE: This method changed in Lang version 2.0. * It no longer trims the CharSequence. * That functionality is available in isBlank().</p> * * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is empty or null * @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence) */ public static boolean isEmpty(final CharSequence cs) { return cs == null || cs.length() == 0; } /** * <p>Checks if a CharSequence is empty (""), null or whitespace only.</p> * * <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p> * * <pre> * StringUtils.isBlank(null) = true * StringUtils.isBlank("") = true * StringUtils.isBlank(" ") = true * StringUtils.isBlank("bob") = false * StringUtils.isBlank(" bob ") = false * </pre> * * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is null, empty or whitespace only * @since 2.0 * @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence) */ public static boolean isBlank(final CharSequence cs) { if (cs == null || cs.length() == 0) { return true; } for (int i = 0; i < cs.length(); i++) { if (!Character.isWhitespace(cs.charAt(i))) { return false; } } return true; } /** * <p>Checks if a CharSequence is not empty (""), not null and not whitespace only.</p> * * <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p> * * <pre> * StringUtils.isNotBlank(null) = false * StringUtils.isNotBlank("") = false * StringUtils.isNotBlank(" ") = false * StringUtils.isNotBlank("bob") = true * StringUtils.isNotBlank(" bob ") = true * </pre> * * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is not empty and not null and not whitespace only * @since 2.0 * @since 3.0 Changed signature from isNotBlank(String) to isNotBlank(CharSequence) */ public static boolean isNotBlank(final CharSequence cs) { return !isBlank(cs); } // Trim //----------------------------------------------------------------------- /** * <p>Removes control characters (char &lt;= 32) from both * ends of this String, handling {@code null} by returning * {@code null}.</p> * * <p>The String is trimmed using {@link String#trim()}. * Trim removes start and end characters &lt;= 32.</p> * * <pre> * StringUtils.trim(null) = null * StringUtils.trim("") = "" * StringUtils.trim(" ") = "" * StringUtils.trim("abc") = "abc" * StringUtils.trim(" abc ") = "abc" * </pre> * * @param str the String to be trimmed, may be null * @return the trimmed string, {@code null} if null String input */ public static String trim(final String str) { return str == null ? null : str.trim(); } /** * <p>Removes control characters (char &lt;= 32) from both * ends of this String returning {@code null} if the String is * empty ("") after the trim or if it is {@code null}. * * <p>The String is trimmed using {@link String#trim()}. * Trim removes start and end characters &lt;= 32.</p> * * <pre> * StringUtils.trimToNull(null) = null * StringUtils.trimToNull("") = null * StringUtils.trimToNull(" ") = null * StringUtils.trimToNull("abc") = "abc" * StringUtils.trimToNull(" abc ") = "abc" * </pre> * * @param str the String to be trimmed, may be null * @return the trimmed String, * {@code null} if only chars &lt;= 32, empty or null String input * @since 2.0 */ public static String trimToNull(final String str) { String ts = trim(str); return isEmpty(ts) ? null : ts; } /** * <p>Removes control characters (char &lt;= 32) from both * ends of this String returning an empty String ("") if the String * is empty ("") after the trim or if it is {@code null}. * * <p>The String is trimmed using {@link String#trim()}. * Trim removes start and end characters &lt;= 32.</p> * * <pre> * StringUtils.trimToEmpty(null) = "" * StringUtils.trimToEmpty("") = "" * StringUtils.trimToEmpty(" ") = "" * StringUtils.trimToEmpty("abc") = "abc" * StringUtils.trimToEmpty(" abc ") = "abc" * </pre> * * @param str the String to be trimmed, may be null * @return the trimmed String, or an empty String if {@code null} input * @since 2.0 */ public static String trimToEmpty(final String str) { return str == null ? EMPTY : str.trim(); } // Equals //----------------------------------------------------------------------- /** * <p>Compares two Strings, returning {@code true} if they represent * equal sequences of characters.</p> * * <p>{@code null}s are handled without exceptions. Two {@code null} * references are considered to be equal. The comparison is case sensitive.</p> * * <pre> * StringUtils.equals(null, null) = true * StringUtils.equals(null, "abc") = false * StringUtils.equals("abc", null) = false * StringUtils.equals("abc", "abc") = true * StringUtils.equals("abc", "ABC") = false * </pre> * * @see Object#equals(Object) * @param cs1 the first String, may be {@code null} * @param cs2 the second String, may be {@code null} * @return {@code true} if the Strings are equal (case-sensitive), or both {@code null} */ public static boolean equals(final String cs1, final String cs2) { if (cs1 == null || cs2 == null) { return false; } if (cs1.length() != cs2.length()) { return false; } return cs1.equals(cs2); } // Substring //----------------------------------------------------------------------- /** * <p>Gets a substring from the specified String avoiding exceptions.</p> * * <p>A negative start position can be used to start {@code n} * characters from the end of the String.</p> * * <p>A {@code null} String will return {@code null}. * An empty ("") String will return "".</p> * * <pre> * StringUtils.substring(null, *) = null * StringUtils.substring("", *) = "" * StringUtils.substring("abc", 0) = "abc" * StringUtils.substring("abc", 2) = "c" * StringUtils.substring("abc", 4) = "" * StringUtils.substring("abc", -2) = "bc" * StringUtils.substring("abc", -4) = "abc" * </pre> * * @param str the String to get the substring from, may be null * @param start the position to start from, negative means count back from the end of the String by this many characters * @return substring from start position, {@code null} if null String input */ public static String substring(final String str, int start) { if (str == null) { return null; } // handle negatives, which means last n characters if (start < 0) { start = str.length() + start; // remember start is negative } if (start < 0) { start = 0; } if (start > str.length()) { return EMPTY; } return str.substring(start); } /** * <p>Gets a substring from the specified String avoiding exceptions.</p> * * <p>A negative start position can be used to start/end {@code n} * characters from the end of the String.</p> * * <p>The returned substring starts with the character in the {@code start} * position and ends before the {@code end} position. All position counting is * zero-based -- i.e., to start at the beginning of the string use * {@code start = 0}. Negative start and end positions can be used to * specify offsets relative to the end of the String.</p> * * <p>If {@code start} is not strictly to the left of {@code end}, "" * is returned.</p> * * <pre> * StringUtils.substring(null, *, *) = null * StringUtils.substring("", * , *) = ""; * StringUtils.substring("abc", 0, 2) = "ab" * StringUtils.substring("abc", 2, 0) = "" * StringUtils.substring("abc", 2, 4) = "c" * StringUtils.substring("abc", 4, 6) = "" * StringUtils.substring("abc", 2, 2) = "" * StringUtils.substring("abc", -2, -1) = "b" * StringUtils.substring("abc", -4, 2) = "ab" * </pre> * * @param str the String to get the substring from, may be null * @param start the position to start from, negative means count back from the end of the String by this many characters * @param end the position to end at (exclusive), negative means count back from the end of the String by this many * characters * @return substring from start position to end position, * {@code null} if null String input */ public static String substring(final String str, int start, int end) { if (str == null) { return null; } // handle negatives if (end < 0) { end = str.length() + end; // remember end is negative } if (start < 0) { start = str.length() + start; // remember start is negative } // check length next if (end > str.length()) { end = str.length(); } // if start is greater than end, return "" if (start > end) { return EMPTY; } if (start < 0) { start = 0; } if (end < 0) { end = 0; } return str.substring(start, end); } // Case conversion //----------------------------------------------------------------------- /** * <p>Converts a String to upper case as per {@link String#toUpperCase()}.</p> * * <p>A {@code null} input String returns {@code null}.</p> * * <pre> * StringUtils.upperCase(null) = null * StringUtils.upperCase("") = "" * StringUtils.upperCase("aBc") = "ABC" * </pre> * * <p>This uses "ENGLISH" as the locale. * * @param str the String to upper case, may be null * @return the upper cased String, {@code null} if null String input */ public static String upperCase(final String str) { if (str == null) { return null; } return str.toUpperCase(Locale.ENGLISH); } /** * <p>Converts a String to lower case as per {@link String#toLowerCase()}.</p> * * <p>A {@code null} input String returns {@code null}.</p> * * <pre> * StringUtils.lowerCase(null) = null * StringUtils.lowerCase("") = "" * StringUtils.lowerCase("aBc") = "abc" * </pre> * * <p>This uses "ENGLISH" as the locale. * * @param str the String to lower case, may be null * @return the lower cased String, {@code null} if null String input */ public static String lowerCase(final String str) { if (str == null) { return null; } return str.toLowerCase(Locale.ENGLISH); } /** * <p>Capitalizes a String changing the first character to title case as * per {@link Character#toTitleCase(int)}. No other characters are changed.</p> * * <pre> * StringUtils.capitalize(null) = null * StringUtils.capitalize("") = "" * StringUtils.capitalize("cat") = "Cat" * StringUtils.capitalize("cAt") = "CAt" * StringUtils.capitalize("'cat'") = "'cat'" * </pre> * * @param str the String to capitalize, may be null * @return the capitalized String, {@code null} if null String input * @see #uncapitalize(String) * @since 2.0 */ 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) { // already capitalized return str; } int[] newCodePoints = new int[str.length()]; // cannot be longer than the char array int outOffset = 0; newCodePoints[outOffset++] = newCodePoint; // copy the first codepoint for (int inOffset = Character.charCount(firstCodepoint); inOffset < str.length(); ) { int codepoint = str.codePointAt(inOffset); newCodePoints[outOffset++] = codepoint; // copy the remaining ones inOffset += Character.charCount(codepoint); } return new String(newCodePoints, 0, outOffset); } /** * <p>Uncapitalizes a String, changing the first character to lower case as * per {@link Character#toLowerCase(int)}. No other characters are changed.</p> * * <pre> * StringUtils.uncapitalize(null) = null * StringUtils.uncapitalize("") = "" * StringUtils.uncapitalize("cat") = "cat" * StringUtils.uncapitalize("Cat") = "cat" * StringUtils.uncapitalize("CAT") = "cAT" * </pre> * * @param str the String to uncapitalize, may be null * @return the uncapitalized String, {@code null} if null String input * @see #capitalize(String) * @since 2.0 */ 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) { // already capitalized return str; } int[] newCodePoints = new int[str.length()]; // cannot be longer than the char array int outOffset = 0; newCodePoints[outOffset++] = newCodePoint; // copy the first codepoint for (int inOffset = Character.charCount(firstCodepoint); inOffset < str.length(); ) { int codepoint = str.codePointAt(inOffset); newCodePoints[outOffset++] = codepoint; // copy the remaining ones inOffset += Character.charCount(codepoint); } return new String(newCodePoints, 0, outOffset); } /** * Encode the given bytes as a string using the given charset * @throws UncheckedIOException with a {@link CharacterCodingException} as the cause if the bytes cannot be encoded using the * provided charset. */ public static String fromBytes(byte[] bytes, Charset charset) throws UncheckedIOException { try { return charset.newDecoder().decode(ByteBuffer.wrap(bytes)).toString(); } catch (CharacterCodingException e) { throw new UncheckedIOException("Cannot encode string.", e); } } /** * Tests if this string starts with the specified prefix ignoring case considerations. * * @param str the string to be tested * @param prefix the prefix * @return true if the string starts with the prefix ignoring case */ public static boolean startsWithIgnoreCase(String str, String prefix) { return str.regionMatches(true, 0, prefix, 0, prefix.length()); } /** * <p>Replaces a String with another String inside a larger String, once.</p> * * <p>A {@code null} reference passed to this method is a no-op.</p> * * <pre> * StringUtils.replaceOnce(null, *, *) = null * StringUtils.replaceOnce("", *, *) = "" * StringUtils.replaceOnce("any", null, *) = "any" * StringUtils.replaceOnce("any", *, null) = "any" * StringUtils.replaceOnce("any", "", *) = "any" * StringUtils.replaceOnce("aba", "a", null) = "aba" * StringUtils.replaceOnce("aba", "a", "") = "ba" * StringUtils.replaceOnce("aba", "a", "z") = "zba" * </pre> * * @see #replace(String text, String searchString, String replacement, int max) * @param text text to search and replace in, may be null * @param searchString the String to search for, may be null * @param replacement the String to replace with, may be null * @return the text with any replacements processed, * {@code null} if null String input */ public static String replaceOnce(String text, String searchString, String replacement) { return replace(text, searchString, replacement, 1); } /** * <p>Replaces a String with another String inside a larger String, * for the first {@code max} values of the search String, * case sensitively/insensitively based on {@code ignoreCase} value.</p> * * <p>A {@code null} reference passed to this method is a no-op.</p> * * <pre> * StringUtils.replace(null, *, *, *, false) = null * StringUtils.replace("", *, *, *, false) = "" * StringUtils.replace("any", null, *, *, false) = "any" * StringUtils.replace("any", *, null, *, false) = "any" * StringUtils.replace("any", "", *, *, false) = "any" * StringUtils.replace("any", *, *, 0, false) = "any" * StringUtils.replace("abaa", "a", null, -1, false) = "abaa" * StringUtils.replace("abaa", "a", "", -1, false) = "b" * StringUtils.replace("abaa", "a", "z", 0, false) = "abaa" * StringUtils.replace("abaa", "A", "z", 1, false) = "abaa" * StringUtils.replace("abaa", "A", "z", 1, true) = "zbaa" * StringUtils.replace("abAa", "a", "z", 2, true) = "zbza" * StringUtils.replace("abAa", "a", "z", -1, true) = "zbzz" * </pre> * * @param text text to search and replace in, may be null * @param searchString the String to search for (case insensitive), may be null * @param replacement the String to replace it with, may be null * @return the text with any replacements processed, * {@code null} if null String input */ public static String replace(String text, String searchString, String replacement) { return replace(text, searchString, replacement, -1); } /** * <p>Replaces a String with another String inside a larger String, * for the first {@code max} values of the search String, * case sensitively/insensitively based on {@code ignoreCase} value.</p> * * <p>A {@code null} reference passed to this method is a no-op.</p> * * <pre> * StringUtils.replace(null, *, *, *, false) = null * StringUtils.replace("", *, *, *, false) = "" * StringUtils.replace("any", null, *, *, false) = "any" * StringUtils.replace("any", *, null, *, false) = "any" * StringUtils.replace("any", "", *, *, false) = "any" * StringUtils.replace("any", *, *, 0, false) = "any" * StringUtils.replace("abaa", "a", null, -1, false) = "abaa" * StringUtils.replace("abaa", "a", "", -1, false) = "b" * StringUtils.replace("abaa", "a", "z", 0, false) = "abaa" * StringUtils.replace("abaa", "A", "z", 1, false) = "abaa" * StringUtils.replace("abaa", "A", "z", 1, true) = "zbaa" * StringUtils.replace("abAa", "a", "z", 2, true) = "zbza" * StringUtils.replace("abAa", "a", "z", -1, true) = "zbzz" * </pre> * * @param text text to search and replace in, may be null * @param searchString the String to search for (case insensitive), may be null * @param replacement the String to replace it with, may be null * @param max maximum number of values to replace, or {@code -1} if no maximum * @return the text with any replacements processed, * {@code null} if null String input */ private static String replace(String text, String searchString, String replacement, int max) { if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) { return text; } int start = 0; int end = indexOf(text, searchString, start); if (end == -1) { return text; } int replLength = searchString.length(); int increase = Math.max(replacement.length() - replLength, 0); increase *= max < 0 ? 16 : Math.min(max, 64); StringBuilder buf = new StringBuilder(text.length() + increase); while (end != -1) { buf.append(text, start, end).append(replacement); start = end + replLength; if (--max == 0) { break; } end = indexOf(text, searchString, start); } buf.append(text, start, text.length()); return buf.toString(); } /** * <p> * Replaces all occurrences of Strings within another String. * </p> * * <p> * A {@code null} reference passed to this method is a no-op, or if * any "search string" or "string to replace" is null, that replace will be * ignored. This will not repeat. For repeating replaces, call the * overloaded method. * </p> * * <pre> * StringUtils.replaceEach(null, *, *) = null * StringUtils.replaceEach("", *, *) = "" * StringUtils.replaceEach("aba", null, null) = "aba" * StringUtils.replaceEach("aba", new String[0], null) = "aba" * StringUtils.replaceEach("aba", null, new String[0]) = "aba" * StringUtils.replaceEach("aba", new String[]{"a"}, null) = "aba" * StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}) = "b" * StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}) = "aba" * StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte" * (example of how it does not repeat) * StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "dcte" * </pre> * * @param text * text to search and replace in, no-op if null * @param searchList * the Strings to search for, no-op if null * @param replacementList * the Strings to replace them with, no-op if null * @return the text with any replacements processed, {@code null} if * null String input * @throws IllegalArgumentException * if the lengths of the arrays are not the same (null is ok, * and/or size 0) * @since 2.4 */ public static String replaceEach(String text, String[] searchList, String[] replacementList) { // mchyzer Performance note: This creates very few new objects (one major goal) // let me know if there are performance requests, we can create a harness to measure if (isEmpty(text)) { return text; } int searchLength = searchList.length; int replacementLength = replacementList.length; // make sure lengths are ok, these need to be equal if (searchLength != replacementLength) { throw new IllegalArgumentException("Search and Replace array lengths don't match: " + searchLength + " vs " + replacementLength); } // keep track of which still have matches boolean[] noMoreMatchesForReplIndex = new boolean[searchLength]; // index on index that the match was found int textIndex = -1; int replaceIndex = -1; int tempIndex; // index of replace array that will replace the search string found // NOTE: logic duplicated below START for (int i = 0; i < searchLength; i++) { if (noMoreMatchesForReplIndex[i] || isEmpty(searchList[i]) || replacementList[i] == null) { continue; } tempIndex = text.indexOf(searchList[i]); // see if we need to keep searching for this if (tempIndex == -1) { noMoreMatchesForReplIndex[i] = true; } else if (textIndex == -1 || tempIndex < textIndex) { textIndex = tempIndex; replaceIndex = i; } } // NOTE: logic mostly below END // no search strings found, we are done if (textIndex == -1) { return text; } int start = 0; // get a good guess on the size of the result buffer so it doesn't have to double if it goes over a bit int increase = 0; // count the replacement text elements that are larger than their corresponding text being replaced for (int i = 0; i < searchList.length; i++) { if (searchList[i] == null || replacementList[i] == null) { continue; } int greater = replacementList[i].length() - searchList[i].length(); if (greater > 0) { increase += 3 * greater; // assume 3 matches } } // have upper-bound at 20% increase, then let Java take over increase = Math.min(increase, text.length() / 5); StringBuilder buf = new StringBuilder(text.length() + increase); while (textIndex != -1) { for (int i = start; i < textIndex; i++) { buf.append(text.charAt(i)); } buf.append(replacementList[replaceIndex]); start = textIndex + searchList[replaceIndex].length(); textIndex = -1; replaceIndex = -1; // find the next earliest match // NOTE: logic mostly duplicated above START for (int i = 0; i < searchLength; i++) { if (noMoreMatchesForReplIndex[i] || searchList[i] == null || searchList[i].isEmpty() || replacementList[i] == null) { continue; } tempIndex = text.indexOf(searchList[i], start); // see if we need to keep searching for this if (tempIndex == -1) { noMoreMatchesForReplIndex[i] = true; } else if (textIndex == -1 || tempIndex < textIndex) { textIndex = tempIndex; replaceIndex = i; } } // NOTE: logic duplicated above END } int textLength = text.length(); for (int i = start; i < textLength; i++) { buf.append(text.charAt(i)); } return buf.toString(); } /** * <p>Finds the first index within a CharSequence, handling {@code null}. * This method uses {@link String#indexOf(String, int)} if possible.</p> * * <p>A {@code null} CharSequence will return {@code -1}.</p> * * <pre> * StringUtils.indexOf(null, *) = -1 * StringUtils.indexOf(*, null) = -1 * StringUtils.indexOf("", "") = 0 * StringUtils.indexOf("", *) = -1 (except when * = "") * StringUtils.indexOf("aabaabaa", "a") = 0 * StringUtils.indexOf("aabaabaa", "b") = 2 * StringUtils.indexOf("aabaabaa", "ab") = 1 * StringUtils.indexOf("aabaabaa", "") = 0 * </pre> * * @param seq the CharSequence to check, may be null * @param searchSeq the CharSequence to find, may be null * @return the first index of the search CharSequence, * -1 if no match or {@code null} string input * @since 2.0 * @since 3.0 Changed signature from indexOf(String, String) to indexOf(CharSequence, CharSequence) */ private static int indexOf(String seq, String searchSeq, int start) { if (seq == null || searchSeq == null) { return -1; } return seq.indexOf(searchSeq, start); } /** * Replace the prefix of the string provided ignoring case considerations. * * <p> * The unmatched part is unchanged. * * * @param str the string to replace * @param prefix the prefix to find * @param replacement the replacement * @return the replaced string */ public static String replacePrefixIgnoreCase(String str, String prefix, String replacement) { return str.replaceFirst("(?i)" + prefix, replacement); } /** * Searches a string for the first occurrence of a character specified by a list of characters. * @param s The string to search. * @param charsToMatch A list of characters to search the string for. * @return The character that was first matched in the string or null if none of the characters were found. */ 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); } /** * Convert a string to boolean safely (as opposed to the less strict {@link Boolean#parseBoolean(String)}). If a customer * specifies a boolean value it should be "true" or "false" (case insensitive) or an exception will be thrown. */ 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'"); } /** * Returns a string whose value is the concatenation of this string repeated {@code count} times. * <p> * If this string is empty or count is zero then the empty string is returned. * <p> * Logical clone of JDK11's {@link String#repeat(int)}. * * @param value the string to repeat * @param count number of times to repeat * @return A string composed of this string repeated {@code count} times or the empty string if this string is empty or count * is zero * @throws IllegalArgumentException if the {@code count} is negative. */ public static String repeat(String value, int count) { if (count < 0) { throw new IllegalArgumentException("count is negative: " + count); } if (value == null || value.length() == 0 || count == 1) { return value; } if (count == 0) { return ""; } if (value.length() > Integer.MAX_VALUE / count) { throw new OutOfMemoryError("Repeating " + value.length() + " bytes String " + count + " times will produce a String exceeding maximum size."); } int len = value.length(); int limit = len * count; char[] array = new char[limit]; value.getChars(0, len, array, 0); int copied; for (copied = len; copied < limit - copied; copied <<= 1) { System.arraycopy(array, 0, array, copied, copied); } System.arraycopy(array, 0, array, copied, limit - copied); return new String(array); } }
3,254
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ExecutorUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static java.util.concurrent.TimeUnit.SECONDS; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Utilities that make it easier to create, use and destroy {@link ExecutorService}s. */ @SdkProtectedApi public final class ExecutorUtils { private ExecutorUtils() { } /** * Create a bounded-queue executor with one thread for performing background tasks. The thread in the service is marked as a * daemon thread. */ public static ExecutorService newSingleDaemonThreadExecutor(int queueCapacity, String threadNameFormat) { return new ThreadPoolExecutor(0, 1, 5, SECONDS, new LinkedBlockingQueue<>(queueCapacity), new ThreadFactoryBuilder().daemonThreads(true).threadNamePrefix(threadNameFormat).build()); } /** * Wrap an executor in a type that cannot be closed, or shut down. */ public static Executor unmanagedExecutor(Executor executor) { return new UnmanagedExecutor(executor); } private static class UnmanagedExecutor implements Executor { private final Executor executor; private UnmanagedExecutor(Executor executor) { this.executor = executor; } @Override public void execute(Runnable command) { executor.execute(command); } } }
3,255
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/NamedThreadFactory.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * An decorator for {@link ThreadFactory} that allows naming threads based on a format. */ @SdkProtectedApi public class NamedThreadFactory implements ThreadFactory { private final ThreadFactory delegate; private final String namePrefix; private final AtomicInteger threadCount = new AtomicInteger(0); public NamedThreadFactory(ThreadFactory delegate, String namePrefix) { this.delegate = Validate.notNull(delegate, "delegate must not be null"); this.namePrefix = Validate.notBlank(namePrefix, "namePrefix must not be blank"); } @Override public Thread newThread(Runnable runnable) { Thread thread = delegate.newThread(runnable); thread.setName(namePrefix + "-" + threadCount.getAndIncrement()); return thread; } }
3,256
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/FunctionalUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.io.IOException; import java.io.UncheckedIOException; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import org.slf4j.Logger; import software.amazon.awssdk.annotations.SdkProtectedApi; @SdkProtectedApi public final class FunctionalUtils { private FunctionalUtils() { } /** * Runs a given {@link UnsafeRunnable} and logs an error without throwing. * * @param errorMsg Message to log with exception thrown. * @param runnable Action to perform. */ public static void runAndLogError(Logger log, String errorMsg, UnsafeRunnable runnable) { try { runnable.run(); } catch (Exception e) { log.error(errorMsg, e); } } /** * @param <T> Type of object to be consumed. * @return A {@link Consumer} that does nothing. */ public static <T> Consumer<T> noOpConsumer() { return ignored -> { }; } /** * @return A {@link Runnable} that does nothing. */ public static Runnable noOpRunnable() { return () -> { }; } /** * A wrapper around a Consumer that throws a checked exception. * * @param unsafeConsumer - something that acts like a consumer but throws an exception * @return a consumer that is wrapped in a try-catch converting the checked exception into a runtime exception */ public static <I> Consumer<I> safeConsumer(UnsafeConsumer<I> unsafeConsumer) { return (input) -> { try { unsafeConsumer.accept(input); } catch (Exception e) { throw asRuntimeException(e); } }; } /** * Takes a functional interface that throws an exception and returns a {@link Function} that deals with that exception by * wrapping in a runtime exception. Useful for APIs that use the standard Java functional interfaces that don't throw checked * exceptions. * * @param unsafeFunction Functional interface that throws checked exception. * @param <T> Input * @param <R> Output * @return New {@link Function} that handles checked exception. */ 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); } }; } /** * A wrapper around a BiConsumer that throws a checked exception. * * @param unsafeSupplier - something that acts like a BiConsumer but throws an exception * @return a consumer that is wrapped in a try-catch converting the checked exception into a runtime exception */ public static <T> Supplier<T> safeSupplier(UnsafeSupplier<T> unsafeSupplier) { return () -> { try { return unsafeSupplier.get(); } catch (Exception e) { throw asRuntimeException(e); } }; } /** * A wrapper around a Runnable that throws a checked exception. * * @param unsafeRunnable Something that acts like a Runnable but throws an exception * @return A Runnable that is wrapped in a try-catch converting the checked exception into a runtime exception */ public static Runnable safeRunnable(UnsafeRunnable unsafeRunnable) { return () -> { try { unsafeRunnable.run(); } catch (Exception e) { throw asRuntimeException(e); } }; } public static <I, O> Function<I, O> toFunction(Supplier<O> supplier) { return ignore -> supplier.get(); } public static <T> T invokeSafely(UnsafeSupplier<T> unsafeSupplier) { return safeSupplier(unsafeSupplier).get(); } public static void invokeSafely(UnsafeRunnable unsafeRunnable) { safeRunnable(unsafeRunnable).run(); } /** * Equivalent of {@link Consumer} that throws a checked exception. */ @FunctionalInterface public interface UnsafeConsumer<I> { void accept(I input) throws Exception; } /** * Equivalent of {@link Function} that throws a checked exception. */ @FunctionalInterface public interface UnsafeFunction<T, R> { R apply(T t) throws Exception; } /** * Equivalent of {@link Supplier} that throws a checked exception. */ @FunctionalInterface public interface UnsafeSupplier<T> { T get() throws Exception; } /** * Equivalent of {@link Runnable} that throws a checked exception. */ @FunctionalInterface public interface UnsafeRunnable { void run() throws Exception; } private static RuntimeException asRuntimeException(Exception exception) { if (exception instanceof RuntimeException) { return (RuntimeException) exception; } if (exception instanceof IOException) { return new UncheckedIOException((IOException) exception); } if (exception instanceof InterruptedException) { Thread.currentThread().interrupt(); } return new RuntimeException(exception); } }
3,257
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/UnmodifiableMapOfLists.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.io.Serializable; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkInternalApi; /** * An unmodifiable view of a {@code Map<T, List<U>>}. Created using {@link CollectionUtils#unmodifiableMapOfLists(Map)}. */ @SdkInternalApi class UnmodifiableMapOfLists<T, U> implements Map<T, List<U>>, Serializable { private static final long serialVersionUID = 1L; private final Map<T, List<U>> delegate; UnmodifiableMapOfLists(Map<T, List<U>> delegate) { this.delegate = delegate; } @Override public int size() { return delegate.size(); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public boolean containsKey(Object key) { return delegate.containsKey(key); } @Override public boolean containsValue(Object value) { return delegate.containsValue(value); } @Override public List<U> get(Object key) { return delegate.get(key); } @Override public List<U> getOrDefault(Object key, List<U> defaultValue) { return unmodifiableList(delegate.getOrDefault(key, defaultValue)); } @Override public List<U> put(T key, List<U> value) { throw new UnsupportedOperationException(); } @Override public List<U> remove(Object key) { throw new UnsupportedOperationException(); } @Override public void putAll(Map<? extends T, ? extends List<U>> m) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Set<T> keySet() { return Collections.unmodifiableSet(delegate.keySet()); } @Override public Collection<List<U>> values() { return new UnmodifiableCollection<>(delegate.values()); } @Override public Set<Entry<T, List<U>>> entrySet() { Set<? extends Entry<T, ? extends List<U>>> entries = delegate.entrySet(); return new UnmodifiableEntrySet<>(entries); } @Override public void forEach(BiConsumer<? super T, ? super List<U>> action) { delegate.forEach((k, v) -> action.accept(k, unmodifiableList(v))); } @Override public void replaceAll(BiFunction<? super T, ? super List<U>, ? extends List<U>> function) { throw new UnsupportedOperationException(); } @Override public List<U> putIfAbsent(T key, List<U> value) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object key, Object value) { throw new UnsupportedOperationException(); } @Override public boolean replace(T key, List<U> oldValue, List<U> newValue) { throw new UnsupportedOperationException(); } @Override public List<U> replace(T key, List<U> value) { throw new UnsupportedOperationException(); } @Override public List<U> computeIfAbsent(T key, Function<? super T, ? extends List<U>> mappingFunction) { throw new UnsupportedOperationException(); } @Override public List<U> computeIfPresent(T key, BiFunction<? super T, ? super List<U>, ? extends List<U>> remappingFunction) { throw new UnsupportedOperationException(); } @Override public List<U> compute(T key, BiFunction<? super T, ? super List<U>, ? extends List<U>> remappingFunction) { throw new UnsupportedOperationException(); } @Override public List<U> merge(T key, List<U> value, BiFunction<? super List<U>, ? super List<U>, ? extends List<U>> remappingFunction) { throw new UnsupportedOperationException(); } @Override public int hashCode() { return delegate.hashCode(); } @Override public boolean equals(Object obj) { return delegate.equals(obj); } @Override public String toString() { return delegate.toString(); } private static class UnmodifiableEntrySet<T, U> implements Set<Entry<T, List<U>>> { private final Set<? extends Entry<T, ? extends List<U>>> delegate; private UnmodifiableEntrySet(Set<? extends Entry<T, ? extends List<U>>> delegate) { this.delegate = delegate; } @Override public int size() { return delegate.size(); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public boolean contains(Object o) { return delegate.contains(o); } @Override public Iterator<Entry<T, List<U>>> iterator() { return new UnmodifiableEntryIterator<>(delegate.iterator()); } @Override public void forEach(Consumer<? super Entry<T, List<U>>> action) { delegate.forEach(e -> action.accept(new SimpleImmutableEntry<>(e.getKey(), unmodifiableList(e.getValue())))); } @Override @SuppressWarnings("unchecked") public Object[] toArray() { Object[] result = delegate.toArray(); for (int i = 0; i < result.length; i++) { Entry<T, List<U>> e = (Entry<T, List<U>>) result[i]; result[i] = new SimpleImmutableEntry<>(e.getKey(), unmodifiableList(e.getValue())); } return result; } @Override @SuppressWarnings("unchecked") public <A> A[] toArray(A[] a) { // Technically this could give the caller access very brief access to the modifiable entries from a different thread, // but that's on them. They had to have done it purposefully with a different thread, and it wouldn't be very // reliable. Object[] result = delegate.toArray(a); for (int i = 0; i < result.length; i++) { Entry<T, List<U>> e = (Entry<T, List<U>>) result[i]; result[i] = new SimpleImmutableEntry<>(e.getKey(), unmodifiableList(e.getValue())); } return (A[]) result; } @Override public boolean add(Entry<T, List<U>> tListEntry) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException(); } @Override public boolean containsAll(Collection<?> c) { return delegate.containsAll(c); } @Override public boolean addAll(Collection<? extends Entry<T, List<U>>> c) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public int hashCode() { return delegate.hashCode(); } @Override public boolean equals(Object obj) { return delegate.equals(obj); } @Override public String toString() { return delegate.toString(); } } private static class UnmodifiableEntryIterator<T, U> implements Iterator<Entry<T, List<U>>> { private final Iterator<? extends Entry<T, ? extends List<U>>> delegate; private UnmodifiableEntryIterator(Iterator<? extends Entry<T, ? extends List<U>>> delegate) { this.delegate = delegate; } @Override public boolean hasNext() { return delegate.hasNext(); } @Override public Entry<T, List<U>> next() { Entry<T, ? extends List<U>> next = delegate.next(); return new SimpleImmutableEntry<>(next.getKey(), unmodifiableList(next.getValue())); } } private static class UnmodifiableCollection<U> implements Collection<List<U>> { private final Collection<? extends List<U>> delegate; private UnmodifiableCollection(Collection<? extends List<U>> delegate) { this.delegate = delegate; } @Override public int size() { return delegate.size(); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public boolean contains(Object o) { return delegate.contains(o); } @Override public Iterator<List<U>> iterator() { return new UnmodifiableListIterator<>(delegate.iterator()); } @Override @SuppressWarnings("unchecked") public Object[] toArray() { Object[] result = delegate.toArray(); for (int i = 0; i < result.length; i++) { result[i] = unmodifiableList((List<U>) result[i]); } return result; } @Override @SuppressWarnings("unchecked") public <A> A[] toArray(A[] a) { // Technically this could give the caller access very brief access to the modifiable entries from a different thread, // but that's on them. They had to have done it purposefully with a different thread, and it wouldn't be very // reliable. Object[] result = delegate.toArray(a); for (int i = 0; i < result.length; i++) { result[i] = unmodifiableList((List<U>) result[i]); } return (A[]) result; } @Override public boolean add(List<U> us) { throw new UnsupportedOperationException(); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException(); } @Override public boolean containsAll(Collection<?> c) { return delegate.containsAll(c); } @Override public boolean addAll(Collection<? extends List<U>> c) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public int hashCode() { return delegate.hashCode(); } @Override public boolean equals(Object obj) { return delegate.equals(obj); } @Override public String toString() { return delegate.toString(); } } private static class UnmodifiableListIterator<U> implements Iterator<List<U>> { private final Iterator<? extends List<U>> delegate; private UnmodifiableListIterator(Iterator<? extends List<U>> delegate) { this.delegate = delegate; } @Override public boolean hasNext() { return delegate.hasNext(); } @Override public List<U> next() { return unmodifiableList(delegate.next()); } @Override public int hashCode() { return delegate.hashCode(); } @Override public boolean equals(Object obj) { return delegate.equals(obj); } @Override public String toString() { return delegate.toString(); } } private static <T> List<T> unmodifiableList(List<T> list) { if (list == null) { return null; } return Collections.unmodifiableList(list); } }
3,258
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ClassLoaderHelper.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import software.amazon.awssdk.annotations.SdkProtectedApi; @SdkProtectedApi public final class ClassLoaderHelper { private ClassLoaderHelper() { } private static Class<?> loadClassViaClasses(String fqcn, Class<?>[] classes) { if (classes == null) { return null; } for (Class<?> clzz: classes) { if (clzz == null) { continue; } ClassLoader loader = clzz.getClassLoader(); if (loader != null) { try { return loader.loadClass(fqcn); } catch (ClassNotFoundException e) { // move on to try the next class loader } } } return null; } private static Class<?> loadClassViaContext(String fqcn) { ClassLoader loader = contextClassLoader(); try { return loader == null ? null : loader.loadClass(fqcn); } catch (ClassNotFoundException e) { // Ignored. } return null; } /** * Loads the class via the optionally specified classes in the order of * their specification, and if not found, via the context class loader of * the current thread, and if not found, from the caller class loader as the * last resort. * * @param fqcn * fully qualified class name of the target class to be loaded * @param classes * class loader providers * @return the class loaded; never null * * @throws ClassNotFoundException * if failed to load the class */ public static Class<?> loadClass(String fqcn, Class<?>... classes) throws ClassNotFoundException { return loadClass(fqcn, true, classes); } /** * If classesFirst is false, loads the class via the context class * loader of the current thread, and if not found, via the class loaders of * the optionally specified classes in the order of their specification, and * if not found, from the caller class loader as the * last resort. * <p> * If classesFirst is true, loads the class via the optionally * specified classes in the order of their specification, and if not found, * via the context class loader of the current thread, and if not found, * from the caller class loader as the last resort. * * @param fqcn * fully qualified class name of the target class to be loaded * @param classesFirst * true if the class loaders of the optionally specified classes * take precedence over the context class loader of the current * thread; false if the opposite is true. * @param classes * class loader providers * @return the class loaded; never null * * @throws ClassNotFoundException if failed to load the class */ public static Class<?> loadClass(String fqcn, boolean classesFirst, Class<?>... classes) throws ClassNotFoundException { Class<?> target = null; if (classesFirst) { target = loadClassViaClasses(fqcn, classes); if (target == null) { target = loadClassViaContext(fqcn); } } else { target = loadClassViaContext(fqcn); if (target == null) { target = loadClassViaClasses(fqcn, classes); } } return target == null ? Class.forName(fqcn) : target; } /** * Attempt to get the current thread's class loader and fallback to the system classloader if null * @return a {@link ClassLoader} or null if none found */ private static ClassLoader contextClassLoader() { ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader(); if (threadClassLoader != null) { return threadClassLoader; } return ClassLoader.getSystemClassLoader(); } /** * Attempt to get class loader that loads the classes and fallback to the thread context classloader if null. * * @param classes the classes * @return a {@link ClassLoader} or null if none found */ public static ClassLoader classLoader(Class<?>... classes) { if (classes != null) { for (Class clzz : classes) { ClassLoader classLoader = clzz.getClassLoader(); if (classLoader != null) { return classLoader; } } } return contextClassLoader(); } }
3,259
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/AttributeMap.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Map; import java.util.Objects; import java.util.Queue; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.function.Function; import java.util.function.Supplier; import software.amazon.awssdk.annotations.Immutable; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.ToBuilderIgnoreField; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A map from {@code AttributeMap.Key<T>} to {@code T} that ensures the values stored with a key matches the type associated with * the key. This does not implement {@link Map} because it has more strict typing requirements, but a {@link Map} can be * converted * to an {code AttributeMap} via the type-unsafe {@link AttributeMap} method. * * This can be used for storing configuration values ({@code OptionKey.LOG_LEVEL} to {@code Boolean.TRUE}), attaching * arbitrary attributes to a request chain ({@code RequestAttribute.CONFIGURATION} to {@code ClientConfiguration}) or similar * use-cases. */ @SdkProtectedApi @Immutable public final class AttributeMap implements ToCopyableBuilder<AttributeMap.Builder, AttributeMap>, SdkAutoCloseable { private static final AttributeMap EMPTY = AttributeMap.builder().build(); private final Map<Key<?>, Value<?>> attributes; private final DependencyGraph dependencyGraph; private AttributeMap(Builder builder) { this.attributes = builder.attributes; this.dependencyGraph = builder.dependencyGraph; } /** * Return true if the provided key is configured in this map. Useful for differentiating between whether the provided key was * not configured in the map or if it is configured, but its value is null. */ public <T> boolean containsKey(Key<T> typedKey) { return attributes.containsKey(typedKey); } /** * Get the value associated with the provided key from this map. This will return null if the value is not set or if the * value stored is null. These cases can be disambiguated using {@link #containsKey(Key)}. */ public <T> T get(Key<T> key) { Validate.notNull(key, "Key to retrieve must not be null."); Value<?> value = attributes.get(key); if (value == null) { return null; } return key.convertValue(value.get(new ExpectCachedLazyValueSource())); } /** * Merges two AttributeMaps into one. This object is given higher precedence then the attributes passed in as a parameter. * * @param lowerPrecedence Options to merge into 'this' AttributeMap object. Any attribute already specified in 'this' object * will be left as is since it has higher precedence. * @return New options with values merged. */ public AttributeMap merge(AttributeMap lowerPrecedence) { Builder resultBuilder = new AttributeMap.Builder(this); lowerPrecedence.attributes.forEach((k, v) -> { resultBuilder.internalComputeIfAbsent(k, () -> { Value<?> result = v.copy(); result.clearCache(); return result; }); }); return resultBuilder.build(); } public static AttributeMap empty() { return EMPTY; } @Override public void close() { attributes.values().forEach(Value::close); } /** * An abstract class extended by pseudo-enums defining the key for data that is stored in the {@link AttributeMap}. For * example, a {@code ClientOption<T>} may extend this to define options that can be stored in an {@link AttributeMap}. */ public abstract static class Key<T> { private final Class<?> valueType; private final Function<Object, T> convertMethod; protected Key(Class<T> valueType) { this.valueType = valueType; this.convertMethod = valueType::cast; } protected Key(UnsafeValueType unsafeValueType) { this.valueType = unsafeValueType.valueType; this.convertMethod = v -> (T) v; // 🙏 } @Override public String toString() { return "Key(" + valueType.getName() + ")"; } /** * Useful for parameterized types. */ protected static class UnsafeValueType { private final Class<?> valueType; public UnsafeValueType(Class<?> valueType) { this.valueType = valueType; } } /** * Validate the provided value is of the correct type and convert it to the proper type for this option. */ public final T convertValue(Object value) { return convertMethod.apply(value); } } @Override public String toString() { return attributes.toString(); } @Override public boolean equals(Object obj) { if (!(obj instanceof AttributeMap)) { return false; } AttributeMap rhs = (AttributeMap) obj; if (attributes.size() != rhs.attributes.size()) { return false; } for (Key<?> lhsKey : attributes.keySet()) { Object lhsValue = get(lhsKey); Object rhsValue = rhs.get(lhsKey); if (!Objects.equals(lhsValue, rhsValue)) { return false; } } return true; } @Override public int hashCode() { int hashCode = 1; for (Key<?> key : attributes.keySet()) { hashCode = 31 * hashCode + Objects.hashCode(get(key)); } return hashCode; } public AttributeMap copy() { return toBuilder().build(); } @Override @ToBuilderIgnoreField("configuration") public Builder toBuilder() { return new Builder(this); } public static Builder builder() { return new Builder(); } public static final class Builder implements CopyableBuilder<Builder, AttributeMap> { private Map<Key<?>, Value<?>> attributes; private DependencyGraph dependencyGraph; private boolean copyOnUpdate; private Builder() { this.attributes = new HashMap<>(); this.dependencyGraph = new DependencyGraph(); this.copyOnUpdate = false; } private Builder(AttributeMap attributeMap) { this.attributes = attributeMap.attributes; this.dependencyGraph = attributeMap.dependencyGraph; this.copyOnUpdate = true; } private Builder(Builder builder) { this.attributes = builder.attributes; this.dependencyGraph = builder.dependencyGraph; this.copyOnUpdate = true; checkCopyOnUpdate(); // Proactively copy the values out of the source builder. } /** * Get the value for the provided key. */ public <T> T get(Key<T> key) { return key.convertValue(internalGet(null, key)); } /** * Add a mapping between the provided key and value, if the current value for the key is null. Returns the value. */ public <T> T computeIfAbsent(Key<T> key, Supplier<T> valueIfAbsent) { Validate.notNull(key, "Key to set must not be null."); Value<?> result = internalComputeIfAbsent(key, () -> { T value = valueIfAbsent.get(); return new ConstantValue<>(value); }); return key.convertValue(resolveValue(result)); } /** * Add a mapping between the provided key and value. */ public <T> Builder put(Key<T> key, T value) { Validate.notNull(key, "Key to set must not be null."); internalPut(key, new ConstantValue<>(value)); return this; } /** * Add a mapping between the provided key and value provider. * * The lazy value will only be resolved when the value is needed. During resolution, the lazy value is provided with a * value reader. The value reader will fail if the reader attempts to read its own value (directly, or indirectly * through other lazy values). * * If a value is updated that a lazy value is depended on, the lazy value will be re-resolved the next time the lazy * value is accessed. */ public <T> Builder putLazy(Key<T> key, LazyValue<T> lazyValue) { Validate.notNull(key, "Key to set must not be null."); internalPut(key, new DerivedValue<>(lazyValue)); return this; } /** * Equivalent to {@link #putLazy(Key, LazyValue)}, but does not assign the value if there is * already a non-null value assigned for the provided key. */ public <T> Builder putLazyIfAbsent(Key<T> key, LazyValue<T> lazyValue) { Validate.notNull(key, "Key to set must not be null."); internalComputeIfAbsent(key, () -> new DerivedValue<>(lazyValue)); return this; } /** * Adds all the attributes from the map provided. This is not type safe, and will throw an exception during creation if * a value in the map is not of the correct type for its key. */ public Builder putAll(Map<? extends Key<?>, ?> attributes) { attributes.forEach(this::unsafeInternalPutConstant); return this; } /** * Put all of the attributes from the provided map into this one. This will resolve lazy attributes and store their * value as a constant, so this should only be used when the source attributes are constants or it's okay that the * values will no longer be lazy. */ public Builder putAll(AttributeMap attributes) { attributes.attributes.forEach((k, v) -> unsafeInternalPutConstant(k, attributes.get(k))); return this; } /** * Equivalent to {@link #internalPut(Key, Value)} with a constant value, but uses runtime check to verify the value. * This is useful when type safety of the value isn't possible. */ private <T> void unsafeInternalPutConstant(Key<T> key, Object value) { try { T tValue = key.convertValue(value); internalPut(key, new ConstantValue<>(tValue)); } catch (ClassCastException e) { throw new IllegalArgumentException("Cannot write " + value.getClass() + " type to key " + key, e); } } /** * Update the value for the provided key. */ private void internalPut(Key<?> key, Value<?> value) { Validate.notNull(value, "Value must not be null."); checkCopyOnUpdate(); Value<?> oldValue = attributes.put(key, value); if (oldValue != null) { dependencyGraph.valueUpdated(oldValue, value); } } /** * If the current value for the provided key is null (or doesn't exist), set it using the provided value supplier. * Returns the new value that was set. */ private Value<?> internalComputeIfAbsent(Key<?> key, Supplier<Value<?>> value) { checkCopyOnUpdate(); return attributes.compute(key, (k, v) -> { if (v == null || resolveValue(v) == null) { Value<?> newValue = value.get(); Validate.notNull(newValue, "Supplied value must not be null."); if (v != null) { dependencyGraph.valueUpdated(v, newValue); } return newValue; } return v; }); } private void checkCopyOnUpdate() { if (copyOnUpdate) { Map<Key<?>, Value<?>> attributesToCopy = attributes; attributes = new HashMap<>(attributesToCopy.size()); Map<Value<?>, Value<?>> valueRemapping = new IdentityHashMap<>(attributesToCopy.size()); attributesToCopy.forEach((k, v) -> { Value<?> newValue = v.copy(); valueRemapping.put(v, newValue); attributes.put(k, newValue); }); dependencyGraph = dependencyGraph.copy(valueRemapping); copyOnUpdate = false; } } @Override public AttributeMap build() { // Resolve all of the attributes ahead of creating the attribute map, so that values can be read without any magic. Collection<Value<?>> valuesToPrime = new ArrayList<>(this.attributes.values()); valuesToPrime.forEach(this::resolveValue); copyOnUpdate = true; return new AttributeMap(this); } @Override public Builder copy() { return new Builder(this); } /** * Retrieve the value for the provided key, with the provided requesting value (used for tracking consumers in the * dependency graph). Requester may be null if this isn't a call within a derived value. */ private <T> T internalGet(Value<?> requester, Key<T> key) { Validate.notNull(key, "Key to retrieve must not be null."); Value<?> value; if (requester != null) { checkCopyOnUpdate(); value = attributes.computeIfAbsent(key, k -> new ConstantValue<>(null)); dependencyGraph.addDependency(requester, value); } else { value = attributes.get(key); if (value == null) { return null; } } return key.convertValue(resolveValue(value)); } /** * Resolve the provided value, making sure to record any of its dependencies in the dependency graph. */ private <T> T resolveValue(Value<T> value) { return value.get(new LazyValueSource() { @Override public <U> U get(Key<U> innerKey) { return internalGet(value, innerKey); } }); } } /** * A value that is evaluated lazily. See {@link Builder#putLazy(Key, LazyValue)}. */ @FunctionalInterface public interface LazyValue<T> { T get(LazyValueSource source); } /** * A source for other values, provided to a {@link LazyValue} when the value is resolved. */ @FunctionalInterface public interface LazyValueSource { <T> T get(Key<T> sourceKey); } /** * Tracks which values "depend on" other values, so that when we update one value, when can clear the cache of any other * values that were derived from the value that was updated. */ private static final class DependencyGraph { /** * Inverted adjacency list of dependencies between derived values. Mapping from a value to what depends on that value. */ private final Map<Value<?>, Set<Value<?>>> dependents; private DependencyGraph() { this.dependents = new IdentityHashMap<>(); } private DependencyGraph(DependencyGraph source, Map<Value<?>, Value<?>> valueRemapping) { this.dependents = new IdentityHashMap<>(source.dependents.size()); source.dependents.forEach((key, values) -> { Set<Value<?>> newValues = new HashSet<>(values.size()); Value<?> remappedKey = valueRemapping.get(key); Validate.notNull(remappedKey, "Remapped key must not be null."); this.dependents.put(remappedKey, newValues); values.forEach(v -> { Value<?> remappedValue = valueRemapping.get(v); Validate.notNull(remappedValue, "Remapped value must not be null."); newValues.add(remappedValue); }); }); } private void addDependency(Value<?> consumer, Value<?> dependency) { Validate.notNull(consumer, "Consumer must not be null."); dependents.computeIfAbsent(dependency, k -> new HashSet<>()).add(consumer); } private void valueUpdated(Value<?> oldValue, Value<?> newValue) { if (oldValue == newValue) { // Optimization: if we didn't actually update the value, do nothing. return; } CachedValue<?> oldCachedValue = oldValue.cachedValue(); CachedValue<?> newCachedValue = newValue.cachedValue(); if (!CachedValue.haveSameCachedValues(oldCachedValue, newCachedValue)) { // Optimization: don't invalidate consumer caches if the value hasn't changed. invalidateConsumerCaches(oldValue); } Set<Value<?>> oldValueDependents = dependents.remove(oldValue); if (oldValueDependents != null) { dependents.put(newValue, oldValueDependents); } // TODO: Explore optimizations to not have to update every dependent value. dependents.values().forEach(v -> { if (v.remove(oldValue)) { v.add(newValue); } }); } private void invalidateConsumerCaches(Value<?> value) { Queue<Value<?>> unloadQueue = new ArrayDeque<>(); unloadQueue.add(value); while (!unloadQueue.isEmpty()) { Value<?> toUnload = unloadQueue.poll(); toUnload.clearCache(); Set<Value<?>> toUnloadDependents = dependents.remove(toUnload); if (toUnloadDependents != null) { unloadQueue.addAll(toUnloadDependents); } } } public DependencyGraph copy(Map<Value<?>, Value<?>> valueRemapping) { return new DependencyGraph(this, valueRemapping); } } /** * A value stored in this attribute map. */ private interface Value<T> extends SdkAutoCloseable { /** * Resolve the stored value using the provided value source. */ T get(LazyValueSource source); /** * Copy this value, so that modifications like {@link #clearCache()} on this object do not affect the copy. */ Value<T> copy(); /** * If this value is cached, clear that cache. */ void clearCache(); /** * Read the cached value. This will return null if there is no value currently cached. */ CachedValue<T> cachedValue(); } /** * A constant (unchanging) {@link Value}. */ private static class ConstantValue<T> implements Value<T> { private final T value; private ConstantValue(T value) { this.value = value; } @Override public T get(LazyValueSource source) { return value; } @Override public Value<T> copy() { return this; } @Override public void clearCache() { } @Override public CachedValue<T> cachedValue() { return new CachedValue<>(value); } @Override public void close() { closeIfPossible(value); } @Override public String toString() { return "Value(" + value + ")"; } } /** * A value that is derived from other {@link Value}s. */ private static final class DerivedValue<T> implements Value<T> { private final LazyValue<T> lazyValue; private boolean valueCached = false; private T value; private boolean onStack = false; private DerivedValue(LazyValue<T> lazyValue) { this.lazyValue = lazyValue; } private DerivedValue(LazyValue<T> lazyValue, boolean valueCached, T value) { this.lazyValue = lazyValue; this.valueCached = valueCached; this.value = value; } @Override public T get(LazyValueSource source) { primeCache(source); return value; } private void primeCache(LazyValueSource source) { if (!valueCached) { if (onStack) { throw new IllegalStateException("Derived key attempted to read itself"); } try { onStack = true; value = lazyValue.get(source); } finally { onStack = false; } valueCached = true; } } @Override public Value<T> copy() { return new DerivedValue<>(lazyValue, valueCached, value); } @Override public void clearCache() { valueCached = false; } @Override public CachedValue<T> cachedValue() { if (!valueCached) { return null; } return new CachedValue<>(value); } @Override public void close() { closeIfPossible(value); } @Override public String toString() { if (valueCached) { return "Value(" + value + ")"; } return "Value(<<lazy>>)"; } } private static class CachedValue<T> { private final T value; private CachedValue(T value) { this.value = value; } private static boolean haveSameCachedValues(CachedValue<?> lhs, CachedValue<?> rhs) { // If one is null, we can't guarantee that they have the same cached value. if (lhs == null || rhs == null) { return false; } return lhs.value == rhs.value; } } /** * An implementation of {@link LazyValueSource} that expects all values to be cached. */ static class ExpectCachedLazyValueSource implements LazyValueSource { @Override public <T> T get(Key<T> sourceKey) { throw new IllegalStateException("Value should be cached."); } } private static void closeIfPossible(Object object) { // We're explicitly checking for whether the provided object is an ExecutorService instance, because as of // Java 21, it extends AutoCloseable, which triggers an ExecutorService#close call, which in turn can // result in deadlocks. Instead, we safely shut it down, and close any other objects that are closeable. if (object instanceof ExecutorService) { ((ExecutorService) object).shutdown(); } else { IoUtils.closeIfCloseable(object, null); } } }
3,260
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/LookaheadInputStream.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * A wrapper for an {@link InputStream} that allows {@link #peek()}ing one byte ahead in the stream. This is useful for * detecting the end of a stream without actually consuming any data in the process (e.g. so the stream can be passed to * another library that doesn't handle end-of-stream as the first byte well). */ @SdkProtectedApi public class LookaheadInputStream extends FilterInputStream { private Integer next; private Integer nextAtMark; public LookaheadInputStream(InputStream in) { super(in); } public int peek() throws IOException { if (next == null) { next = read(); } return next; } @Override public int read() throws IOException { if (next == null) { return super.read(); } Integer next = this.next; this.next = null; return next; } @Override public int read(byte[] b, int off, int len) throws IOException { if (next == null) { return super.read(b, off, len); } if (len == 0) { return 0; } if (next == -1) { return -1; } b[off] = (byte) (int) next; next = null; if (len == 1) { return 1; } return super.read(b, off + 1, b.length - 1) + 1; } @Override public long skip(long n) throws IOException { if (next == null) { return super.skip(n); } if (n == 0) { return 0; } if (next == -1) { return 0; } next = null; if (n == 1) { return 1; } return super.skip(n - 1); } @Override public int available() throws IOException { if (next == null) { return super.available(); } return super.available() + 1; } @Override public synchronized void mark(int readlimit) { if (next == null) { super.mark(readlimit); } else { nextAtMark = next; super.mark(readlimit - 1); } } @Override public synchronized void reset() throws IOException { next = nextAtMark; super.reset(); } }
3,261
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/Pair.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static software.amazon.awssdk.utils.Validate.paramNotNull; import java.util.function.BiFunction; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Simple struct of two values, possibly of different types. * * @param <LeftT> Left type * @param <RightT> Right Type */ @SdkProtectedApi public final class Pair<LeftT, RightT> { private final LeftT left; private final RightT right; private Pair(LeftT left, RightT right) { this.left = paramNotNull(left, "left"); this.right = paramNotNull(right, "right"); } /** * @return Left value */ public LeftT left() { return this.left; } /** * @return Right value */ public RightT right() { return this.right; } /** * Apply the function to both the left and right values and return the transformed result. * * @param function Function to apply on the {@link Pair} * @param <ReturnT> Transformed return type of {@link BiFunction}. * @return Result of {@link BiFunction} applied on left and right values of the pair. */ public <ReturnT> ReturnT apply(BiFunction<LeftT, RightT, ReturnT> function) { return function.apply(left, right); } @Override public boolean equals(Object obj) { if (!(obj instanceof Pair)) { return false; } Pair other = (Pair) obj; return other.left.equals(left) && other.right.equals(right); } @Override public int hashCode() { return getClass().hashCode() + left.hashCode() + right.hashCode(); } @Override public String toString() { return "Pair(left=" + left + ", right=" + right + ")"; } public static <LeftT, RightT> Pair<LeftT, RightT> of(LeftT left, RightT right) { return new Pair<>(left, right); } }
3,262
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/BinaryUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.io.ByteArrayInputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Base64; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.internal.Base16Lower; /** * Utilities for encoding and decoding binary data to and from different forms. */ @SdkProtectedApi public final class BinaryUtils { private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private BinaryUtils() { } /** * Converts byte data to a Hex-encoded string in lower case. * * @param data * data to hex encode. * * @return hex-encoded string. */ public static String toHex(byte[] data) { return Base16Lower.encodeAsString(data); } /** * Converts a Hex-encoded data string to the original byte data. * * @param hexData * hex-encoded data to decode. * @return decoded data from the hex string. */ public static byte[] fromHex(String hexData) { return Base16Lower.decode(hexData); } /** * Converts byte data to a Base64-encoded string. * @param data * * data to Base64 encode. * @return encoded Base64 string. */ public static String toBase64(byte[] data) { return data == null ? null : new String(toBase64Bytes(data), StandardCharsets.UTF_8); } /** * Converts byte data to a Base64-encoded string. * @param data * * data to Base64 encode. * @return encoded Base64 string. */ public static byte[] toBase64Bytes(byte[] data) { return data == null ? null : Base64.getEncoder().encode(data); } /** * Converts a Base64-encoded string to the original byte data. * * @param b64Data * a Base64-encoded string to decode. * * @return bytes decoded from a Base64 string. */ public static byte[] fromBase64(String b64Data) { return b64Data == null ? null : Base64.getDecoder().decode(b64Data); } /** * Converts a Base64-encoded string to the original byte data. * * @param b64Data * a Base64-encoded string to decode. * * @return bytes decoded from a Base64 string. */ public static byte[] fromBase64Bytes(byte[] b64Data) { return b64Data == null ? null : Base64.getDecoder().decode(b64Data); } /** * Wraps a ByteBuffer in an InputStream. If the input {@code byteBuffer} * is null, returns an empty stream. * * @param byteBuffer The ByteBuffer to wrap. * * @return An InputStream wrapping the ByteBuffer content. */ public static ByteArrayInputStream toStream(ByteBuffer byteBuffer) { if (byteBuffer == null) { return new ByteArrayInputStream(new byte[0]); } return new ByteArrayInputStream(copyBytesFrom(byteBuffer)); } /** * Returns an immutable copy of the given {@code ByteBuffer}. * <p> * The new buffer's position will be set to the position of the given {@code ByteBuffer}, but the mark if defined will be * ignored. * <p> * <b>NOTE:</b> this method intentionally converts direct buffers to non-direct though there is no guarantee this will always * be the case, if this is required see {@link #toNonDirectBuffer(ByteBuffer)} * * @param bb the source {@code ByteBuffer} to copy. * @return a read only {@code ByteBuffer}. */ public static ByteBuffer immutableCopyOf(ByteBuffer bb) { if (bb == null) { return null; } ByteBuffer readOnlyCopy = bb.asReadOnlyBuffer(); readOnlyCopy.rewind(); ByteBuffer cloned = ByteBuffer.allocate(readOnlyCopy.capacity()) .put(readOnlyCopy); cloned.position(bb.position()); cloned.limit(bb.limit()); return cloned.asReadOnlyBuffer(); } /** * Returns an immutable copy of the remaining bytes of the given {@code ByteBuffer}. * <p> * <b>NOTE:</b> this method intentionally converts direct buffers to non-direct though there is no guarantee this will always * be the case, if this is required see {@link #toNonDirectBuffer(ByteBuffer)} * * @param bb the source {@code ByteBuffer} to copy. * @return a read only {@code ByteBuffer}. */ public static ByteBuffer immutableCopyOfRemaining(ByteBuffer bb) { if (bb == null) { return null; } ByteBuffer readOnlyCopy = bb.asReadOnlyBuffer(); ByteBuffer cloned = ByteBuffer.allocate(readOnlyCopy.remaining()) .put(readOnlyCopy); cloned.flip(); return cloned.asReadOnlyBuffer(); } /** * Returns a copy of the given {@code DirectByteBuffer} from its current position as a non-direct {@code HeapByteBuffer} * <p> * The new buffer's position will be set to the position of the given {@code ByteBuffer}, but the mark if defined will be * ignored. * * @param bb the source {@code ByteBuffer} to copy. * @return {@code ByteBuffer}. */ public static ByteBuffer toNonDirectBuffer(ByteBuffer bb) { if (bb == null) { return null; } if (!bb.isDirect()) { throw new IllegalArgumentException("Provided ByteBuffer is already non-direct"); } int sourceBufferPosition = bb.position(); ByteBuffer readOnlyCopy = bb.asReadOnlyBuffer(); readOnlyCopy.rewind(); ByteBuffer cloned = ByteBuffer.allocate(bb.capacity()) .put(readOnlyCopy); cloned.rewind(); cloned.position(sourceBufferPosition); if (bb.isReadOnly()) { return cloned.asReadOnlyBuffer(); } return cloned; } /** * Returns a copy of all the bytes from the given <code>ByteBuffer</code>, * from the beginning to the buffer's limit; or null if the input is null. * <p> * The internal states of the given byte buffer will be restored when this * method completes execution. * <p> * When handling <code>ByteBuffer</code> from user's input, it's typical to * call the {@link #copyBytesFrom(ByteBuffer)} instead of * {@link #copyAllBytesFrom(ByteBuffer)} so as to account for the position * of the input <code>ByteBuffer</code>. The opposite is typically true, * however, when handling <code>ByteBuffer</code> from withint the * unmarshallers of the low-level clients. */ public static byte[] copyAllBytesFrom(ByteBuffer bb) { if (bb == null) { return null; } if (bb.hasArray()) { return Arrays.copyOfRange( bb.array(), bb.arrayOffset(), bb.arrayOffset() + bb.limit()); } ByteBuffer copy = bb.asReadOnlyBuffer(); copy.rewind(); byte[] dst = new byte[copy.remaining()]; copy.get(dst); return dst; } 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; } /** * Returns a copy of the bytes from the given <code>ByteBuffer</code>, * ranging from the the buffer's current position to the buffer's limit; or * null if the input is null. * <p> * The internal states of the given byte buffer will be restored when this * method completes execution. * <p> * When handling <code>ByteBuffer</code> from user's input, it's typical to * call the {@link #copyBytesFrom(ByteBuffer)} instead of * {@link #copyAllBytesFrom(ByteBuffer)} so as to account for the position * of the input <code>ByteBuffer</code>. The opposite is typically true, * however, when handling <code>ByteBuffer</code> from withint the * unmarshallers of the low-level clients. */ public static byte[] copyBytesFrom(ByteBuffer bb) { if (bb == null) { return null; } if (bb.hasArray()) { return Arrays.copyOfRange( bb.array(), bb.arrayOffset() + bb.position(), bb.arrayOffset() + bb.limit()); } byte[] dst = new byte[bb.remaining()]; bb.asReadOnlyBuffer().get(dst); return dst; } /** * This behaves identically to {@link #copyBytesFrom(ByteBuffer)}, except * that the readLimit acts as a limit to the number of bytes that should be * read from the byte buffer. */ public static byte[] copyBytesFrom(ByteBuffer bb, int readLimit) { if (bb == null) { return null; } int numBytesToRead = Math.min(readLimit, bb.limit() - bb.position()); if (bb.hasArray()) { return Arrays.copyOfRange( bb.array(), bb.arrayOffset() + bb.position(), bb.arrayOffset() + bb.position() + numBytesToRead); } byte[] dst = new byte[numBytesToRead]; bb.asReadOnlyBuffer().get(dst); return dst; } }
3,263
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/MapUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.annotations.SdkProtectedApi; @SdkProtectedApi public final class MapUtils { private MapUtils() { } public static <K, V> Map<K, V> of(K k1, V v1) { Map<K, V> m = new HashMap<>(); m.put(k1, v1); return m; } public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2) { Map<K, V> m = new HashMap<>(); m.put(k1, v1); m.put(k2, v2); return m; } public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) { Map<K, V> m = new HashMap<>(); m.put(k1, v1); m.put(k2, v2); m.put(k3, v3); return m; } public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { Map<K, V> m = new HashMap<>(); m.put(k1, v1); m.put(k2, v2); m.put(k3, v3); m.put(k4, v4); return m; } public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { Map<K, V> m = new HashMap<>(); m.put(k1, v1); m.put(k2, v2); m.put(k3, v3); m.put(k4, v4); m.put(k5, v5); return m; } public static <K, V> Map<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) { Map<K, V> m = new HashMap<>(); m.put(k1, v1); m.put(k2, v2); m.put(k3, v3); m.put(k4, v4); m.put(k5, v5); m.put(k6, v6); return m; } }
3,264
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/NumericUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.time.Duration; import software.amazon.awssdk.annotations.SdkProtectedApi; @SdkProtectedApi public final class NumericUtils { private NumericUtils() { } /** * Returns the {@code int} nearest in value to {@code value}. * * @param value any {@code long} value * @return the same value cast to {@code int} if it is in the range of the {@code int} type, * {@link Integer#MAX_VALUE} if it is too large, or {@link Integer#MIN_VALUE} if it is too * small */ public static int saturatedCast(long value) { if (value > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } if (value < Integer.MIN_VALUE) { return Integer.MIN_VALUE; } return (int) value; } public static Duration min(Duration a, Duration b) { return (a.compareTo(b) < 0) ? a : b; } public static Duration max(Duration a, Duration b) { return (a.compareTo(b) > 0) ? a : b; } }
3,265
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ReflectionMethodInvoker.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * This class acts as a proxy to invoke a specific method on objects of a specific class. It will use the JDK's * reflection library to find and invoke the method. * <p> * The relatively expensive call to find the correct method on the class is lazy and will not be performed until the * first invocation or until the invoker is explicitly initialized. Once found, the method is cached so repeated * calls to initialize() or invoke() will not incur the reflection cost of searching for the method on the class. * <p> * Example: * {@code * ReflectionMethodInvoker<String, Integer> invoker = * new ReflectionMethodInvoker<String, Integer>(String.class, Integer.class, "indexOf", String.class, int.class); * invoker.invoke("ababab", "ab", 1); // This is equivalent to calling "ababab".indexOf("ab", 1); * } * @param <T> The class type that has the method to be invoked. * @param <R> The expected return type of the method invocation. */ @SdkProtectedApi public class ReflectionMethodInvoker<T, R> { private final Class<T> clazz; private final String methodName; private final Class<R> returnType; private final Class<?>[] parameterTypes; private Method targetMethod; /** * Construct an instance of {@code ReflectionMethodInvoker}. * <p> * This constructor will not make any reflection calls as part of initialization; i.e. no validation of the * existence of the given method signature will occur. * @param clazz The class that has the method to be invoked. * @param returnType The expected return class of the method invocation. The object returned by the invocation * will be cast to this class. * @param methodName The name of the method to invoke. * @param parameterTypes The classes of the parameters of the method to invoke. */ public ReflectionMethodInvoker(Class<T> clazz, Class<R> returnType, String methodName, Class<?>... parameterTypes) { this.clazz = clazz; this.methodName = methodName; this.returnType = returnType; this.parameterTypes = parameterTypes; } /** * Attempt to invoke the method this proxy targets for on the given object with the given arguments. If the * invoker has not yet been initialized, an attempt to initialize the invoker will be made first. If the call * succeeds the invoker will be in an initialized state after this call and future calls to the same method will * not incur an initialization cost. If the call fails because the target method could not be found, the invoker * will remain in an uninitialized state after the exception is thrown. * @param obj The object to invoke the method on. * @param args The arguments to pass to the method. These arguments must match the signature of the method. * @return The returned value of the method cast to the 'returnType' class that this proxy was initialized with. * @throws NoSuchMethodException if the JVM could not find a method matching the signature specified in the * initialization of this proxy. * @throws RuntimeException if any other exception is thrown when attempting to invoke the method or by the * method itself. The cause of this exception will be the exception that was actually thrown. */ 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); } } /** * Initializes the method invoker by finding and caching the target method from the target class that will be used * for subsequent invoke operations. If the invoker is already initialized this call will do nothing. * @throws NoSuchMethodException if the JVM could not find a method matching the signature specified in the * initialization of this proxy. */ public void initialize() throws NoSuchMethodException { getTargetMethod(); } /** * Gets the initialization state of the invoker. * @return true if the invoker has been initialized and the method has been cached for invocation; otherwise false. */ public boolean isInitialized() { return targetMethod != null; } private Method getTargetMethod() throws NoSuchMethodException { if (targetMethod != null) { return targetMethod; } try { targetMethod = clazz.getMethod(methodName, parameterTypes); return targetMethod; } catch (RuntimeException e) { throw new RuntimeException(createInvocationErrorMessage(), e); } } private String createInvocationErrorMessage() { return String.format("Failed to reflectively invoke method %s on %s", methodName, clazz.getName()); } }
3,266
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/Logger.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static software.amazon.awssdk.utils.StringUtils.lowerCase; import java.util.function.Supplier; import org.slf4j.LoggerFactory; import org.slf4j.event.Level; import software.amazon.awssdk.annotations.SdkProtectedApi; @SdkProtectedApi public final class Logger { private final org.slf4j.Logger log; Logger(org.slf4j.Logger log) { this.log = log; } public org.slf4j.Logger logger() { return log; } /** * Checks if info is enabled and if so logs the supplied message * @param msg - supplier for the log message */ public void info(Supplier<String> msg) { if (log.isInfoEnabled()) { log.info(msg.get()); } } /** * Checks if info is enabled and if so logs the supplied message and exception * @param msg - supplier for the log message * @param throwable - a throwable to log */ public void info(Supplier<String> msg, Throwable throwable) { if (log.isInfoEnabled()) { log.info(msg.get(), throwable); } } /** * Checks if error is enabled and if so logs the supplied message * @param msg - supplier for the log message */ public void error(Supplier<String> msg) { if (log.isErrorEnabled()) { log.error(msg.get()); } } /** * Checks if error is enabled and if so logs the supplied message and exception * @param msg - supplier for the log message * @param throwable - a throwable to log */ public void error(Supplier<String> msg, Throwable throwable) { if (log.isErrorEnabled()) { log.error(msg.get(), throwable); } } /** * Checks if debug is enabled and if so logs the supplied message * @param msg - supplier for the log message */ public void debug(Supplier<String> msg) { if (log.isDebugEnabled()) { log.debug(msg.get()); } } /** * Checks if debug is enabled and if so logs the supplied message and exception * @param msg - supplier for the log message * @param throwable - a throwable to log */ public void debug(Supplier<String> msg, Throwable throwable) { if (log.isDebugEnabled()) { log.debug(msg.get(), throwable); } } /** * Checks if warn is enabled and if so logs the supplied message * @param msg - supplier for the log message */ public void warn(Supplier<String> msg) { if (log.isWarnEnabled()) { log.warn(msg.get()); } } /** * Checks if warn is enabled and if so logs the supplied message and exception * @param msg - supplier for the log message * @param throwable - a throwable to log */ public void warn(Supplier<String> msg, Throwable throwable) { if (log.isWarnEnabled()) { log.warn(msg.get(), throwable); } } /** * Checks if trace is enabled and if so logs the supplied message * @param msg - supplier for the log message */ public void trace(Supplier<String> msg) { if (log.isTraceEnabled()) { log.trace(msg.get()); } } /** * Checks if trace is enabled and if so logs the supplied message and exception * @param msg - supplier for the log message * @param throwable - a throwable to log */ public void trace(Supplier<String> msg, Throwable throwable) { if (log.isTraceEnabled()) { log.trace(msg.get(), throwable); } } /** * Determines if the provided log-level is enabled. * @param logLevel the SLF4J log level enum * @return whether that level is enabled */ public boolean isLoggingLevelEnabled(Level logLevel) { switch (logLevel) { case TRACE: return log.isTraceEnabled(); case DEBUG: return log.isDebugEnabled(); case INFO: return log.isInfoEnabled(); case WARN: return log.isWarnEnabled(); case ERROR: return log.isErrorEnabled(); default: throw new IllegalStateException("Unsupported log level: " + logLevel); } } /** * Determines if the log-level passed is enabled * @param logLevel a string representation of the log level, e.g. "debug" * @return whether or not that level is enable */ public boolean isLoggingLevelEnabled(String logLevel) { String lowerLogLevel = lowerCase(logLevel); switch (lowerLogLevel) { case "debug": return log.isDebugEnabled(); case "trace": return log.isTraceEnabled(); case "error": return log.isErrorEnabled(); case "info": return log.isInfoEnabled(); case "warn": return log.isWarnEnabled(); default: throw new IllegalArgumentException("Unknown log level: " + lowerLogLevel); } } /** * Log a message at the given log level (if it is enabled). * * @param logLevel the SLF4J log level * @param msg supplier for the log message */ public void log(Level logLevel, Supplier<String> msg) { switch (logLevel) { case TRACE: trace(msg); break; case DEBUG: debug(msg); break; case INFO: info(msg); break; case WARN: warn(msg); break; case ERROR: error(msg); break; default: throw new IllegalStateException("Unsupported log level: " + logLevel); } } /** * Static factory to get a logger instance for a given class * @param clz - class to get the logger for * @return a Logger instance */ public static Logger loggerFor(Class<?> clz) { return new Logger(LoggerFactory.getLogger(clz)); } /** * Static factory to get a logger instance with a specific name. * @param name - The name of the logger to create * @return a Logger instance */ public static Logger loggerFor(String name) { return new Logger(LoggerFactory.getLogger(name)); } }
3,267
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/CompletableFutureUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Utility class for working with {@link CompletableFuture}. */ @SdkProtectedApi public final class CompletableFutureUtils { private static final Logger log = Logger.loggerFor(CompletableFutureUtils.class); private CompletableFutureUtils() { } /** * Convenience method for creating a future that is immediately completed * exceptionally with the given {@code Throwable}. * <p> * Similar to {@code CompletableFuture#failedFuture} which was added in * Java 9. * * @param t The failure. * @param <U> The type of the element. * @return The failed future. */ public static <U> CompletableFuture<U> failedFuture(Throwable t) { CompletableFuture<U> cf = new CompletableFuture<>(); cf.completeExceptionally(t); return cf; } /** * Wraps the given error in a {@link CompletionException} if necessary. * Useful if an exception needs to be rethrown from within {@link * CompletableFuture#handle(java.util.function.BiFunction)} or similar * methods. * * @param t The error. * @return The error as a CompletionException. */ public static CompletionException errorAsCompletionException(Throwable t) { if (t instanceof CompletionException) { return (CompletionException) t; } return new CompletionException(t); } /** * Forward the {@code Throwable} from {@code src} to {@code dst}. * @param src The source of the {@code Throwable}. * @param dst The destination where the {@code Throwable} will be forwarded to. * * @return {@code src}. */ public static <T> CompletableFuture<T> forwardExceptionTo(CompletableFuture<T> src, CompletableFuture<?> dst) { src.whenComplete((r, e) -> { if (e != null) { dst.completeExceptionally(e); } }); return src; } /** * Forward the {@code Throwable} that can be transformed as per the transformationFunction * from {@code src} to {@code dst}. * @param src The source of the {@code Throwable}. * @param dst The destination where the {@code Throwable} will be forwarded to * @param transformationFunction Transformation function taht will be applied on to the forwarded exception. * @return */ public static <T> CompletableFuture<T> forwardTransformedExceptionTo(CompletableFuture<T> src, CompletableFuture<?> dst, Function<Throwable, Throwable> transformationFunction) { src.whenComplete((r, e) -> { if (e != null) { dst.completeExceptionally(transformationFunction.apply(e)); } }); return src; } /** * Completes the {@code dst} future based on the result of the {@code src} future asynchronously on * the provided {@link Executor} and return the {@code src} future. * * @param src The source {@link CompletableFuture} * @param dst The destination where the {@code Throwable} or response will be forwarded to. * @return the {@code src} future. */ public static <T> CompletableFuture<T> forwardResultTo(CompletableFuture<T> src, CompletableFuture<T> dst) { src.whenComplete((r, e) -> { if (e != null) { dst.completeExceptionally(e); } else { dst.complete(r); } }); return src; } /** * Completes the {@code dst} future based on the result of the {@code src} future asynchronously on * the provided {@link Executor} and return the {@code src} future. * * @param src The source {@link CompletableFuture} * @param dst The destination where the {@code Throwable} or response will be forwarded to. * @param executor the executor to complete the des future * @return the {@code src} future. */ public static <T> CompletableFuture<T> forwardResultTo(CompletableFuture<T> src, CompletableFuture<T> dst, Executor executor) { src.whenCompleteAsync((r, e) -> { if (e != null) { dst.completeExceptionally(e); } else { dst.complete(r); } }, executor); return src; } /** * Completes the {@code dst} future based on the result of the {@code src} future, synchronously, * after applying the provided transformation {@link Function} if successful. * * @param src The source {@link CompletableFuture} * @param dst The destination where the {@code Throwable} or transformed result will be forwarded to. * @return the {@code src} future. */ public static <SourceT, DestT> CompletableFuture<SourceT> forwardTransformedResultTo(CompletableFuture<SourceT> src, CompletableFuture<DestT> dst, Function<SourceT, DestT> function) { src.whenComplete((r, e) -> { if (e != null) { dst.completeExceptionally(e); } else { dst.complete(function.apply(r)); } }); return src; } /** * Similar to {@link CompletableFuture#allOf(CompletableFuture[])}, but * when any future is completed exceptionally, forwards the * exception to other futures. * * @param futures The futures. * @return The new future that is completed when all the futures in {@code * futures} are. */ public static CompletableFuture<Void> allOfExceptionForwarded(CompletableFuture<?>[] futures) { CompletableFuture<Void> anyFail = anyFail(futures); anyFail.whenComplete((r, t) -> { if (t != null) { for (CompletableFuture<?> cf : futures) { cf.completeExceptionally(t); } } }); return CompletableFuture.allOf(futures); } /** * Returns a new CompletableFuture that is completed when any of * the given CompletableFutures completes exceptionally. * * @param futures the CompletableFutures * @return a new CompletableFuture that is completed if any provided * future completed exceptionally. */ static CompletableFuture<Void> anyFail(CompletableFuture<?>[] futures) { CompletableFuture<Void> completableFuture = new CompletableFuture<>(); for (CompletableFuture<?> future : futures) { future.whenComplete((r, t) -> { if (t != null) { completableFuture.completeExceptionally(t); } }); } return completableFuture; } public static <T> T joinInterruptibly(CompletableFuture<T> future) { try { return future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new CompletionException("Interrupted while waiting on a future.", e); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof Error) { throw (Error) cause; } throw new CompletionException(cause); } } public static void joinInterruptiblyIgnoringFailures(CompletableFuture<?> future) { try { future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (ExecutionException e) { // Ignore } } /** * Joins (interruptibly) on the future, and re-throws any RuntimeExceptions or Errors just like the async task would have * thrown if it was executed synchronously. */ public static <T> T joinLikeSync(CompletableFuture<T> future) { try { return joinInterruptibly(future); } catch (CompletionException e) { Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { // Make sure we don't lose the context of where the join is in the stack... cause.addSuppressed(new RuntimeException("Task failed.")); throw (RuntimeException) cause; } throw e; } } }
3,268
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/CollectionUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collector; import java.util.stream.Collectors; import software.amazon.awssdk.annotations.SdkProtectedApi; @SdkProtectedApi public final class CollectionUtils { private CollectionUtils() { } public static boolean isNullOrEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } public static boolean isNullOrEmpty(Map<?, ?> map) { return map == null || map.isEmpty(); } public static boolean isNotEmpty(Map<?, ?> map) { return map != null && !map.isEmpty(); } /** * Returns a new list containing the second list appended to the first list. */ public static <T> List<T> mergeLists(List<T> list1, List<T> list2) { List<T> merged = new LinkedList<>(); if (list1 != null) { merged.addAll(list1); } if (list2 != null) { merged.addAll(list2); } return merged; } /** * @param list List to get first element from. * @param <T> Type of elements in the list. * @return The first element in the list if it exists. If the list is null or empty this will * return null. */ public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } /** * Perform a deep copy of the provided map of lists. This only performs a deep copy of the map and lists. Entries are not * copied, so care should be taken to ensure that entries are immutable if preventing unwanted mutations of the elements is * desired. */ public static <T, U> Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map) { return deepCopyMap(map, () -> new LinkedHashMap<>(map.size())); } /** * Perform a deep copy of the provided map of lists. This only performs a deep copy of the map and lists. Entries are not * copied, so care should be taken to ensure that entries are immutable if preventing unwanted mutations of the elements is * desired. */ public static <T, U> Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map, Supplier<Map<T, List<U>>> mapConstructor) { Map<T, List<U>> result = mapConstructor.get(); map.forEach((k, v) -> result.put(k, new ArrayList<>(v))); return result; } public static <T, U> Map<T, List<U>> unmodifiableMapOfLists(Map<T, List<U>> map) { return new UnmodifiableMapOfLists<>(map); } /** * Perform a deep copy of the provided map of lists, and make the result unmodifiable. * * This is equivalent to calling {@link #deepCopyMap} followed by {@link #unmodifiableMapOfLists}. */ public static <T, U> Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map) { return unmodifiableMapOfLists(deepCopyMap(map)); } /** * Perform a deep copy of the provided map of lists, and make the result unmodifiable. * * This is equivalent to calling {@link #deepCopyMap} followed by {@link #unmodifiableMapOfLists}. */ public static <T, U> Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map, Supplier<Map<T, List<U>>> mapConstructor) { return unmodifiableMapOfLists(deepCopyMap(map, mapConstructor)); } /** * Collect a stream of {@link Map.Entry} to a {@link Map} with the same key/value types * @param <K> the key type * @param <V> the value type * @return a map */ public static <K, V> Collector<Map.Entry<K, V>, ?, Map<K, V>> toMap() { return Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue); } /** * Transforms the values of a map to another map with the same keys, using the supplied function. * * @param inputMap the input map * @param mapper the function used to transform the map values * @param <K> the key type * @param <VInT> the value type for the input map * @param <VOutT> the value type for the output map * @return a map */ public static <K, VInT, VOutT> Map<K, VOutT> mapValues(Map<K, VInT> inputMap, Function<VInT, VOutT> mapper) { return inputMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> mapper.apply(e.getValue()))); } /** * Filters a map based on a condition * * @param map the input map * @param condition the predicate to filter on * @param <K> the key type * @param <V> the value type * @return the filtered map */ public static <K, V> Map<K, V> filterMap(Map<K, V> map, Predicate<Map.Entry<K, V>> condition) { return map.entrySet() .stream() .filter(condition) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } /** * Return a new map that is the inverse of the supplied map, with the values becoming the keys * and vice versa. Requires the values to be unique. * * @param inputMap a map where both the keys and values are unique * @param <K> the key type * @param <V> the value type * @return a map */ public static <K, V> Map<K, V> inverseMap(Map<V, K> inputMap) { return inputMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey)); } /** * For a collection of values of type {@code V} that can all be converted to type {@code K}, create a map that * indexes all of the values by {@code K}. This requires that no two values map to the same index. * * @param values the collection of values to index * @param indexFunction the function used to convert a value to its index * @param <K> the index (or key) type * @param <V> the value type * @return a (modifiable) map that indexes K to its unique value V * @throws IllegalArgumentException if any of the values map to the same index */ public static <K, V> Map<K, V> uniqueIndex(Iterable<V> values, Function<? super V, K> indexFunction) { Map<K, V> map = new HashMap<>(); for (V value : values) { K index = indexFunction.apply(value); V prev = map.put(index, value); Validate.isNull(prev, "No duplicate indices allowed but both %s and %s have the same index: %s", prev, value, index); } return map; } }
3,269
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/Md5Utils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.slf4j.LoggerFactory; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Utility methods for computing MD5 sums. */ @SdkProtectedApi public final class Md5Utils { private static final int SIXTEEN_K = 1 << 14; private Md5Utils() { } /** * Computes the MD5 hash of the data in the given input stream and returns * it as an array of bytes. * Note this method closes the given input stream upon completion. */ public static byte[] computeMD5Hash(InputStream is) throws IOException { BufferedInputStream bis = new BufferedInputStream(is); try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); byte[] buffer = new byte[SIXTEEN_K]; int bytesRead; while ((bytesRead = bis.read(buffer, 0, buffer.length)) != -1) { messageDigest.update(buffer, 0, bytesRead); } return messageDigest.digest(); } catch (NoSuchAlgorithmException e) { // should never get here throw new IllegalStateException(e); } finally { try { bis.close(); } catch (Exception e) { LoggerFactory.getLogger(Md5Utils.class).debug("Unable to close input stream of hash candidate: {}", e); } } } /** * Returns the MD5 in base64 for the data from the given input stream. * Note this method closes the given input stream upon completion. */ public static String md5AsBase64(InputStream is) throws IOException { return BinaryUtils.toBase64(computeMD5Hash(is)); } /** * Computes the MD5 hash of the given data and returns it as an array of * bytes. */ public static byte[] computeMD5Hash(byte[] input) { try { MessageDigest md = MessageDigest.getInstance("MD5"); return md.digest(input); } catch (NoSuchAlgorithmException e) { // should never get here throw new IllegalStateException(e); } } /** * Returns the MD5 in base64 for the given byte array. */ public static String md5AsBase64(byte[] input) { return BinaryUtils.toBase64(computeMD5Hash(input)); } /** * Computes the MD5 of the given file. */ public static byte[] computeMD5Hash(File file) throws FileNotFoundException, IOException { return computeMD5Hash(new FileInputStream(file)); } /** * Returns the MD5 in base64 for the given file. */ public static String md5AsBase64(File file) throws FileNotFoundException, IOException { return BinaryUtils.toBase64(computeMD5Hash(file)); } }
3,270
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ScheduledExecutorUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static software.amazon.awssdk.utils.Validate.paramNotNull; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; /** * Utilities that make it easier to create, use and destroy * {@link ScheduledExecutor}s. */ @SdkProtectedApi public final class ScheduledExecutorUtils { private ScheduledExecutorUtils() { } /** * Wrap a scheduled executor in a type that cannot be closed, or shut down. */ public static ScheduledExecutorService unmanagedScheduledExecutor(ScheduledExecutorService executor) { if (executor instanceof UnmanagedScheduledExecutorService) { return executor; } if (executor == null) { return null; } return new UnmanagedScheduledExecutorService(executor); } /** * Unwrap a scheduled executor. Requires the UnmanagedScheduledExecutorService to be the "outer" type. */ public static ScheduledExecutorService unwrapUnmanagedScheduledExecutor(ScheduledExecutorService executor) { if (executor instanceof UnmanagedScheduledExecutorService) { return ((UnmanagedScheduledExecutorService) executor).delegate; } return executor; } /** * Wrapper around {@link ScheduledExecutorService} to prevent it from being * closed. Used when the customer provides * a custom scheduled executor service in which case they are responsible for * the lifecycle of it. */ @SdkTestInternalApi public static final class UnmanagedScheduledExecutorService implements ScheduledExecutorService { private final ScheduledExecutorService delegate; UnmanagedScheduledExecutorService(ScheduledExecutorService delegate) { this.delegate = paramNotNull(delegate, "ScheduledExecutorService"); } public ScheduledExecutorService scheduledExecutorService() { return delegate; } @Override public void shutdown() { // Do nothing, this executor service is managed by the customer. } @Override public List<Runnable> shutdownNow() { return new ArrayList<>(); } @Override public boolean isShutdown() { return delegate.isShutdown(); } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return delegate.awaitTermination(timeout, unit); } @Override public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { return delegate.schedule(command, delay, unit); } @Override public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) { return delegate.schedule(callable, delay, unit); } @Override public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { return delegate.scheduleAtFixedRate(command, initialDelay, period, unit); } @Override public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { return delegate.scheduleWithFixedDelay(command, initialDelay, delay, unit); } @Override public boolean isTerminated() { return delegate.isTerminated(); } @Override public <T> Future<T> submit(Callable<T> task) { return delegate.submit(task); } @Override public <T> Future<T> submit(Runnable task, T result) { return delegate.submit(task, result); } @Override public Future<?> submit(Runnable task) { return delegate.submit(task); } @Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException { return delegate.invokeAll(tasks); } @Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { return delegate.invokeAll(tasks, timeout, unit); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { return delegate.invokeAny(tasks); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return delegate.invokeAny(tasks, timeout, unit); } @Override public void execute(Runnable command) { delegate.execute(command); } } }
3,271
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/StringInputStream.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Simple wrapper for ByteArrayInputStream that will automatically encode the * string as UTF-8 data, and still allows access to the original string. */ @SdkProtectedApi public class StringInputStream extends ByteArrayInputStream { private final String string; public StringInputStream(String s) { super(s.getBytes(StandardCharsets.UTF_8)); this.string = s; } /** * Returns the original string specified when this input stream was * constructed. * * @return The original string specified when this input stream was * constructed. */ public String getString() { return string; } }
3,272
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ComparableUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.stream.Stream; import software.amazon.awssdk.annotations.SdkProtectedApi; @SdkProtectedApi public final class ComparableUtils { private ComparableUtils() { } /** * Does a safe comparison of two {@link Comparable} objects accounting for nulls * * @param d1 * First object * @param d2 * Second object * @return A positive number if the object double is larger, a negative number if the second * object is larger, or 0 if they are equal. Null is considered less than any non-null * value */ 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; } } /** * Get the minimum value from a list of comparable vales. * * @param values The values from which the minimum should be extracted. * @return The minimum value in the list. */ @SafeVarargs public static <T extends Comparable<T>> T minimum(T... values) { return values == null ? null : Stream.of(values).min(Comparable::compareTo).orElse(null); } /** * Get the maximum value from a list of comparable vales. * * @param values The values from which the maximum should be extracted. * @return The maximum value in the list. */ @SafeVarargs public static <T extends Comparable<T>> T maximum(T... values) { return values == null ? null : Stream.of(values).max(Comparable::compareTo).orElse(null); } }
3,273
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/OptionalUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.Optional; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Functions that make working with optionals easier. */ @SdkProtectedApi public final class OptionalUtils { /** * This class should be used statically. */ private OptionalUtils() { } /** * Attempt to find a present-valued optional in a list of optionals. * * @param firstValue The first value that should be checked. * @param fallbackValues The suppliers we should check in order for a present value. * @return The first present value (or Optional.empty() if none are present) */ @SafeVarargs public static <T> Optional<T> firstPresent(Optional<T> firstValue, Supplier<Optional<T>>... fallbackValues) { if (firstValue.isPresent()) { return firstValue; } for (Supplier<Optional<T>> fallbackValueSupplier : fallbackValues) { Optional<T> fallbackValue = fallbackValueSupplier.get(); if (fallbackValue.isPresent()) { return fallbackValue; } } return Optional.empty(); } public static <T> Optional<T> firstPresent(Optional<T> firstValue, Supplier<T> fallbackValue) { if (firstValue.isPresent()) { return firstValue; } return Optional.ofNullable(fallbackValue.get()); } }
3,274
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/Either.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Represents a value that can be one of two types. * * @param <L> Left type * @param <R> Right type */ @SdkProtectedApi public final class Either<L, R> { private final Optional<L> left; private final Optional<R> right; private Either(Optional<L> l, Optional<R> r) { left = l; right = r; } /** * Maps the Either to a type and returns the resolved value (which may be from the left or the right value). * * @param lFunc Function that maps the left value if present. * @param rFunc Function that maps the right value if present. * @param <T> Type that both the left and right should be mapped to. * @return Mapped value from either lFunc or rFunc depending on which value is present. */ public <T> T map( Function<? super L, ? extends T> lFunc, Function<? super R, ? extends T> rFunc) { return left.<T>map(lFunc).orElseGet(() -> right.map(rFunc).get()); } /** * Map the left most value and return a new Either reflecting the new types. * * @param lFunc Function that maps the left value if present. * @param <T> New type of left value. * @return New Either bound to the new left type and the same right type. */ public <T> Either<T, R> mapLeft(Function<? super L, ? extends T> lFunc) { return new Either<>(left.map(lFunc), right); } /** * Map the right most value and return a new Either reflecting the new types. * * @param rFunc Function that maps the right value if present. * @param <T> New type of right value. * @return New Either bound to the same left type and the new right type. */ public <T> Either<L, T> mapRight(Function<? super R, ? extends T> rFunc) { return new Either<>(left, right.map(rFunc)); } /** * Apply the consumers to the left or the right value depending on which is present. * * @param lFunc Consumer of left value, invoked if left value is present. * @param rFunc Consumer of right value, invoked if right value is present. */ public void apply(Consumer<? super L> lFunc, Consumer<? super R> rFunc) { left.ifPresent(lFunc); right.ifPresent(rFunc); } /** * Create a new Either with the left type. * * @param value Left value * @param <L> Left type * @param <R> Right type */ public static <L, R> Either<L, R> left(L value) { return new Either<>(Optional.of(value), Optional.empty()); } /** * Create a new Either with the right type. * * @param value Right value * @param <L> Left type * @param <R> Right type */ public static <L, R> Either<L, R> right(R value) { return new Either<>(Optional.empty(), Optional.of(value)); } /** * @return the left value */ public Optional<L> left() { return left; } /** * @return the right value */ public Optional<R> right() { return right; } /** * Create a new {@code Optional<Either>} from two possibly null values. * * If both values are null, {@link Optional#empty()} is returned. Only one of the left or right values * is allowed to be non-null, otherwise an {@link IllegalArgumentException} is thrown. * @param left The left value (possibly null) * @param right The right value (possibly null) * @param <L> Left type * @param <R> Right type * @return an Optional Either representing one of the two values or empty if both are null */ 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)); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Either)) { return false; } Either<?, ?> either = (Either<?, ?>) o; return left.equals(either.left) && right.equals(either.right); } @Override public int hashCode() { return 31 * left.hashCode() + right.hashCode(); } }
3,275
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/UserHomeDirectoryUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.Optional; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * Load the home directory that should be used for the stored file. This will check the same environment variables as the CLI * to identify the location of home, before falling back to java-specific resolution. */ @SdkProtectedApi public final class UserHomeDirectoryUtils { private UserHomeDirectoryUtils() { } public static String userHomeDirectory() { // CHECKSTYLE:OFF - To match the logic of the CLI we have to consult environment variables directly. Optional<String> home = SystemSetting.getStringValueFromEnvironmentVariable("HOME"); if (home.isPresent()) { return home.get(); } boolean isWindows = JavaSystemSetting.OS_NAME.getStringValue() .map(s -> StringUtils.lowerCase(s).startsWith("windows")) .orElse(false); if (isWindows) { Optional<String> userProfile = SystemSetting.getStringValueFromEnvironmentVariable("USERPROFILE"); if (userProfile.isPresent()) { return userProfile.get(); } Optional<String> homeDrive = SystemSetting.getStringValueFromEnvironmentVariable("HOMEDRIVE"); Optional<String> homePath = SystemSetting.getStringValueFromEnvironmentVariable("HOMEPATH"); if (homeDrive.isPresent() && homePath.isPresent()) { return homeDrive.get() + homePath.get(); } } return JavaSystemSetting.USER_HOME.getStringValueOrThrow(); // CHECKSTYLE:ON } }
3,276
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ConditionalDecorator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.List; import java.util.function.Predicate; import java.util.function.UnaryOperator; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.internal.DefaultConditionalDecorator; /** * An interface that defines a class that contains a transform for another type as well as a condition for whether * that transform should be applied. * * @param <T> A type that can be decorated, or transformed, through applying a function. */ @FunctionalInterface @SdkProtectedApi public interface ConditionalDecorator<T> { default Predicate<T> predicate() { return t -> true; } UnaryOperator<T> transform(); static <T> ConditionalDecorator<T> create(Predicate<T> predicate, UnaryOperator<T> transform) { DefaultConditionalDecorator.Builder<T> builder = new DefaultConditionalDecorator.Builder<>(); return builder.predicate(predicate).transform(transform).build(); } /** * This function will transform an initially supplied value with provided transforming, or decorating, functions that are * conditionally and sequentially applied. For each pair of condition and transform: if the condition evaluates to true, the * transform will be applied to the incoming value and the output from the transform is the input to the next transform. * <p> * If the supplied collection is ordered, the function is guaranteed to apply the transforms in the order in which they appear * in the collection. * * @param initialValue The untransformed start value * @param decorators A list of condition to transform * @param <T> The type of the value * @return A single transformed value that is the result of applying all transforms evaluated to true */ static <T> T decorate(T initialValue, List<ConditionalDecorator<T>> decorators) { return decorators.stream() .filter(d -> d.predicate().test(initialValue)) .reduce(initialValue, (element, decorator) -> decorator.transform().apply(element), (el1, el2) -> { throw new IllegalStateException("Should not reach here, combine function not " + "needed unless executed in parallel."); }); } }
3,277
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/SystemSetting.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.Optional; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.internal.SystemSettingUtils; /** * An interface implemented by enums in other packages in order to define the system settings the want loaded. An enum * is expected to implement this interface, and then have values loaded from the {@link System} using methods like * {@link #getStringValue()}. */ @SdkProtectedApi public interface SystemSetting { /** * The system property of the setting (or null if there is no property for this setting). */ String property(); /** * The environment variable of the setting (or null if there is no environment variable for this setting). */ String environmentVariable(); /** * The default value of the setting (or empty if there is no default). This value will be applied if the customer did not * specify a setting. */ String defaultValue(); /** * Attempt to load a system setting from {@link System#getProperty(String)} and {@link System#getenv(String)}. This should be * used in favor of those methods because the SDK should support both methods of configuration. * * {@link System#getProperty(String)} takes precedent over {@link System#getenv(String)} if both are specified. * * @return The requested setting, or {@link Optional#empty()} if the values were not set, or the security manager did not * allow reading the setting. */ default Optional<String> getStringValue() { return SystemSettingUtils.resolveSetting(this); } /** * Attempt to load a system setting from {@link System#getenv(String)}. This should NOT BE USED, so checkstyle will * complain about using it. The only reason this is made available is for when we ABSOLUTELY CANNOT support a system * property for a specific setting. That should be the exception, NOT the rule. We should almost always provide a system * property alternative for all environment variables. * * @return The requested setting, or {@link Optional#empty()} if the values were not set, or the security manager did not * allow reading the setting. */ static Optional<String> getStringValueFromEnvironmentVariable(String key) { return SystemSettingUtils.resolveEnvironmentVariable(key); } /** * Attempt to load a system setting from {@link System#getProperty(String)} and {@link System#getenv(String)}. This should be * used in favor of those methods because the SDK should support both methods of configuration. * * {@link System#getProperty(String)} takes precedent over {@link System#getenv(String)} if both are specified. * <p> * Similar to {@link #getStringValue()}, but does not fall back to the default value. * * @return The requested setting, or {@link Optional#empty()} if the values were not set, or the security manager did not * allow reading the setting. */ default Optional<String> getNonDefaultStringValue() { return SystemSettingUtils.resolveNonDefaultSetting(this); } /** * Load the requested system setting as per the documentation in {@link #getStringValue()}, throwing an exception if the value * was not set and had no default. * * @return The requested setting. */ default String getStringValueOrThrow() { return getStringValue().orElseThrow(() -> new IllegalStateException("Either the environment variable " + environmentVariable() + " or the java" + "property " + property() + " must be set.")); } /** * Attempt to load a system setting from {@link System#getProperty(String)} and {@link System#getenv(String)}. This should be * used in favor of those methods because the SDK should support both methods of configuration. * * The result will be converted to an integer. * * {@link System#getProperty(String)} takes precedent over {@link System#getenv(String)} if both are specified. * * @return The requested setting, or {@link Optional#empty()} if the values were not set, or the security manager did not * allow reading the setting. */ default Optional<Integer> getIntegerValue() { return getStringValue().map(Integer::parseInt); } /** * Load the requested system setting as per the documentation in {@link #getIntegerValue()}, throwing an exception if the * value was not set and had no default. * * @return The requested setting. */ default Integer getIntegerValueOrThrow() { return Integer.parseInt(getStringValueOrThrow()); } /** * Attempt to load a system setting from {@link System#getProperty(String)} and {@link System#getenv(String)}. This should be * used in favor of those methods because the SDK should support both methods of configuration. * * The result will be converted to a boolean. * * {@link System#getProperty(String)} takes precedent over {@link System#getenv(String)} if both are specified. * * @return The requested setting, or {@link Optional#empty()} if the values were not set, or the security manager did not * allow reading the setting. */ default Optional<Boolean> getBooleanValue() { return getStringValue().map(value -> SystemSettingUtils.safeStringToBoolean(this, value)); } /** * Load the requested system setting as per the documentation in {@link #getBooleanValue()}, throwing an * exception if the value was not set and had no default. * * @return The requested setting. */ default Boolean getBooleanValueOrThrow() { return getBooleanValue().orElseThrow(() -> new IllegalStateException("Either the environment variable " + environmentVariable() + " or the java" + "property " + property() + " must be set.")); } }
3,278
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ThreadFactoryBuilder.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicLong; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; /** * A builder for creating a thread factory. This allows changing the behavior of the created thread factory. */ @SdkProtectedApi public class ThreadFactoryBuilder { /** * To prevent thread names from becoming too long we limit to 4 digits for the pool number before wrapping back * around. */ private static final int POOL_NUMBER_MAX = 10_000; private static final AtomicLong POOL_NUMBER = new AtomicLong(0); private String threadNamePrefix = "aws-java-sdk"; private Boolean daemonThreads = true; /** * The name prefix for threads created by this thread factory. The prefix will be appended with a number unique to the thread * factory and a number unique to the thread. * * For example, "aws-java-sdk-thread" could become "aws-java-sdk-thread-3-4". * * By default, this is "aws-java-sdk-thread". */ public ThreadFactoryBuilder threadNamePrefix(String threadNamePrefix) { this.threadNamePrefix = threadNamePrefix; return this; } /** * Whether the threads created by the factory should be daemon threads. By default this is true - we shouldn't be holding up * the customer's JVM shutdown unless we're absolutely sure we want to. */ public ThreadFactoryBuilder daemonThreads(Boolean daemonThreads) { this.daemonThreads = daemonThreads; return this; } /** * Test API to reset pool count for reliable assertions. */ @SdkTestInternalApi static void resetPoolNumber() { POOL_NUMBER.set(0); } /** * Create the {@link ThreadFactory} with the configuration currently applied to this builder. */ 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; } }
3,279
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/JavaSystemSetting.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * The system properties usually provided by the Java runtime. */ @SdkProtectedApi public enum JavaSystemSetting implements SystemSetting { JAVA_VERSION("java.version"), JAVA_VENDOR("java.vendor"), TEMP_DIRECTORY("java.io.tmpdir"), JAVA_VM_NAME("java.vm.name"), JAVA_VM_VERSION("java.vm.version"), OS_NAME("os.name"), OS_VERSION("os.version"), USER_HOME("user.home"), USER_LANGUAGE("user.language"), USER_REGION("user.region"), USER_NAME("user.name"), SSL_KEY_STORE("javax.net.ssl.keyStore"), SSL_KEY_STORE_PASSWORD("javax.net.ssl.keyStorePassword"), SSL_KEY_STORE_TYPE("javax.net.ssl.keyStoreType") ; private final String systemProperty; JavaSystemSetting(String systemProperty) { this.systemProperty = systemProperty; } @Override public String property() { return systemProperty; } @Override public String environmentVariable() { return null; } @Override public String defaultValue() { return null; } }
3,280
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/Platform.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import software.amazon.awssdk.annotations.SdkProtectedApi; @SdkProtectedApi public class Platform { private Platform() { } /** * Determine whether the current operation system seems to be Windows. */ public static boolean isWindows() { return JavaSystemSetting.OS_NAME.getStringValue() .map(s -> StringUtils.lowerCase(s).startsWith("windows")) .orElse(false); } }
3,281
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/Lazy.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkPublicApi; /** * A class that lazily constructs a value the first time {@link #getValue()} is invoked. * * This should be {@link #close()}d if the initializer returns value that needs to be {@link AutoCloseable#close()}d. */ @SdkPublicApi public class Lazy<T> implements SdkAutoCloseable { private final Supplier<T> initializer; private volatile T value; public Lazy(Supplier<T> initializer) { this.initializer = initializer; } public static <T> Lazy<T> withValue(T initialValue) { return new ResolvedLazy<>(initialValue); } public boolean hasValue() { return value != null; } public T getValue() { T result = value; if (result == null) { synchronized (this) { result = value; if (result == null) { result = initializer.get(); value = result; } } } return result; } @Override public String toString() { T value = this.value; return ToString.builder("Lazy") .add("value", value == null ? "Uninitialized" : value) .build(); } @Override public void close() { try { // Make sure the value has been initialized before we attempt to close it getValue(); } catch (RuntimeException e) { // Failed to initialize the value. } IoUtils.closeIfCloseable(initializer, null); IoUtils.closeIfCloseable(value, null); } private static class ResolvedLazy<T> extends Lazy<T> { private final T initialValue; private ResolvedLazy(T initialValue) { super(null); this.initialValue = initialValue; } @Override public boolean hasValue() { return true; } @Override public T getValue() { return initialValue; } @Override public String toString() { return ToString.builder("Lazy") .add("value", initialValue) .build(); } @Override public void close() { IoUtils.closeIfCloseable(initialValue, null); } } }
3,282
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ProxyConfigProvider.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.Optional; import java.util.Set; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.internal.proxy.ProxyEnvironmentVariableConfigProvider; import software.amazon.awssdk.utils.internal.proxy.ProxySystemPropertyConfigProvider; /** * Interface for providing proxy configuration settings. Implementations of this interface can retrieve proxy configuration * from various sources such as system properties and environment variables. **/ @SdkProtectedApi public interface ProxyConfigProvider { /** * Constant representing the HTTPS scheme. */ String HTTPS = "https"; /** * Returns a new {@code ProxyConfigProvider} that retrieves proxy configuration from system properties. * * @param scheme The URI scheme for which the proxy configuration is needed (e.g., "http" or "https"). * @return A {@code ProxyConfigProvider} for system property-based proxy configuration. */ static ProxyConfigProvider fromSystemPropertySettings(String scheme) { return new ProxySystemPropertyConfigProvider(scheme); } /** * Returns a new {@code ProxyConfigProvider} that retrieves proxy configuration from environment variables. * * @param scheme The URI scheme for which the proxy configuration is needed (e.g., "http" or "https"). * @return A {@code ProxyConfigProvider} for environment variable-based proxy configuration. */ static ProxyConfigProvider fromEnvironmentSettings(String scheme) { return new ProxyEnvironmentVariableConfigProvider(scheme); } /** * Returns a {@code ProxyConfigProvider} based on the specified settings for using system properties, environment * variables, and the scheme. * * @param useSystemPropertyValues A {@code Boolean} indicating whether to use system property values. * @param useEnvironmentVariableValues A {@code Boolean} indicating whether to use environment variable values. * @param scheme The URI scheme for which the proxy configuration is needed (e.g., "http" or "https"). * @return A {@code ProxyConfigProvider} based on the specified settings. */ static ProxyConfigProvider fromSystemEnvironmentSettings(Boolean useSystemPropertyValues, Boolean useEnvironmentVariableValues, String scheme) { ProxyConfigProvider resultProxyConfig = null; if (Boolean.TRUE.equals(useSystemPropertyValues)) { resultProxyConfig = fromSystemPropertySettings(scheme); } else if (Boolean.TRUE.equals(useEnvironmentVariableValues)) { return fromEnvironmentSettings(scheme); } boolean isProxyConfigurationNotSet = resultProxyConfig != null && resultProxyConfig.host() == null && resultProxyConfig.port() == 0 && !resultProxyConfig.password().isPresent() && !resultProxyConfig.userName().isPresent() && CollectionUtils.isNullOrEmpty(resultProxyConfig.nonProxyHosts()); if (isProxyConfigurationNotSet && Boolean.TRUE.equals(useEnvironmentVariableValues)) { return fromEnvironmentSettings(scheme); } return resultProxyConfig; } /** * Gets the proxy port. * * @return The proxy port. */ int port(); /** * Gets the proxy username if available. * * @return An optional containing the proxy username, if available. */ Optional<String> userName(); /** * Gets the proxy password if available. * * @return An optional containing the proxy password, if available. */ Optional<String> password(); /** * Gets the proxy host. * * @return The proxy host. */ String host(); /** * Gets the set of non-proxy hosts. * * @return A set containing the non-proxy host names. */ Set<String> nonProxyHosts(); }
3,283
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ProxySystemSetting.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * The system properties related to http and https proxies */ @SdkProtectedApi public enum ProxySystemSetting implements SystemSetting { PROXY_HOST("http.proxyHost"), PROXY_PORT("http.proxyPort"), NON_PROXY_HOSTS("http.nonProxyHosts"), PROXY_USERNAME("http.proxyUser"), PROXY_PASSWORD("http.proxyPassword"), HTTPS_PROXY_HOST("https.proxyHost"), HTTPS_PROXY_PORT("https.proxyPort"), HTTPS_PROXY_USERNAME("https.proxyUser"), HTTPS_PROXY_PASSWORD("https.proxyPassword") ; private final String systemProperty; ProxySystemSetting(String systemProperty) { this.systemProperty = systemProperty; } @Override public String property() { return systemProperty; } @Override public String environmentVariable() { return null; } @Override public String defaultValue() { return null; } }
3,284
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/SdkAutoCloseable.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import software.amazon.awssdk.annotations.SdkPublicApi; /** * An implementation of {@link AutoCloseable} that does not throw any checked exceptions. The SDK does not throw checked * exceptions in its close() methods, so users of the SDK should not need to handle them. */ @SdkPublicApi // CHECKSTYLE:OFF - This is the only place we're allowed to use AutoCloseable public interface SdkAutoCloseable extends AutoCloseable { // CHECKSTYLE:ON /** * {@inheritDoc} */ @Override void close(); }
3,285
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/Validate.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.time.Duration; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.function.Predicate; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * <p>This class assists in validating arguments. The validation methods are * based along the following principles: * <ul> * <li>An invalid {@code null} argument causes a {@link NullPointerException}.</li> * <li>A non-{@code null} argument causes an {@link IllegalArgumentException}.</li> * <li>An invalid index into an array/collection/map/string causes an {@link IndexOutOfBoundsException}.</li> * </ul> * * <p>All exceptions messages are * <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax">format strings</a> * as defined by the Java platform. For example:</p> * * <pre> * Validate.isTrue(i &gt; 0, "The value must be greater than zero: %d", i); * Validate.notNull(surname, "The surname must not be %s", null); * </pre> * * <p>This class's source was modified from the Apache commons-lang library: https://github.com/apache/commons-lang/</p> * * <p>#ThreadSafe#</p> * @see java.lang.String#format(String, Object...) */ @SdkProtectedApi public final class Validate { private static final String DEFAULT_IS_NULL_EX_MESSAGE = "The validated object is null"; private Validate() { } // isTrue //--------------------------------------------------------------------------------- /** * <p>Validate that the argument condition is {@code true}; otherwise * throwing an exception with the specified message. This method is useful when * validating according to an arbitrary boolean expression, such as validating a * primitive number or using your own custom validation expression.</p> * * <pre> * Validate.isTrue(i &gt;= min &amp;&amp; i &lt;= max, "The value must be between &#37;d and &#37;d", min, max); * Validate.isTrue(myObject.isOk(), "The object is not okay");</pre> * * @param expression the boolean expression to check * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @throws IllegalArgumentException if expression is {@code false} */ public static void isTrue(final boolean expression, final String message, final Object... values) { if (!expression) { throw new IllegalArgumentException(String.format(message, values)); } } // isFalse //--------------------------------------------------------------------------------- /** * <p>Validate that the argument condition is {@code false}; otherwise * throwing an exception with the specified message. This method is useful when * validating according to an arbitrary boolean expression, such as validating a * primitive number or using your own custom validation expression.</p> * * <pre> * Validate.isFalse(myObject.permitsSomething(), "The object is not allowed to permit something");</pre> * * @param expression the boolean expression to check * @param message the {@link String#format(String, Object...)} exception message if not false, not null * @param values the optional values for the formatted exception message, null array not recommended * @throws IllegalArgumentException if expression is {@code true} */ public static void isFalse(final boolean expression, final String message, final Object... values) { isTrue(!expression, message, values); } // notNull //--------------------------------------------------------------------------------- /** * <p>Validate that the specified argument is not {@code null}; * otherwise throwing an exception with the specified message. * * <pre>Validate.notNull(myObject, "The object must not be null");</pre> * * @param <T> the object type * @param object the object to check * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message * @return the validated object (never {@code null} for method chaining) * @throws NullPointerException if the object is {@code null} */ 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; } /** * <p>Validate that the specified argument is {@code null}; * otherwise throwing an exception with the specified message. * * <pre>Validate.isNull(myObject, "The object must be null");</pre> * * @param <T> the object type * @param object the object to check * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message * @throws IllegalArgumentException if the object is not {@code null} */ public static <T> void isNull(final T object, final String message, final Object... values) { if (object != null) { throw new IllegalArgumentException(String.format(message, values)); } } /** * <p>Validate that the specified field/param is not {@code null}; * otherwise throwing an exception with a precanned message that includes the parameter name. * * <pre>Validate.paramNotNull(myObject, "myObject");</pre> * * @param <T> the object type * @param object the object to check * @param paramName The name of the param or field being checked. * @return the validated object (never {@code null} for method chaining) * @throws NullPointerException if the object is {@code null} */ 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; } /** * <p>Validate that the specified char sequence is neither * {@code null}, a length of zero (no characters), empty nor * whitespace; otherwise throwing an exception with the specified * message. * * <pre>Validate.paramNotBlank(myCharSequence, "myCharSequence");</pre> * * @param <T> the char sequence type * @param chars the character sequence to check * @param paramName The name of the param or field being checked. * @return the validated char sequence (never {@code null} for method chaining) * @throws NullPointerException if the char sequence is {@code null} */ public static <T extends CharSequence> T paramNotBlank(final T chars, final String paramName) { if (chars == null) { throw new NullPointerException(String.format("%s must not be null.", paramName)); } if (StringUtils.isBlank(chars)) { throw new IllegalArgumentException(String.format("%s must not be blank or empty.", paramName)); } return chars; } /** * <p>Validate the stateful predicate is true for the given object and return the object; * otherwise throw an exception with the specified message.</p> * * {@code String value = Validate.validState(someString, s -> s.length() == 0, "must be blank got: %s", someString);} * * * @param <T> the object type * @param object the object to check * @param test the predicate to apply, will return true if the object is valid * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message * @return the validated object * @throws NullPointerException if the object is {@code null} */ public static <T> T validState(final T object, final Predicate<T> test, final String message, final Object... values) { if (!test.test(object)) { throw new IllegalStateException(String.format(message, values)); } return object; } // notEmpty array //--------------------------------------------------------------------------------- /** * <p>Validate that the specified argument array is neither {@code null} * nor a length of zero (no elements); otherwise throwing an exception * with the specified message. * * <pre>Validate.notEmpty(myArray, "The array must not be empty");</pre> * * @param <T> the array type * @param array the array to check, validated not null by this method * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @return the validated array (never {@code null} method for chaining) * @throws NullPointerException if the array is {@code null} * @throws IllegalArgumentException if the array is empty */ 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; } // notEmpty collection //--------------------------------------------------------------------------------- /** * <p>Validate that the specified argument collection is neither {@code null} * nor a size of zero (no elements); otherwise throwing an exception * with the specified message. * * <pre>Validate.notEmpty(myCollection, "The collection must not be empty");</pre> * * @param <T> the collection type * @param collection the collection to check, validated not null by this method * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @return the validated collection (never {@code null} method for chaining) * @throws NullPointerException if the collection is {@code null} * @throws IllegalArgumentException if the collection is empty */ public static <T extends Collection<?>> T notEmpty(final T collection, final String message, final Object... values) { if (collection == null) { throw new NullPointerException(String.format(message, values)); } if (collection.isEmpty()) { throw new IllegalArgumentException(String.format(message, values)); } return collection; } // notEmpty map //--------------------------------------------------------------------------------- /** * <p>Validate that the specified argument map is neither {@code null} * nor a size of zero (no elements); otherwise throwing an exception * with the specified message. * * <pre>Validate.notEmpty(myMap, "The map must not be empty");</pre> * * @param <T> the map type * @param map the map to check, validated not null by this method * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @return the validated map (never {@code null} method for chaining) * @throws NullPointerException if the map is {@code null} * @throws IllegalArgumentException if the map is empty */ public static <T extends Map<?, ?>> T notEmpty(final T map, final String message, final Object... values) { if (map == null) { throw new NullPointerException(String.format(message, values)); } if (map.isEmpty()) { throw new IllegalArgumentException(String.format(message, values)); } return map; } // notEmpty string //--------------------------------------------------------------------------------- /** * <p>Validate that the specified argument character sequence is * neither {@code null} nor a length of zero (no characters); * otherwise throwing an exception with the specified message. * * <pre>Validate.notEmpty(myString, "The string must not be empty");</pre> * * @param <T> the character sequence type * @param chars the character sequence to check, validated not null by this method * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @return the validated character sequence (never {@code null} method for chaining) * @throws NullPointerException if the character sequence is {@code null} * @throws IllegalArgumentException if the character sequence is empty */ public static <T extends CharSequence> T notEmpty(final T chars, final String message, final Object... values) { if (chars == null) { throw new NullPointerException(String.format(message, values)); } if (chars.length() == 0) { throw new IllegalArgumentException(String.format(message, values)); } return chars; } // notBlank string //--------------------------------------------------------------------------------- /** * <p>Validate that the specified argument character sequence is * neither {@code null}, a length of zero (no characters), empty * nor whitespace; otherwise throwing an exception with the specified * message. * * <pre>Validate.notBlank(myString, "The string must not be blank");</pre> * * @param <T> the character sequence type * @param chars the character sequence to check, validated not null by this method * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @return the validated character sequence (never {@code null} method for chaining) * @throws NullPointerException if the character sequence is {@code null} * @throws IllegalArgumentException if the character sequence is blank */ 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; } // noNullElements array //--------------------------------------------------------------------------------- /** * <p>Validate that the specified argument array is neither * {@code null} nor contains any elements that are {@code null}; * otherwise throwing an exception with the specified message. * * <pre>Validate.noNullElements(myArray, "The array is null or contains null.");</pre> * * @param <T> the array type * @param array the array to check, validated not null by this method * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message * @return the validated array (never {@code null} method for chaining) * @throws NullPointerException if the array is {@code null} * @throws IllegalArgumentException if an element is {@code null} */ 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; } // noNullElements iterable //--------------------------------------------------------------------------------- /** * <p>Validate that the specified argument iterable is neither * {@code null} nor contains any elements that are {@code null}; * otherwise throwing an exception with the specified message. * * <pre>Validate.noNullElements(myCollection, "The collection is null or contains null.");</pre> * * @param <T> the iterable type * @param iterable the iterable to check, validated not null by this method * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message. * @return the validated iterable (never {@code null} method for chaining) * @throws NullPointerException if the array is {@code null} * @throws IllegalArgumentException if an element is {@code null} */ public static <T extends Iterable<?>> T noNullElements(final T iterable, final String message, final Object... values) { Validate.notNull(iterable, DEFAULT_IS_NULL_EX_MESSAGE); int i = 0; for (Iterator<?> it = iterable.iterator(); it.hasNext(); i++) { if (it.next() == null) { throw new IllegalArgumentException(String.format(message, values)); } } return iterable; } // validState //--------------------------------------------------------------------------------- /** * <p>Validate that the stateful condition is {@code true}; otherwise * throwing an exception with the specified message. This method is useful when * validating according to an arbitrary boolean expression, such as validating a * primitive number or using your own custom validation expression.</p> * * <pre>Validate.validState(this.isOk(), "The state is not OK: %s", myObject);</pre> * * @param expression the boolean expression to check * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @throws IllegalStateException if expression is {@code false} */ public static void validState(final boolean expression, final String message, final Object... values) { if (!expression) { throw new IllegalStateException(String.format(message, values)); } } // inclusiveBetween //--------------------------------------------------------------------------------- /** * <p>Validate that the specified argument object fall between the two * inclusive values specified; otherwise, throws an exception with the * specified message.</p> * * <pre>Validate.inclusiveBetween(0, 2, 1, "Not in boundaries");</pre> * * @param <T> the type of the argument object * @param start the inclusive start value, not null * @param end the inclusive end value, not null * @param value the object to validate, not null * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @throws IllegalArgumentException if the value falls outside the boundaries */ 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; } /** * Validate that the specified primitive value falls between the two * inclusive values specified; otherwise, throws an exception with the * specified message. * * <pre>Validate.inclusiveBetween(0, 2, 1, "Not in range");</pre> * * @param start the inclusive start value * @param end the inclusive end value * @param value the value to validate * @param message the exception message if invalid, not null * * @throws IllegalArgumentException if the value falls outside the boundaries */ public static long inclusiveBetween(final long start, final long end, final long value, final String message) { if (value < start || value > end) { throw new IllegalArgumentException(message); } return value; } /** * Validate that the specified primitive value falls between the two * inclusive values specified; otherwise, throws an exception with the * specified message. * * <pre>Validate.inclusiveBetween(0.1, 2.1, 1.1, "Not in range");</pre> * * @param start the inclusive start value * @param end the inclusive end value * @param value the value to validate * @param message the exception message if invalid, not null * * @throws IllegalArgumentException if the value falls outside the boundaries */ public static double inclusiveBetween(final double start, final double end, final double value, final String message) { if (value < start || value > end) { throw new IllegalArgumentException(message); } return value; } // exclusiveBetween //--------------------------------------------------------------------------------- /** * <p>Validate that the specified argument object fall between the two * exclusive values specified; otherwise, throws an exception with the * specified message.</p> * * <pre>Validate.exclusiveBetween(0, 2, 1, "Not in boundaries");</pre> * * @param <T> the type of the argument object * @param start the exclusive start value, not null * @param end the exclusive end value, not null * @param value the object to validate, not null * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @throws IllegalArgumentException if the value falls outside the boundaries */ 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; } /** * Validate that the specified primitive value falls between the two * exclusive values specified; otherwise, throws an exception with the * specified message. * * <pre>Validate.exclusiveBetween(0, 2, 1, "Not in range");</pre> * * @param start the exclusive start value * @param end the exclusive end value * @param value the value to validate * @param message the exception message if invalid, not null * * @throws IllegalArgumentException if the value falls outside the boundaries */ public static long exclusiveBetween(final long start, final long end, final long value, final String message) { if (value <= start || value >= end) { throw new IllegalArgumentException(message); } return value; } /** * Validate that the specified primitive value falls between the two * exclusive values specified; otherwise, throws an exception with the * specified message. * * <pre>Validate.exclusiveBetween(0.1, 2.1, 1.1, "Not in range");</pre> * * @param start the exclusive start value * @param end the exclusive end value * @param value the value to validate * @param message the exception message if invalid, not null * * @throws IllegalArgumentException if the value falls outside the boundaries */ public static double exclusiveBetween(final double start, final double end, final double value, final String message) { if (value <= start || value >= end) { throw new IllegalArgumentException(message); } return value; } // isInstanceOf //--------------------------------------------------------------------------------- /** * <p>Validate that the argument is an instance of the specified class; otherwise * throwing an exception with the specified message. This method is useful when * validating according to an arbitrary class</p> * * <pre>Validate.isInstanceOf(OkClass.class, object, "Wrong class, object is of class %s", * object.getClass().getName());</pre> * * @param type the class the object must be validated against, not null * @param obj the object to check, null throws an exception * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @throws IllegalArgumentException if argument is not of specified class */ 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); } // isAssignableFrom //--------------------------------------------------------------------------------- /** * Validates that the argument can be converted to the specified class, if not throws an exception. * * <p>This method is useful when validating if there will be no casting errors.</p> * * <pre>Validate.isAssignableFrom(SuperClass.class, object.getClass());</pre> * * <p>The message of the exception is &quot;The validated object can not be converted to the&quot; * followed by the name of the class and &quot;class&quot;</p> * * @param superType the class the class must be validated against, not null * @param type the class to check, not null * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @throws IllegalArgumentException if argument can not be converted to the specified class */ 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; } /** * Asserts that the given number is positive (non-negative and non-zero). * * @param num Number to validate * @param fieldName Field name to display in exception message if not positive. * @return Number if positive. */ public static int isPositive(int num, String fieldName) { if (num <= 0) { throw new IllegalArgumentException(String.format("%s must be positive", fieldName)); } return num; } /** * Asserts that the given number is positive (non-negative and non-zero). * * @param num Number to validate * @param fieldName Field name to display in exception message if not positive. * @return Number if positive. */ public static long isPositive(long num, String fieldName) { if (num <= 0) { throw new IllegalArgumentException(String.format("%s must be positive", fieldName)); } return num; } public static double isPositive(double num, String fieldName) { if (num <= 0) { throw new IllegalArgumentException(String.format("%s must be positive", fieldName)); } return num; } public static int isNotNegative(int num, String fieldName) { if (num < 0) { throw new IllegalArgumentException(String.format("%s must not be negative", fieldName)); } return num; } public static Long isNotNegativeOrNull(Long num, String fieldName) { if (num == null) { return null; } if (num < 0) { throw new IllegalArgumentException(String.format("%s must not be negative", fieldName)); } return num; } public static long isNotNegative(long num, String fieldName) { if (num < 0) { throw new IllegalArgumentException(String.format("%s must not be negative", fieldName)); } return num; } /** * Asserts that the given duration is positive (non-negative and non-zero). * * @param duration Number to validate * @param fieldName Field name to display in exception message if not positive. * @return Duration if positive. */ public static Duration isPositive(Duration duration, String fieldName) { if (duration == null) { throw new IllegalArgumentException(String.format("%s cannot be null", fieldName)); } if (duration.isNegative() || duration.isZero()) { throw new IllegalArgumentException(String.format("%s must be positive", fieldName)); } return duration; } /** * Asserts that the given duration is positive (non-negative and non-zero) or null. * * @param duration Number to validate * @param fieldName Field name to display in exception message if not positive. * @return Duration if positive or null. */ public static Duration isPositiveOrNull(Duration duration, String fieldName) { if (duration == null) { return null; } return isPositive(duration, fieldName); } /** * Asserts that the given boxed integer is positive (non-negative and non-zero) or null. * * @param num Boxed integer to validate * @param fieldName Field name to display in exception message if not positive. * @return Duration if positive or null. */ public static Integer isPositiveOrNull(Integer num, String fieldName) { if (num == null) { return null; } return isPositive(num, fieldName); } /** * Asserts that the given boxed double is positive (non-negative and non-zero) or null. * * @param num Boxed double to validate * @param fieldName Field name to display in exception message if not positive. * @return Duration if double or null. */ public static Double isPositiveOrNull(Double num, String fieldName) { if (num == null) { return null; } return isPositive(num, fieldName); } /** * Asserts that the given boxed long is positive (non-negative and non-zero) or null. * * @param num Boxed long to validate * @param fieldName Field name to display in exception message if not positive. * @return Duration if positive or null. */ public static Long isPositiveOrNull(Long num, String fieldName) { if (num == null) { return null; } return isPositive(num, fieldName); } /** * Asserts that the given duration is positive (non-negative and non-zero). * * @param duration Number to validate * @param fieldName Field name to display in exception message if not positive. * @return Duration if positive. */ public static Duration isNotNegative(Duration duration, String fieldName) { if (duration == null) { throw new IllegalArgumentException(String.format("%s cannot be null", fieldName)); } if (duration.isNegative()) { throw new IllegalArgumentException(String.format("%s must not be negative", fieldName)); } return duration; } /** * Returns the param if non null, otherwise gets a default value from the provided {@link Supplier}. * * @param param Param to return if non null. * @param defaultValue Supplier of default value. * @param <T> Type of value. * @return Value of param or default value if param was null. */ public static <T> T getOrDefault(T param, Supplier<T> defaultValue) { paramNotNull(defaultValue, "defaultValue"); return param != null ? param : defaultValue.get(); } /** * Verify that only one of the objects is non null. If all objects are null this method * does not throw. * * @param message Error message if more than one object is non-null. * @param objs Objects to validate. * @throws IllegalArgumentException if more than one of the objects was non-null. */ 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; } } } } }
3,286
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/HostnameValidator.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.regex.Matcher; import java.util.regex.Pattern; import software.amazon.awssdk.annotations.SdkProtectedApi; @SdkProtectedApi public final class HostnameValidator { private static final Pattern DEFAULT_HOSTNAME_COMPLIANT_PATTERN = Pattern.compile("[A-Za-z0-9\\-]+"); private static final int HOSTNAME_MAX_LENGTH = 63; private HostnameValidator() { } public static void validateHostnameCompliant(String hostnameComponent, String paramName, String object) { validateHostnameCompliant(hostnameComponent, paramName, object, DEFAULT_HOSTNAME_COMPLIANT_PATTERN); } public static void validateHostnameCompliant(String hostnameComponent, String paramName, String object, Pattern pattern) { if (hostnameComponent == null) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the required '%s' " + "component is missing.", object, paramName)); } if (StringUtils.isEmpty(hostnameComponent)) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component is empty.", object, paramName)); } if (StringUtils.isBlank(hostnameComponent)) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component is blank.", 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 = pattern.matcher(hostnameComponent); if (!m.matches()) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component must match the pattern \"%s\".", object, paramName, pattern)); } } }
3,287
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ProxyEnvironmentSetting.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static software.amazon.awssdk.utils.internal.SystemSettingUtils.resolveEnvironmentVariable; import java.util.Locale; import java.util.Optional; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * An enumeration representing environment settings related to proxy configuration. Instances of this enum are used to * define and access proxy configuration settings obtained from environment variables. */ @SdkProtectedApi public enum ProxyEnvironmentSetting implements SystemSetting { HTTP_PROXY("http_proxy"), HTTPS_PROXY("https_proxy"), NO_PROXY("no_proxy") ; private final String environmentVariable; ProxyEnvironmentSetting(String environmentVariable) { this.environmentVariable = environmentVariable; } @Override public Optional<String> getStringValue() { Optional<String> envVarLowercase = resolveEnvironmentVariable(environmentVariable); if (envVarLowercase.isPresent()) { return getValueIfValid(envVarLowercase.get()); } Optional<String> envVarUppercase = resolveEnvironmentVariable(environmentVariable.toUpperCase(Locale.getDefault())); if (envVarUppercase.isPresent()) { return getValueIfValid(envVarUppercase.get()); } return Optional.empty(); } @Override public String property() { return null; } @Override public String environmentVariable() { return environmentVariable; } @Override public String defaultValue() { return null; } private Optional<String> getValueIfValid(String value) { String trimmedValue = value.trim(); if (!trimmedValue.isEmpty()) { return Optional.of(trimmedValue); } return Optional.empty(); } }
3,288
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/DateUtils.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import static java.time.ZoneOffset.UTC; import static java.time.format.DateTimeFormatter.ISO_INSTANT; import static java.time.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME; import static java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME; import java.math.BigDecimal; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.chrono.IsoChronology; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.DateTimeParseException; import java.time.format.ResolverStyle; import java.util.Arrays; import java.util.List; import java.util.Locale; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.ThreadSafe; /** * Utilities for parsing and formatting dates. */ @ThreadSafe @SdkProtectedApi public final class DateUtils { /** * Alternate ISO 8601 format without fractional seconds. */ static final DateTimeFormatter ALTERNATE_ISO_8601_DATE_FORMAT = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd'T'HH:mm:ss'Z'") .toFormatter() .withZone(UTC); /** * RFC 822 date/time formatter. */ static final DateTimeFormatter RFC_822_DATE_TIME = new DateTimeFormatterBuilder() .parseCaseInsensitive() .parseLenient() .appendPattern("EEE, dd MMM yyyy HH:mm:ss") .appendLiteral(' ') .appendOffset("+HHMM", "GMT") .toFormatter() .withLocale(Locale.US) .withResolverStyle(ResolverStyle.SMART) .withChronology(IsoChronology.INSTANCE); // ISO_INSTANT does not handle offsets in Java 12-. See https://bugs.openjdk.java.net/browse/JDK-8166138 private static final List<DateTimeFormatter> ALTERNATE_ISO_8601_FORMATTERS = Arrays.asList(ISO_INSTANT, ALTERNATE_ISO_8601_DATE_FORMAT, ISO_OFFSET_DATE_TIME); private static final int MILLI_SECOND_PRECISION = 3; private DateUtils() { } /** * Parses the specified date string as an ISO 8601 date (yyyy-MM-dd'T'HH:mm:ss.SSSZZ) * and returns the {@link Instant} object. * * @param dateString * The date string to parse. * * @return The parsed Instant object. */ public static Instant parseIso8601Date(String dateString) { // For EC2 Spot Fleet. if (dateString.endsWith("+0000")) { dateString = dateString .substring(0, dateString.length() - 5) .concat("Z"); } DateTimeParseException exception = null; for (DateTimeFormatter formatter : ALTERNATE_ISO_8601_FORMATTERS) { try { return parseInstant(dateString, formatter); } catch (DateTimeParseException e) { exception = e; } } if (exception != null) { throw exception; } // should never execute this throw new RuntimeException("Failed to parse date " + dateString); } /** * Formats the specified date as an ISO 8601 string. * * @param date the date to format * @return the ISO-8601 string representing the specified date */ public static String formatIso8601Date(Instant date) { return ISO_INSTANT.format(date); } /** * Parses the specified date string as an RFC 822 date and returns the Date object. * * @param dateString * The date string to parse. * * @return The parsed Date object. */ public static Instant parseRfc822Date(String dateString) { if (dateString == null) { return null; } return parseInstant(dateString, RFC_822_DATE_TIME); } /** * Formats the specified date as an RFC 822 string. * * @param instant * The instant to format. * * @return The RFC 822 string representing the specified date. */ public static String formatRfc822Date(Instant instant) { return RFC_822_DATE_TIME.format(ZonedDateTime.ofInstant(instant, UTC)); } /** * Parses the specified date string as an RFC 1123 date and returns the Date * object. * * @param dateString * The date string to parse. * * @return The parsed Date object. */ public static Instant parseRfc1123Date(String dateString) { if (dateString == null) { return null; } return parseInstant(dateString, RFC_1123_DATE_TIME); } /** * Formats the specified date as an RFC 1123 string. * * @param instant * The instant to format. * * @return The RFC 1123 string representing the specified date. */ public static String formatRfc1123Date(Instant instant) { return RFC_1123_DATE_TIME.format(ZonedDateTime.ofInstant(instant, UTC)); } /** * Returns the number of days since epoch with respect to the given number * of milliseconds since epoch. */ public static long numberOfDaysSinceEpoch(long milliSinceEpoch) { return Duration.ofMillis(milliSinceEpoch).toDays(); } private static Instant parseInstant(String dateString, DateTimeFormatter formatter) { // Should not call formatter.withZone(ZoneOffset.UTC) because it will override the zone // for timestamps with an offset. See https://bugs.openjdk.java.net/browse/JDK-8177021 if (formatter.equals(ISO_OFFSET_DATE_TIME)) { return formatter.parse(dateString, Instant::from); } return formatter.withZone(ZoneOffset.UTC).parse(dateString, Instant::from); } /** * Parses the given string containing a Unix timestamp with millisecond decimal precision into an {@link Instant} object. */ public static Instant parseUnixTimestampInstant(String dateString) throws NumberFormatException { if (dateString == null) { return null; } validateTimestampLength(dateString); BigDecimal dateValue = new BigDecimal(dateString); return Instant.ofEpochMilli(dateValue.scaleByPowerOfTen(MILLI_SECOND_PRECISION).longValue()); } /** * Parses the given string containing a Unix timestamp in epoch millis into a {@link Instant} object. */ public static Instant parseUnixTimestampMillisInstant(String dateString) throws NumberFormatException { if (dateString == null) { return null; } return Instant.ofEpochMilli(Long.parseLong(dateString)); } /** * Formats the give {@link Instant} object into an Unix timestamp with millisecond decimal precision. */ public static String formatUnixTimestampInstant(Instant instant) { if (instant == null) { return null; } BigDecimal dateValue = BigDecimal.valueOf(instant.toEpochMilli()); return dateValue.scaleByPowerOfTen(0 - MILLI_SECOND_PRECISION) .toPlainString(); } private static void validateTimestampLength(String timestamp) { // Helps avoid BigDecimal parsing unnecessarily large numbers, since it's unbounded // Long has a max value of 9,223,372,036,854,775,807, which is 19 digits. Assume that a valid timestamp is no // no longer than 20 characters long (+1 for decimal) if (timestamp.length() > 20) { throw new RuntimeException("Input timestamp string must be no longer than 20 characters"); } } }
3,289
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ToString.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.Arrays; import software.amazon.awssdk.annotations.NotThreadSafe; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * A class to standardize implementations of {@link Object#toString()} across the SDK. * * <pre>{@code * ToString.builder("Person") * .add("name", name) * .add("age", age) * .build(); * }</pre> */ @NotThreadSafe @SdkProtectedApi public final class ToString { private final StringBuilder result; private final int startingLength; /** * @see #builder(String) */ private ToString(String className) { this.result = new StringBuilder(className).append("("); this.startingLength = result.length(); } /** * Create a to-string result for the given class name. */ public static String create(String className) { return className + "()"; } /** * Create a to-string result builder for the given class name. * @param className The name of the class being toString'd */ public static ToString builder(String className) { return new ToString(className); } /** * Add a field to the to-string result. * @param fieldName The name of the field. Must not be null. * @param field The value of the field. Value is ignored if null. */ public ToString add(String fieldName, Object field) { if (field != null) { String value; if (field.getClass().isArray()) { if (field instanceof byte[]) { value = "0x" + BinaryUtils.toHex((byte[]) field); } else { value = Arrays.toString((Object[]) field); } } else { value = String.valueOf(field); } result.append(fieldName).append("=").append(value).append(", "); } return this; } /** * Convert this result to a string. The behavior of calling other methods after this one is undefined. */ public String build() { if (result.length() > startingLength) { result.setLength(result.length() - 2); } return result.append(")").toString(); } }
3,290
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/CancellableOutputStream.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.io.OutputStream; import software.amazon.awssdk.annotations.SdkPublicApi; /** * An implementation of {@link OutputStream} to which writing can be {@link #cancel()}ed. * <p> * Cancelling tells the downstream receiver of the output that the stream will not be written to anymore, and that the * data sent was incomplete. The stream must still be {@link #close()}d by the caller. */ @SdkPublicApi public abstract class CancellableOutputStream extends OutputStream { /** * Cancel writing to the stream. This is different than {@link #close()} in that it indicates the data written so * far is truncated and incomplete. Callers must still invoke {@link #close()} even if the stream is * cancelled. */ public abstract void cancel(); }
3,291
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/ImmutableMap.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * An immutable map that could be built by convenient constructors. * <p> * Example of using map Builder: * * <pre> * { * &#064;code * Map&lt;String, AttibuteValue&gt; item = new ImmutableMap.Builder&lt;String, AttibuteValue&gt;() * .put(&quot;one&quot;, new AttibuteValue(&quot;1&quot;)) * .put(&quot;two&quot;, new AttibuteValue(&quot;2&quot;)) * .put(&quot;three&quot;, new AttibuteValue(&quot;3&quot;)).build(); * } * </pre> * * For <i>small</i> immutable maps (up to five entries), the * {@code ImmutableMapParamter.of()} methods are preferred: * * <pre> * {@code * Map<String, AttibuteValue> item = * ImmutableMap * .of("one", new AttributeValue("1"), * "two", new AttributeValue("2"), * "three", new AttributeValue("3"), * } * </pre> * * @param <K> * Class of the key for the map. * @param <V> * Class of the value for the map. */ @SdkProtectedApi public final class ImmutableMap<K, V> implements Map<K, V> { private static final String UNMODIFIABLE_MESSAGE = "This is an immutable map."; private static final String DUPLICATED_KEY_MESSAGE = "Duplicate keys are provided."; private final Map<K, V> map; private ImmutableMap(Map<K, V> map) { this.map = map; } /** * Returns a new MapParameterBuilder instance. */ public static <K, V> Builder<K, V> builder() { return new Builder<>(); } /** * Returns an ImmutableMap instance containing a single entry. * * @param k0 * Key of the single entry. * @param v0 * Value of the single entry. */ public static <K, V> ImmutableMap<K, V> of(K k0, V v0) { Map<K, V> map = Collections.singletonMap(k0, v0); return new ImmutableMap<>(map); } /** * Returns an ImmutableMap instance containing two entries. * * @param k0 * Key of the first entry. * @param v0 * Value of the first entry. * @param k1 * Key of the second entry. * @param v1 * Value of the second entry. */ public static <K, V> ImmutableMap<K, V> of(K k0, V v0, K k1, V v1) { Map<K, V> map = new HashMap<>(); putAndWarnDuplicateKeys(map, k0, v0); putAndWarnDuplicateKeys(map, k1, v1); return new ImmutableMap<>(map); } /** * Returns an ImmutableMap instance containing three entries. * * @param k0 * Key of the first entry. * @param v0 * Value of the first entry. * @param k1 * Key of the second entry. * @param v1 * Value of the second entry. * @param k2 * Key of the third entry. * @param v2 * Value of the third entry. */ public static <K, V> ImmutableMap<K, V> of(K k0, V v0, K k1, V v1, K k2, V v2) { Map<K, V> map = new HashMap<>(); putAndWarnDuplicateKeys(map, k0, v0); putAndWarnDuplicateKeys(map, k1, v1); putAndWarnDuplicateKeys(map, k2, v2); return new ImmutableMap<>(map); } /** * Returns an ImmutableMap instance containing four entries. * * @param k0 * Key of the first entry. * @param v0 * Value of the first entry. * @param k1 * Key of the second entry. * @param v1 * Value of the second entry. * @param k2 * Key of the third entry. * @param v2 * Value of the third entry. * @param k3 * Key of the fourth entry. * @param v3 * Value of the fourth entry. */ public static <K, V> ImmutableMap<K, V> of(K k0, V v0, K k1, V v1, K k2, V v2, K k3, V v3) { Map<K, V> map = new HashMap<>(); putAndWarnDuplicateKeys(map, k0, v0); putAndWarnDuplicateKeys(map, k1, v1); putAndWarnDuplicateKeys(map, k2, v2); putAndWarnDuplicateKeys(map, k3, v3); return new ImmutableMap<>(map); } /** * Returns an ImmutableMap instance containing five entries. * * @param k0 * Key of the first entry. * @param v0 * Value of the first entry. * @param k1 * Key of the second entry. * @param v1 * Value of the second entry. * @param k2 * Key of the third entry. * @param v2 * Value of the third entry. * @param k3 * Key of the fourth entry. * @param v3 * Value of the fourth entry. * @param k4 * Key of the fifth entry. * @param v4 * Value of the fifth entry. */ public static <K, V> ImmutableMap<K, V> of(K k0, V v0, K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { Map<K, V> map = new HashMap<>(); putAndWarnDuplicateKeys(map, k0, v0); putAndWarnDuplicateKeys(map, k1, v1); putAndWarnDuplicateKeys(map, k2, v2); putAndWarnDuplicateKeys(map, k3, v3); putAndWarnDuplicateKeys(map, k4, v4); return new ImmutableMap<>(map); } private static <K, V> void putAndWarnDuplicateKeys(Map<K, V> map, K key, V value) { if (map.containsKey(key)) { throw new IllegalArgumentException(DUPLICATED_KEY_MESSAGE); } map.put(key, value); } /** Inherited methods **/ @Override public boolean containsKey(Object key) { return map.containsKey(key); } @Override public boolean containsValue(Object value) { return map.containsValue(value); } @Override public Set<Entry<K, V>> entrySet() { return map.entrySet(); } @Override public V get(Object key) { return map.get(key); } @Override public boolean isEmpty() { return map.isEmpty(); } @Override public Set<K> keySet() { return map.keySet(); } @Override public int size() { return map.size(); } @Override public Collection<V> values() { return map.values(); } /** Unsupported methods **/ @Override public void clear() { throw new UnsupportedOperationException(UNMODIFIABLE_MESSAGE); } @Override public V put(K key, V value) { throw new UnsupportedOperationException(UNMODIFIABLE_MESSAGE); } @Override public void putAll(Map<? extends K, ? extends V> map) { throw new UnsupportedOperationException(UNMODIFIABLE_MESSAGE); } @Override public V remove(Object key) { throw new UnsupportedOperationException(UNMODIFIABLE_MESSAGE); } @Override public boolean equals(Object o) { return map.equals(o); } @Override public int hashCode() { return map.hashCode(); } @Override public String toString() { return map.toString(); } /** * A convenient builder for creating ImmutableMap instances. */ public static class Builder<K, V> { private final Map<K, V> entries; public Builder() { this.entries = new HashMap<>(); } /** * Add a key-value pair into the built map. The method will throw * IllegalArgumentException immediately when duplicate keys are * provided. * * @return Returns a reference to this object so that method calls can * be chained together. */ public Builder<K, V> put(K key, V value) { putAndWarnDuplicateKeys(entries, key, value); return this; } /** * Generates and returns a new ImmutableMap instance which * contains all the entries added into the Builder by {@code put()} * method. */ public ImmutableMap<K, V> build() { HashMap<K, V> builtMap = new HashMap<>(entries); return new ImmutableMap<>(builtMap); } } }
3,292
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/cache/CachedSupplier.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.cache; import static java.time.temporal.ChronoUnit.MINUTES; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.utils.ComparableUtils; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.SdkAutoCloseable; import software.amazon.awssdk.utils.Validate; /** * A wrapper for a {@link Supplier} that applies certain caching rules to the retrieval of its value, including customizable * pre-fetching behaviors for updating values as they get close to expiring so that not all threads have to block to update the * value. * * For example, the {@link OneCallerBlocks} strategy will have a single caller block to update the value, and the * {@link NonBlocking} strategy maintains a thread pool for updating the value asynchronously in the background. * * This should be created using {@link #builder(Supplier)}. */ @SdkProtectedApi public class CachedSupplier<T> implements Supplier<T>, SdkAutoCloseable { private static final Logger log = Logger.loggerFor(CachedSupplier.class); /** * Maximum time to wait for a blocking refresh lock before calling refresh again. This is to rate limit how many times we call * refresh. In the ideal case, refresh always occurs in a timely fashion and only one thread actually does the refresh. */ private static final Duration BLOCKING_REFRESH_MAX_WAIT = Duration.ofSeconds(5); /** * Used as a primitive form of rate limiting for the speed of our refreshes. This will make sure that the backing supplier has * a period of time to update the value when the {@link RefreshResult#staleTime()} arrives without getting called by every * thread that initiates a {@link #get()}. */ private final Lock refreshLock = new ReentrantLock(); /** * The strategy we should use for pre-fetching the cached data when the {@link RefreshResult#prefetchTime()} arrives. This is * configured when the cache is created via {@link Builder#prefetchStrategy(PrefetchStrategy)}. */ private final PrefetchStrategy prefetchStrategy; /** * Whether the {@link #prefetchStrategy} has been initialized via {@link PrefetchStrategy#initializeCachedSupplier}. */ private final AtomicBoolean prefetchStrategyInitialized = new AtomicBoolean(false); /** * How the supplier should behave when the cached value is stale on retrieval or fails to be retrieved. */ private final StaleValueBehavior staleValueBehavior; /** * The clock used by this supplier. Adjustable for testing. */ private final Clock clock; /** * The number of consecutive failures encountered when updating a stale value. */ private final AtomicInteger consecutiveStaleRetrievalFailures = new AtomicInteger(0); /** * The name to include with each log message, to differentiate caches. */ private final String cachedValueName; /** * The value currently stored in this cache. */ private volatile RefreshResult<T> cachedValue; /** * The "expensive" to call supplier that is used to refresh the {@link #cachedValue}. */ private final Supplier<RefreshResult<T>> valueSupplier; /** * Random instance used for jittering refresh results. */ private final Random jitterRandom = new Random(); private CachedSupplier(Builder<T> builder) { Validate.notNull(builder.supplier, "builder.supplier"); Validate.notNull(builder.jitterEnabled, "builder.jitterEnabled"); this.valueSupplier = jitteredPrefetchValueSupplier(builder.supplier, builder.jitterEnabled); this.prefetchStrategy = Validate.notNull(builder.prefetchStrategy, "builder.prefetchStrategy"); this.staleValueBehavior = Validate.notNull(builder.staleValueBehavior, "builder.staleValueBehavior"); this.clock = Validate.notNull(builder.clock, "builder.clock"); this.cachedValueName = Validate.notNull(builder.cachedValueName, "builder.cachedValueName"); } /** * Retrieve a builder that can be used for creating a {@link CachedSupplier}. * * @param valueSupplier The value supplier that should have its value cached. */ public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } @Override public T get() { if (cacheIsStale()) { log.debug(() -> "(" + cachedValueName + ") Cached value is stale and will be refreshed."); refreshCache(); } else if (shouldInitiateCachePrefetch()) { log.debug(() -> "(" + cachedValueName + ") Cached value has reached prefetch time and will be refreshed."); prefetchCache(); } return this.cachedValue.value(); } /** * Determines whether the value in this cache is stale, and all threads should block and wait for an updated value. */ private boolean cacheIsStale() { RefreshResult<T> currentCachedValue = cachedValue; if (currentCachedValue == null) { return true; } if (currentCachedValue.staleTime() == null) { return false; } Instant now = clock.instant(); return !now.isBefore(currentCachedValue.staleTime()); } /** * Determines whether the cached value's prefetch time has passed and we should initiate a pre-fetch on the value using the * configured {@link #prefetchStrategy}. */ private boolean shouldInitiateCachePrefetch() { RefreshResult<T> currentCachedValue = cachedValue; if (currentCachedValue == null) { return false; } if (currentCachedValue.prefetchTime() == null) { return false; } return !clock.instant().isBefore(currentCachedValue.prefetchTime()); } /** * Initiate a pre-fetch of the data using the configured {@link #prefetchStrategy}. */ private void prefetchCache() { prefetchStrategy.prefetch(this::refreshCache); } /** * Perform a blocking refresh of the cached value. This will rate limit synchronous refresh calls based on the * {@link #BLOCKING_REFRESH_MAX_WAIT} time. This ensures that when the data needs to be updated, we won't immediately hammer * the underlying value refresher if it can get back to us in a reasonable time. */ private void refreshCache() { try { boolean lockAcquired = refreshLock.tryLock(BLOCKING_REFRESH_MAX_WAIT.getSeconds(), TimeUnit.SECONDS); try { // Make sure the value was not refreshed while we waited for the lock. if (cacheIsStale() || shouldInitiateCachePrefetch()) { log.debug(() -> "(" + cachedValueName + ") Refreshing cached value."); // It wasn't, call the supplier to update it. if (prefetchStrategyInitialized.compareAndSet(false, true)) { prefetchStrategy.initializeCachedSupplier(this); } try { RefreshResult<T> cachedValue = handleFetchedSuccess(prefetchStrategy.fetch(valueSupplier)); this.cachedValue = cachedValue; log.debug(() -> "(" + cachedValueName + ") Successfully refreshed cached value. " + "Next Prefetch Time: " + cachedValue.prefetchTime() + ". " + "Next Stale Time: " + cachedValue.staleTime()); } catch (RuntimeException t) { cachedValue = handleFetchFailure(t); } } } finally { if (lockAcquired) { refreshLock.unlock(); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("Interrupted waiting to refresh a cached value.", e); } } /** * Perform necessary transformations of the successfully-fetched value based on the stale value behavior of this supplier. */ private RefreshResult<T> handleFetchedSuccess(RefreshResult<T> fetch) { consecutiveStaleRetrievalFailures.set(0); Instant now = clock.instant(); if (now.isBefore(fetch.staleTime())) { return fetch; } switch (staleValueBehavior) { case STRICT: Instant newStale = now.plusSeconds(1); log.warn(() -> "(" + cachedValueName + ") Retrieved value expiration is in the past (" + fetch.staleTime() + "). Using expiration of " + newStale); return fetch.toBuilder().staleTime(newStale).build(); // Refresh again in 1 second case ALLOW: Instant newStaleTime = jitterTime(now, Duration.ofMinutes(1), Duration.ofMinutes(10)); log.warn(() -> "(" + cachedValueName + ") Cached value expiration has been extended to " + newStaleTime + " because the downstream service returned a time in the past: " + fetch.staleTime()); return fetch.toBuilder() .staleTime(newStaleTime) .build(); default: throw new IllegalStateException("Unknown stale-value-behavior: " + staleValueBehavior); } } /** * Perform necessary transformations of the currently-cached value based on the stale value behavior of this supplier. */ private RefreshResult<T> handleFetchFailure(RuntimeException e) { log.debug(() -> "(" + cachedValueName + ") Failed to refresh cached value.", e); RefreshResult<T> currentCachedValue = cachedValue; if (currentCachedValue == null) { throw e; } Instant now = clock.instant(); if (!now.isBefore(currentCachedValue.staleTime())) { int numFailures = consecutiveStaleRetrievalFailures.incrementAndGet(); switch (staleValueBehavior) { case STRICT: throw e; case ALLOW: Instant newStaleTime = jitterTime(now, Duration.ofMillis(1), maxStaleFailureJitter(numFailures)); log.warn(() -> "(" + cachedValueName + ") Cached value expiration has been extended to " + newStaleTime + " because calling the downstream service failed (consecutive failures: " + numFailures + ").", e); return currentCachedValue.toBuilder() .staleTime(newStaleTime) .build(); default: throw new IllegalStateException("Unknown stale-value-behavior: " + staleValueBehavior); } } return currentCachedValue; } /** * Wrap a value supplier with one that jitters its prefetch time. */ private Supplier<RefreshResult<T>> jitteredPrefetchValueSupplier(Supplier<RefreshResult<T>> supplier, boolean prefetchJitterEnabled) { return () -> { RefreshResult<T> result = supplier.get(); if (!prefetchJitterEnabled || result.prefetchTime() == null) { return result; } Duration maxJitter = maxPrefetchJitter(result); if (maxJitter.isZero()) { return result; } Instant newPrefetchTime = jitterTime(result.prefetchTime(), Duration.ZERO, maxJitter); return result.toBuilder() .prefetchTime(newPrefetchTime) .build(); }; } private Duration maxPrefetchJitter(RefreshResult<T> result) { Instant staleTime = result.staleTime() != null ? result.staleTime() : Instant.MAX; Instant oneMinuteBeforeStale = staleTime.minus(1, MINUTES); if (!result.prefetchTime().isBefore(oneMinuteBeforeStale)) { return Duration.ZERO; } Duration timeBetweenPrefetchAndStale = Duration.between(result.prefetchTime(), oneMinuteBeforeStale); if (timeBetweenPrefetchAndStale.toDays() > 365) { // The value will essentially never become stale. The user is likely using this for a value that should be // periodically refreshed on a best-effort basis. Use a 5-minute jitter range to respect their requested // prefetch time. return Duration.ofMinutes(5); } return timeBetweenPrefetchAndStale; } private Duration maxStaleFailureJitter(int numFailures) { long exponentialBackoffMillis = (1L << numFailures - 1) * 100; return ComparableUtils.minimum(Duration.ofMillis(exponentialBackoffMillis), Duration.ofSeconds(10)); } private Instant jitterTime(Instant time, Duration jitterStart, Duration jitterEnd) { long jitterRange = jitterEnd.minus(jitterStart).toMillis(); long jitterAmount = Math.abs(jitterRandom.nextLong() % jitterRange); return time.plus(jitterStart).plusMillis(jitterAmount); } /** * Free any resources consumed by the prefetch strategy this supplier is using. */ @Override public void close() { prefetchStrategy.close(); } /** * A Builder for {@link CachedSupplier}, created by {@link #builder(Supplier)}. */ public static final class Builder<T> { private final Supplier<RefreshResult<T>> supplier; private PrefetchStrategy prefetchStrategy = new OneCallerBlocks(); private Boolean jitterEnabled = true; private StaleValueBehavior staleValueBehavior = StaleValueBehavior.STRICT; private Clock clock = Clock.systemUTC(); private String cachedValueName = "unknown"; private Builder(Supplier<RefreshResult<T>> supplier) { this.supplier = supplier; } /** * Configure the way in which data in the cache should be pre-fetched when the data's {@link RefreshResult#prefetchTime()} * arrives. * * By default, this uses the {@link OneCallerBlocks} strategy, which will block a single {@link #get()} caller to update * the value. */ public Builder<T> prefetchStrategy(PrefetchStrategy prefetchStrategy) { this.prefetchStrategy = prefetchStrategy; return this; } /** * Configure the way the cache should behave when a stale value is retrieved or when retrieving a value fails while the * cache is stale. * * By default, this uses {@link StaleValueBehavior#STRICT}. */ public Builder<T> staleValueBehavior(StaleValueBehavior staleValueBehavior) { this.staleValueBehavior = staleValueBehavior; return this; } /** * Configures a name for the cached value. This name will be included with logs emitted by this supplier, to aid * in debugging. * * By default, this uses "unknown". */ public Builder<T> cachedValueName(String cachedValueName) { this.cachedValueName = cachedValueName; return this; } /** * Configure the clock used for this cached supplier. Configurable for testing. */ @SdkTestInternalApi public Builder<T> clock(Clock clock) { this.clock = clock; return this; } /** * Whether jitter is enabled on the prefetch time. Can be disabled for testing. */ @SdkTestInternalApi Builder<T> jitterEnabled(Boolean jitterEnabled) { this.jitterEnabled = jitterEnabled; return this; } /** * Create a {@link CachedSupplier} using the current configuration of this builder. */ public CachedSupplier<T> build() { return new CachedSupplier<>(this); } } /** * The way in which the cache should be pre-fetched when the data's {@link RefreshResult#prefetchTime()} arrives. * * @see OneCallerBlocks * @see NonBlocking */ @FunctionalInterface public interface PrefetchStrategy extends SdkAutoCloseable { /** * Execute the provided value updater to update the cache. The specific implementation defines how this is invoked. */ void prefetch(Runnable valueUpdater); /** * Invoke the provided supplier to retrieve the refresh result. This is useful for prefetch strategies to override when * they care about the refresh result. */ default <T> RefreshResult<T> fetch(Supplier<RefreshResult<T>> supplier) { return supplier.get(); } /** * Invoked when the prefetch strategy is registered with a {@link CachedSupplier}. */ default void initializeCachedSupplier(CachedSupplier<?> cachedSupplier) { } /** * Free any resources associated with the strategy. This is invoked when the {@link CachedSupplier#close()} method is * invoked. */ @Override default void close() { } } /** * How the cached supplier should behave when a stale value is retrieved from the underlying supplier or the underlying * supplier fails while the cached value is stale. */ public enum StaleValueBehavior { /** * Strictly treat the stale time. Never return a stale cached value (except when the supplier returns an expired * value, in which case the supplier will return the value but only for a very short period of time to prevent * overloading the underlying supplier). */ STRICT, /** * Allow stale values to be returned from the cache. Value retrieval will never fail, as long as the cache has * succeeded when calling the underlying supplier at least once. */ ALLOW } }
3,293
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/cache/OneCallerBlocks.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.cache; import java.util.concurrent.atomic.AtomicBoolean; import software.amazon.awssdk.annotations.SdkProtectedApi; /** * A {@link CachedSupplier.PrefetchStrategy} that will have one caller at a time block to update the value. * * Multiple calls to {@link #prefetch(Runnable)} will result in only one caller actually performing the update, with the others * immediately returning. */ @SdkProtectedApi public class OneCallerBlocks implements CachedSupplier.PrefetchStrategy { /** * Whether we are currently refreshing the supplier. This is used to make sure only one caller is blocking at a time. */ private final AtomicBoolean currentlyRefreshing = new AtomicBoolean(false); @Override public void prefetch(Runnable valueUpdater) { if (currentlyRefreshing.compareAndSet(false, true)) { try { valueUpdater.run(); } finally { currentlyRefreshing.set(false); } } } }
3,294
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/cache/RefreshResult.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.cache; import java.time.Instant; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.builder.CopyableBuilder; import software.amazon.awssdk.utils.builder.ToCopyableBuilder; /** * A wrapper for the value returned by the {@link Supplier} underlying a {@link CachedSupplier}. The underlying {@link Supplier} * returns this to specify when the underlying value should be refreshed. */ @SdkProtectedApi public final class RefreshResult<T> implements ToCopyableBuilder<RefreshResult.Builder<T>, RefreshResult<T>> { private final T value; private final Instant staleTime; private final Instant prefetchTime; private RefreshResult(Builder<T> builder) { this.value = builder.value; this.staleTime = builder.staleTime; this.prefetchTime = builder.prefetchTime; } /** * Get a builder for creating a {@link RefreshResult}. * * @param value The value that should be cached by the supplier. */ public static <T> Builder<T> builder(T value) { return new Builder<>(value); } /** * The value resulting from the refresh. */ public T value() { return value; } /** * When the configured value is stale and should no longer be used. All threads will block until the value is updated. */ public Instant staleTime() { return staleTime; } /** * When the configured value is getting close to stale and should be updated using the supplier's * {@link CachedSupplier#prefetchStrategy}. */ public Instant prefetchTime() { return prefetchTime; } @Override public RefreshResult.Builder<T> toBuilder() { return new RefreshResult.Builder<>(this); } /** * A builder for a {@link RefreshResult}. */ public static final class Builder<T> implements CopyableBuilder<Builder<T>, RefreshResult<T>> { private final T value; private Instant staleTime = Instant.MAX; private Instant prefetchTime = Instant.MAX; private Builder(T value) { this.value = value; } private Builder(RefreshResult<T> value) { this.value = value.value; this.staleTime = value.staleTime; this.prefetchTime = value.prefetchTime; } /** * Specify the time at which the value in this cache is stale, and all calls to {@link CachedSupplier#get()} should block * to try to update the value. * * If this isn't specified, all threads will never block to update the value. */ public Builder<T> staleTime(Instant staleTime) { this.staleTime = staleTime; return this; } /** * Specify the time at which a thread that calls {@link CachedSupplier#get()} should trigger a cache prefetch. The * exact behavior of a "prefetch" is defined when the cache is created with * {@link CachedSupplier.Builder#prefetchStrategy(CachedSupplier.PrefetchStrategy)}, and may either have one thread block * to refresh the cache or have an asynchronous task reload the value in the background. * * If this isn't specified, the prefetch strategy will never be used and all threads will block to update the value when * the {@link #staleTime(Instant)} arrives. */ public Builder<T> prefetchTime(Instant prefetchTime) { this.prefetchTime = prefetchTime; return this; } /** * Build a {@link RefreshResult} using the values currently configured in this builder. */ public RefreshResult<T> build() { return new RefreshResult<>(this); } } }
3,295
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/cache/NonBlocking.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.cache; import java.time.Duration; import java.time.Instant; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.Semaphore; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.SdkTestInternalApi; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.ThreadFactoryBuilder; /** * A {@link CachedSupplier.PrefetchStrategy} that will run a single thread in the background to update the value. A call to * prefetch on this strategy will never return. * * Multiple calls to {@link #prefetch(Runnable)} will still only result in one background task performing the update. */ @SdkProtectedApi public class NonBlocking implements CachedSupplier.PrefetchStrategy { private static final Logger log = Logger.loggerFor(NonBlocking.class); /** * The maximum number of concurrent refreshes before we start logging warnings and skipping refreshes. */ private static final int MAX_CONCURRENT_REFRESHES = 100; /** * The semaphore around concurrent background refreshes, enforcing the {@link #MAX_CONCURRENT_REFRESHES}. */ private static final Semaphore CONCURRENT_REFRESH_LEASES = new Semaphore(MAX_CONCURRENT_REFRESHES); /** * Thread used to kick off refreshes during the prefetch window. This does not do the actual refreshing. That's left for * the {@link #EXECUTOR}. */ private static final ScheduledThreadPoolExecutor SCHEDULER = new ScheduledThreadPoolExecutor(1, new ThreadFactoryBuilder().threadNamePrefix("sdk-cache-scheduler") .daemonThreads(true) .build()); /** * Threads used to do the actual work of refreshing the values (because the cached supplier might block, so we don't * want the work to be done by a small thread pool). This executor is created as unbounded, but we start complaining and * skipping refreshes when there are more than {@link #MAX_CONCURRENT_REFRESHES} running. */ private static final ThreadPoolExecutor EXECUTOR = new ThreadPoolExecutor(1, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>(), new ThreadFactoryBuilder().threadNamePrefix("sdk-cache") .daemonThreads(true) .build()); /** * An incrementing number, used to uniquely identify an instance of NonBlocking in the {@link #asyncThreadName}. */ private static final AtomicLong INSTANCE_NUMBER = new AtomicLong(0); /** * Whether we are currently refreshing the supplier. This is used to make sure only one caller is blocking at a time. */ private final AtomicBoolean currentlyPrefetching = new AtomicBoolean(false); /** * Name of the thread refreshing the cache for this strategy. */ private final String asyncThreadName; /** * The refresh task currently scheduled for this non-blocking instance. We ensure that no more than one task is scheduled * per instance. */ private final AtomicReference<ScheduledFuture<?>> refreshTask = new AtomicReference<>(); /** * Whether this strategy has been shutdown (and should stop doing background refreshes) */ private volatile boolean shutdown = false; /** * The cached supplier using this non-blocking instance. */ private volatile CachedSupplier<?> cachedSupplier; static { // Ensure that cancelling a task actually removes it from the queue. SCHEDULER.setRemoveOnCancelPolicy(true); } /** * Create a non-blocking prefetch strategy that uses the provided value for the name of the background thread that will be * performing the update. */ public NonBlocking(String asyncThreadName) { this.asyncThreadName = asyncThreadName + "-" + INSTANCE_NUMBER.getAndIncrement(); } @SdkTestInternalApi static ThreadPoolExecutor executor() { return EXECUTOR; } @Override public void initializeCachedSupplier(CachedSupplier<?> cachedSupplier) { this.cachedSupplier = cachedSupplier; } @Override public void prefetch(Runnable valueUpdater) { // Only run one async prefetch at a time. if (currentlyPrefetching.compareAndSet(false, true)) { tryRunBackgroundTask(valueUpdater, () -> currentlyPrefetching.set(false)); } } @Override public <T> RefreshResult<T> fetch(Supplier<RefreshResult<T>> supplier) { RefreshResult<T> result = supplier.get(); schedulePrefetch(result); return result; } private void schedulePrefetch(RefreshResult<?> result) { if (shutdown || result.staleTime() == null || result.prefetchTime() == null) { return; } Duration timeUntilPrefetch = Duration.between(Instant.now(), result.prefetchTime()); if (timeUntilPrefetch.isNegative() || timeUntilPrefetch.toDays() > 7) { log.debug(() -> "Skipping background refresh because the prefetch time is in the past or too far in the future: " + result.prefetchTime()); return; } Instant backgroundRefreshTime = result.prefetchTime().plusSeconds(1); Duration timeUntilBackgroundRefresh = timeUntilPrefetch.plusSeconds(1); log.debug(() -> "Scheduling refresh attempt for " + backgroundRefreshTime + " (in " + timeUntilBackgroundRefresh.toMillis() + " ms)"); ScheduledFuture<?> scheduledTask = SCHEDULER.schedule(() -> { runWithInstanceThreadName(() -> { log.debug(() -> "Executing refresh attempt scheduled for " + backgroundRefreshTime); // If the supplier has already been prefetched, this will just be a cache hit. tryRunBackgroundTask(cachedSupplier::get); }); }, timeUntilBackgroundRefresh.toMillis(), TimeUnit.MILLISECONDS); updateTask(scheduledTask); if (shutdown) { updateTask(null); } } @Override public void close() { shutdown = true; updateTask(null); } public void updateTask(ScheduledFuture<?> newTask) { ScheduledFuture<?> currentTask; do { currentTask = refreshTask.get(); if (currentTask != null && !currentTask.isDone()) { currentTask.cancel(false); } } while (!refreshTask.compareAndSet(currentTask, newTask)); } public void tryRunBackgroundTask(Runnable runnable) { tryRunBackgroundTask(runnable, () -> { }); } public void tryRunBackgroundTask(Runnable runnable, Runnable runOnCompletion) { if (!CONCURRENT_REFRESH_LEASES.tryAcquire()) { log.warn(() -> "Skipping a background refresh task because there are too many other tasks running."); runOnCompletion.run(); return; } try { EXECUTOR.submit(() -> { runWithInstanceThreadName(() -> { try { runnable.run(); } catch (Throwable t) { log.warn(() -> "Exception occurred in AWS SDK background task.", t); } finally { CONCURRENT_REFRESH_LEASES.release(); runOnCompletion.run(); } }); }); } catch (Throwable t) { log.warn(() -> "Exception occurred when submitting AWS SDK background task.", t); CONCURRENT_REFRESH_LEASES.release(); runOnCompletion.run(); } } public void runWithInstanceThreadName(Runnable runnable) { String baseThreadName = Thread.currentThread().getName(); try { Thread.currentThread().setName(baseThreadName + "-" + asyncThreadName); runnable.run(); } finally { Thread.currentThread().setName(baseThreadName); } } }
3,296
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/cache
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/cache/lru/LruCache.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.cache.lru; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.annotations.ThreadSafe; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; /** * A thread-safe LRU (Least Recently Used) cache implementation that returns the value for a specified key, * retrieving it by either getting the stored value from the cache or using a supplied function to calculate that value * and add it to the cache. * <p> * When the cache is full, a new value will push out the least recently used value. * When the cache is queried for an already stored value (cache hit), this value is moved to the back of the queue * before it's returned so that the order of most recently used to least recently used can be maintained. * <p> * The user can configure the maximum size of the cache, which is set to a default of 100. * <p> * Null values are accepted. */ @SdkProtectedApi @ThreadSafe public final class LruCache<K, V> { private static final Logger log = Logger.loggerFor(LruCache.class); private static final int DEFAULT_SIZE = 100; private final Map<K, CacheEntry<K, V>> cache; private final Function<K, V> valueSupplier; private final Object listLock = new Object(); private final int maxCacheSize; private CacheEntry<K, V> leastRecentlyUsed = null; private CacheEntry<K, V> mostRecentlyUsed = null; private LruCache(Builder<K, V> b) { this.valueSupplier = b.supplier; Integer customSize = Validate.isPositiveOrNull(b.maxSize, "size"); this.maxCacheSize = customSize != null ? customSize : DEFAULT_SIZE; this.cache = new ConcurrentHashMap<>(); } /** * Get a value based on the key. If the value exists in the cache, it's returned, and it's position in the cache is updated. * Otherwise, the value is calculated based on the supplied function {@link Builder#builder(Function)}. */ public V get(K key) { while (true) { CacheEntry<K, V> cachedEntry = cache.computeIfAbsent(key, this::newEntry); synchronized (listLock) { if (cachedEntry.evicted()) { continue; } moveToBackOfQueue(cachedEntry); return cachedEntry.value(); } } } private CacheEntry<K, V> newEntry(K key) { V value = valueSupplier.apply(key); return new CacheEntry<>(key, value); } /** * Moves an entry to the back of the queue and sets it as the most recently used. If the entry is already the * most recently used, do nothing. * <p> * Summary of cache update: * <ol> * <li>Detach the entry from its current place in the double linked list.</li> * <li>Add it to the back of the queue (most recently used)</li> *</ol> */ private void moveToBackOfQueue(CacheEntry<K, V> entry) { if (entry.equals(mostRecentlyUsed)) { return; } removeFromQueue(entry); addToQueue(entry); } /** * Detaches an entry from its neighbors in the cache. Remove the entry from its current place in the double linked list * by letting its previous neighbor point to its next neighbor, and vice versa, if those exist. * <p> * The least-recently-used and most-recently-used pointers are reset if needed. * <p> * <b>Note:</b> Detaching an entry does not delete it from the cache hash map. */ private void removeFromQueue(CacheEntry<K, V> entry) { CacheEntry<K, V> previousEntry = entry.previous(); if (previousEntry != null) { previousEntry.setNext(entry.next()); } CacheEntry<K, V> nextEntry = entry.next(); if (nextEntry != null) { nextEntry.setPrevious(entry.previous()); } if (entry.equals(leastRecentlyUsed)) { leastRecentlyUsed = entry.previous(); } if (entry.equals(mostRecentlyUsed)) { mostRecentlyUsed = entry.next(); } } /** * Adds an entry to the queue as the most recently used, adjusts all pointers and triggers an evict * event if the cache is now full. */ private void addToQueue(CacheEntry<K, V> entry) { if (mostRecentlyUsed != null) { mostRecentlyUsed.setPrevious(entry); entry.setNext(mostRecentlyUsed); } entry.setPrevious(null); mostRecentlyUsed = entry; if (leastRecentlyUsed == null) { leastRecentlyUsed = entry; } if (size() > maxCacheSize) { evict(); } } /** * Removes the least recently used entry from the cache, marks it as evicted and removes it from the queue. */ private void evict() { leastRecentlyUsed.isEvicted(true); closeEvictedResourcesIfPossible(leastRecentlyUsed.value); cache.remove(leastRecentlyUsed.key()); removeFromQueue(leastRecentlyUsed); } private void closeEvictedResourcesIfPossible(V value) { if (value instanceof AutoCloseable) { try { ((AutoCloseable) value).close(); } catch (Exception e) { log.warn(() -> "Attempted to close instance that was evicted by cache, but got exception: " + e.getMessage()); } } } public int size() { return cache.size(); } public static <K, V> LruCache.Builder<K, V> builder(Function<K, V> supplier) { return new Builder<>(supplier); } public static final class Builder<K, V> { private final Function<K, V> supplier; private Integer maxSize; private Builder(Function<K, V> supplier) { this.supplier = supplier; } public Builder<K, V> maxSize(Integer maxSize) { this.maxSize = maxSize; return this; } public LruCache<K, V> build() { return new LruCache<>(this); } } private static final class CacheEntry<K, V> { private final K key; private final V value; private boolean evicted = false; private CacheEntry<K, V> previous; private CacheEntry<K, V> next; private CacheEntry(K key, V value) { this.key = key; this.value = value; } K key() { return key; } V value() { return value; } boolean evicted() { return evicted; } void isEvicted(boolean evicted) { this.evicted = evicted; } CacheEntry<K, V> next() { return next; } void setNext(CacheEntry<K, V> next) { this.next = next; } CacheEntry<K, V> previous() { return previous; } void setPrevious(CacheEntry<K, V> previous) { this.previous = previous; } @Override @SuppressWarnings("unchecked") public boolean equals(Object o) { if (this == o) { return true; } if ((o == null) || getClass() != o.getClass()) { return false; } CacheEntry<?, ?> that = (CacheEntry<?, ?>) o; return Objects.equals(key, that.key) && Objects.equals(value, that.value); } @Override public int hashCode() { int result = key != null ? key.hashCode() : 0; result = 31 * result + (value != null ? value.hashCode() : 0); return result; } } }
3,297
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/async/FlatteningSubscriber.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.Logger; import software.amazon.awssdk.utils.Validate; @SdkProtectedApi public class FlatteningSubscriber<U> extends DelegatingSubscriber<Iterable<U>, U> { private static final Logger log = Logger.loggerFor(FlatteningSubscriber.class); /** * The amount of unfulfilled demand open against the upstream subscriber. */ private final AtomicLong upstreamDemand = new AtomicLong(0); /** * The amount of unfulfilled demand the downstream subscriber has opened against us. */ private final AtomicLong downstreamDemand = new AtomicLong(0); /** * A flag that is used to ensure that only one thread is handling updates to the state of this subscriber at a time. This * allows us to ensure that the downstream onNext, onComplete and onError are only ever invoked serially. */ private final AtomicBoolean handlingStateUpdate = new AtomicBoolean(false); /** * Items given to us by the upstream subscriber that we will use to fulfill demand of the downstream subscriber. */ private final LinkedBlockingQueue<U> allItems = new LinkedBlockingQueue<>(); /** * Whether the upstream subscriber has called onError on us. If this is null, we haven't gotten an onError. If it's non-null * this will be the exception that the upstream passed to our onError. After we get an onError, we'll call onError on the * downstream subscriber as soon as possible. */ private final AtomicReference<Throwable> onErrorFromUpstream = new AtomicReference<>(null); /** * Whether we have called onComplete or onNext on the downstream subscriber. */ private volatile boolean terminalCallMadeDownstream = false; /** * Whether the upstream subscriber has called onComplete on us. After this happens, we'll drain any outstanding items in the * allItems queue and then call onComplete on the downstream subscriber. */ private volatile boolean onCompleteCalledByUpstream = false; /** * The subscription to the upstream subscriber. */ private Subscription upstreamSubscription; public FlatteningSubscriber(Subscriber<? super U> subscriber) { super(subscriber); } @Override public void onSubscribe(Subscription subscription) { if (upstreamSubscription != null) { log.warn(() -> "Received duplicate subscription, cancelling the duplicate.", new IllegalStateException()); subscription.cancel(); return; } upstreamSubscription = subscription; subscriber.onSubscribe(new Subscription() { @Override public void request(long l) { addDownstreamDemand(l); handleStateUpdate(); } @Override public void cancel() { subscription.cancel(); } }); } @Override public void onNext(Iterable<U> nextItems) { try { nextItems.forEach(item -> { Validate.notNull(nextItems, "Collections flattened by the flattening subscriber must not contain null."); allItems.add(item); }); } catch (RuntimeException e) { upstreamSubscription.cancel(); onError(e); throw e; } upstreamDemand.decrementAndGet(); handleStateUpdate(); } @Override public void onError(Throwable throwable) { onErrorFromUpstream.compareAndSet(null, throwable); handleStateUpdate(); } @Override public void onComplete() { onCompleteCalledByUpstream = true; handleStateUpdate(); } /** * Increment the downstream demand by the provided value, accounting for overflow. */ private void addDownstreamDemand(long l) { if (l > 0) { downstreamDemand.getAndUpdate(current -> { long newValue = current + l; return newValue >= 0 ? newValue : Long.MAX_VALUE; }); } else { log.error(() -> "Demand " + l + " must not be negative."); upstreamSubscription.cancel(); onError(new IllegalArgumentException("Demand must not be negative")); } } /** * This is invoked after each downstream request or upstream onNext, onError or onComplete. */ private void handleStateUpdate() { do { // Anything that happens after this if statement and before we set handlingStateUpdate to false is guaranteed to only // happen on one thread. For that reason, we should only invoke onNext, onComplete or onError within that block. if (!handlingStateUpdate.compareAndSet(false, true)) { return; } try { // If we've already called onComplete or onError, don't do anything. if (terminalCallMadeDownstream) { return; } // Call onNext, onComplete and onError as needed based on the current subscriber state. handleOnNextState(); handleUpstreamDemandState(); handleOnCompleteState(); handleOnErrorState(); } catch (Error e) { throw e; } catch (Throwable e) { log.error(() -> "Unexpected exception encountered that violates the reactive streams specification. Attempting " + "to terminate gracefully.", e); upstreamSubscription.cancel(); onError(e); } finally { handlingStateUpdate.set(false); } // It's possible we had an important state change between when we decided to release the state update flag, and we // actually released it. If that seems to have happened, try to handle that state change on this thread, because // another thread is not guaranteed to come around and do so. } while (onNextNeeded() || upstreamDemandNeeded() || onCompleteNeeded() || onErrorNeeded()); } /** * Fulfill downstream demand by pulling items out of the item queue and sending them downstream. */ private void handleOnNextState() { while (onNextNeeded() && !onErrorNeeded()) { downstreamDemand.decrementAndGet(); subscriber.onNext(allItems.poll()); } } /** * Returns true if we need to call onNext downstream. If this is executed outside the handling-state-update condition, the * result is subject to change. */ private boolean onNextNeeded() { return !allItems.isEmpty() && downstreamDemand.get() > 0; } /** * Request more upstream demand if it's needed. */ private void handleUpstreamDemandState() { if (upstreamDemandNeeded()) { ensureUpstreamDemandExists(); } } /** * Returns true if we need to increase our upstream demand. */ private boolean upstreamDemandNeeded() { return upstreamDemand.get() <= 0 && downstreamDemand.get() > 0 && allItems.isEmpty(); } /** * If there are zero pending items in the queue and the upstream has called onComplete, then tell the downstream * we're done. */ private void handleOnCompleteState() { if (onCompleteNeeded()) { terminalCallMadeDownstream = true; subscriber.onComplete(); } } /** * Returns true if we need to call onNext downstream. If this is executed outside the handling-state-update condition, the * result is subject to change. */ private boolean onCompleteNeeded() { return onCompleteCalledByUpstream && allItems.isEmpty() && !terminalCallMadeDownstream; } /** * If the upstream has called onError, then tell the downstream we're done, no matter what state the queue is in. */ private void handleOnErrorState() { if (onErrorNeeded()) { terminalCallMadeDownstream = true; subscriber.onError(onErrorFromUpstream.get()); } } /** * Returns true if we need to call onError downstream. If this is executed outside the handling-state-update condition, the * result is subject to change. */ private boolean onErrorNeeded() { return onErrorFromUpstream.get() != null && !terminalCallMadeDownstream; } /** * Ensure that we have at least 1 demand upstream, so that we can get more items. */ private void ensureUpstreamDemandExists() { if (this.upstreamDemand.get() < 0) { log.error(() -> "Upstream delivered more data than requested. Resetting state to prevent a frozen stream.", new IllegalStateException()); upstreamDemand.set(1); upstreamSubscription.request(1); } else if (this.upstreamDemand.compareAndSet(0, 1)) { upstreamSubscription.request(1); } } }
3,298
0
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils
Create_ds/aws-sdk-java-v2/utils/src/main/java/software/amazon/awssdk/utils/async/EventListeningSubscriber.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.utils.async; import java.util.function.Consumer; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import software.amazon.awssdk.annotations.SdkProtectedApi; import software.amazon.awssdk.utils.Logger; /** * A {@link Subscriber} that can invoke callbacks during various parts of the subscriber and subscription lifecycle. */ @SdkProtectedApi public final class EventListeningSubscriber<T> extends DelegatingSubscriber<T, T> { private static final Logger log = Logger.loggerFor(EventListeningSubscriber.class); private final Runnable afterCompleteListener; private final Consumer<Throwable> afterErrorListener; private final Runnable afterCancelListener; public EventListeningSubscriber(Subscriber<T> subscriber, Runnable afterCompleteListener, Consumer<Throwable> afterErrorListener, Runnable afterCancelListener) { super(subscriber); this.afterCompleteListener = afterCompleteListener; this.afterErrorListener = afterErrorListener; this.afterCancelListener = afterCancelListener; } @Override public void onNext(T t) { super.subscriber.onNext(t); } @Override public void onSubscribe(Subscription subscription) { super.onSubscribe(new CancelListeningSubscriber(subscription)); } @Override public void onError(Throwable throwable) { super.onError(throwable); if (afterErrorListener != null) { callListener(() -> afterErrorListener.accept(throwable), "Post-onError callback failed. This exception will be dropped."); } } @Override public void onComplete() { super.onComplete(); callListener(afterCompleteListener, "Post-onComplete callback failed. This exception will be dropped."); } private class CancelListeningSubscriber extends DelegatingSubscription { protected CancelListeningSubscriber(Subscription s) { super(s); } @Override public void cancel() { super.cancel(); callListener(afterCancelListener, "Post-cancel callback failed. This exception will be dropped."); } } private void callListener(Runnable listener, String listenerFailureMessage) { if (listener != null) { try { listener.run(); } catch (RuntimeException e) { log.error(() -> listenerFailureMessage, e); } } } }
3,299