target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void hostComponentWithEncodedString_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("id"); exception.expectMessage("63"); HostnameValidator.validateHostnameCompliant(LONG_STRING_64, "id", "test"); } | public static void validateHostnameCompliant(String hostnameComponent, String paramName, String object) { if (StringUtils.isEmpty(hostnameComponent)) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the required '%s' " + "component is missing.", object, paramName)); } if (hostnameComponent.length() > HOSTNAME_MAX_LENGTH) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component exceeds the maximum length of %d characters.", object, paramName, HOSTNAME_MAX_LENGTH)); } Matcher m = HOSTNAME_COMPLIANT_PATTERN.matcher(hostnameComponent); if (!m.matches()) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component must only contain alphanumeric characters and dashes.", object, paramName)); } } | HostnameValidator { public static void validateHostnameCompliant(String hostnameComponent, String paramName, String object) { if (StringUtils.isEmpty(hostnameComponent)) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the required '%s' " + "component is missing.", object, paramName)); } if (hostnameComponent.length() > HOSTNAME_MAX_LENGTH) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component exceeds the maximum length of %d characters.", object, paramName, HOSTNAME_MAX_LENGTH)); } Matcher m = HOSTNAME_COMPLIANT_PATTERN.matcher(hostnameComponent); if (!m.matches()) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component must only contain alphanumeric characters and dashes.", object, paramName)); } } } | HostnameValidator { public static void validateHostnameCompliant(String hostnameComponent, String paramName, String object) { if (StringUtils.isEmpty(hostnameComponent)) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the required '%s' " + "component is missing.", object, paramName)); } if (hostnameComponent.length() > HOSTNAME_MAX_LENGTH) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component exceeds the maximum length of %d characters.", object, paramName, HOSTNAME_MAX_LENGTH)); } Matcher m = HOSTNAME_COMPLIANT_PATTERN.matcher(hostnameComponent); if (!m.matches()) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component must only contain alphanumeric characters and dashes.", object, paramName)); } } private HostnameValidator(); } | HostnameValidator { public static void validateHostnameCompliant(String hostnameComponent, String paramName, String object) { if (StringUtils.isEmpty(hostnameComponent)) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the required '%s' " + "component is missing.", object, paramName)); } if (hostnameComponent.length() > HOSTNAME_MAX_LENGTH) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component exceeds the maximum length of %d characters.", object, paramName, HOSTNAME_MAX_LENGTH)); } Matcher m = HOSTNAME_COMPLIANT_PATTERN.matcher(hostnameComponent); if (!m.matches()) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component must only contain alphanumeric characters and dashes.", object, paramName)); } } private HostnameValidator(); static void validateHostnameCompliant(String hostnameComponent, String paramName, String object); } | HostnameValidator { public static void validateHostnameCompliant(String hostnameComponent, String paramName, String object) { if (StringUtils.isEmpty(hostnameComponent)) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the required '%s' " + "component is missing.", object, paramName)); } if (hostnameComponent.length() > HOSTNAME_MAX_LENGTH) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component exceeds the maximum length of %d characters.", object, paramName, HOSTNAME_MAX_LENGTH)); } Matcher m = HOSTNAME_COMPLIANT_PATTERN.matcher(hostnameComponent); if (!m.matches()) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component must only contain alphanumeric characters and dashes.", object, paramName)); } } private HostnameValidator(); static void validateHostnameCompliant(String hostnameComponent, String paramName, String object); } |
@Test public void hostComponentTooLong_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("id"); exception.expectMessage("63"); HostnameValidator.validateHostnameCompliant(LONG_STRING_64, "id", "test"); } | public static void validateHostnameCompliant(String hostnameComponent, String paramName, String object) { if (StringUtils.isEmpty(hostnameComponent)) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the required '%s' " + "component is missing.", object, paramName)); } if (hostnameComponent.length() > HOSTNAME_MAX_LENGTH) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component exceeds the maximum length of %d characters.", object, paramName, HOSTNAME_MAX_LENGTH)); } Matcher m = HOSTNAME_COMPLIANT_PATTERN.matcher(hostnameComponent); if (!m.matches()) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component must only contain alphanumeric characters and dashes.", object, paramName)); } } | HostnameValidator { public static void validateHostnameCompliant(String hostnameComponent, String paramName, String object) { if (StringUtils.isEmpty(hostnameComponent)) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the required '%s' " + "component is missing.", object, paramName)); } if (hostnameComponent.length() > HOSTNAME_MAX_LENGTH) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component exceeds the maximum length of %d characters.", object, paramName, HOSTNAME_MAX_LENGTH)); } Matcher m = HOSTNAME_COMPLIANT_PATTERN.matcher(hostnameComponent); if (!m.matches()) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component must only contain alphanumeric characters and dashes.", object, paramName)); } } } | HostnameValidator { public static void validateHostnameCompliant(String hostnameComponent, String paramName, String object) { if (StringUtils.isEmpty(hostnameComponent)) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the required '%s' " + "component is missing.", object, paramName)); } if (hostnameComponent.length() > HOSTNAME_MAX_LENGTH) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component exceeds the maximum length of %d characters.", object, paramName, HOSTNAME_MAX_LENGTH)); } Matcher m = HOSTNAME_COMPLIANT_PATTERN.matcher(hostnameComponent); if (!m.matches()) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component must only contain alphanumeric characters and dashes.", object, paramName)); } } private HostnameValidator(); } | HostnameValidator { public static void validateHostnameCompliant(String hostnameComponent, String paramName, String object) { if (StringUtils.isEmpty(hostnameComponent)) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the required '%s' " + "component is missing.", object, paramName)); } if (hostnameComponent.length() > HOSTNAME_MAX_LENGTH) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component exceeds the maximum length of %d characters.", object, paramName, HOSTNAME_MAX_LENGTH)); } Matcher m = HOSTNAME_COMPLIANT_PATTERN.matcher(hostnameComponent); if (!m.matches()) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component must only contain alphanumeric characters and dashes.", object, paramName)); } } private HostnameValidator(); static void validateHostnameCompliant(String hostnameComponent, String paramName, String object); } | HostnameValidator { public static void validateHostnameCompliant(String hostnameComponent, String paramName, String object) { if (StringUtils.isEmpty(hostnameComponent)) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the required '%s' " + "component is missing.", object, paramName)); } if (hostnameComponent.length() > HOSTNAME_MAX_LENGTH) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component exceeds the maximum length of %d characters.", object, paramName, HOSTNAME_MAX_LENGTH)); } Matcher m = HOSTNAME_COMPLIANT_PATTERN.matcher(hostnameComponent); if (!m.matches()) { throw new IllegalArgumentException( String.format("The provided %s is not valid: the '%s' " + "component must only contain alphanumeric characters and dashes.", object, paramName)); } } private HostnameValidator(); static void validateHostnameCompliant(String hostnameComponent, String paramName, String object); } |
@Test public void modifyAsyncHttpContent_putObjectRequestChecksumEnabled_shouldWrapChecksumRequestBody() { ExecutionAttributes executionAttributes = getExecutionAttributes(); Context.ModifyHttpRequest modifyHttpRequest = InterceptorTestUtils.modifyHttpRequestContext(PutObjectRequest.builder().build()); Optional<AsyncRequestBody> asyncRequestBody = interceptor.modifyAsyncHttpContent(modifyHttpRequest, executionAttributes); assertThat(asyncRequestBody.isPresent()).isTrue(); assertThat(executionAttributes.getAttribute(CHECKSUM)).isNotNull(); assertThat(asyncRequestBody.get()).isExactlyInstanceOf(ChecksumCalculatingAsyncRequestBody.class); } | @Override public Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { boolean shouldRecordChecksum = shouldRecordChecksum(context.request(), ASYNC, executionAttributes, context.httpRequest()); if (shouldRecordChecksum && context.asyncRequestBody().isPresent()) { SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(ASYNC_RECORDING_CHECKSUM, true); executionAttributes.putAttribute(CHECKSUM, checksum); return Optional.of(new ChecksumCalculatingAsyncRequestBody(context.asyncRequestBody().get(), checksum)); } return context.asyncRequestBody(); } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { boolean shouldRecordChecksum = shouldRecordChecksum(context.request(), ASYNC, executionAttributes, context.httpRequest()); if (shouldRecordChecksum && context.asyncRequestBody().isPresent()) { SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(ASYNC_RECORDING_CHECKSUM, true); executionAttributes.putAttribute(CHECKSUM, checksum); return Optional.of(new ChecksumCalculatingAsyncRequestBody(context.asyncRequestBody().get(), checksum)); } return context.asyncRequestBody(); } } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { boolean shouldRecordChecksum = shouldRecordChecksum(context.request(), ASYNC, executionAttributes, context.httpRequest()); if (shouldRecordChecksum && context.asyncRequestBody().isPresent()) { SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(ASYNC_RECORDING_CHECKSUM, true); executionAttributes.putAttribute(CHECKSUM, checksum); return Optional.of(new ChecksumCalculatingAsyncRequestBody(context.asyncRequestBody().get(), checksum)); } return context.asyncRequestBody(); } } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { boolean shouldRecordChecksum = shouldRecordChecksum(context.request(), ASYNC, executionAttributes, context.httpRequest()); if (shouldRecordChecksum && context.asyncRequestBody().isPresent()) { SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(ASYNC_RECORDING_CHECKSUM, true); executionAttributes.putAttribute(CHECKSUM, checksum); return Optional.of(new ChecksumCalculatingAsyncRequestBody(context.asyncRequestBody().get(), checksum)); } return context.asyncRequestBody(); } @Override Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { boolean shouldRecordChecksum = shouldRecordChecksum(context.request(), ASYNC, executionAttributes, context.httpRequest()); if (shouldRecordChecksum && context.asyncRequestBody().isPresent()) { SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(ASYNC_RECORDING_CHECKSUM, true); executionAttributes.putAttribute(CHECKSUM, checksum); return Optional.of(new ChecksumCalculatingAsyncRequestBody(context.asyncRequestBody().get(), checksum)); } return context.asyncRequestBody(); } @Override Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); } |
@Test public void testEmptyByteArray() throws Exception { String s = IoUtils.toUtf8String(new ByteArrayInputStream(new byte[0])); assertEquals("", s); } | public static String toUtf8String(InputStream is) throws IOException { return new String(toByteArray(is), StandardCharsets.UTF_8); } | IoUtils { public static String toUtf8String(InputStream is) throws IOException { return new String(toByteArray(is), StandardCharsets.UTF_8); } } | IoUtils { public static String toUtf8String(InputStream is) throws IOException { return new String(toByteArray(is), StandardCharsets.UTF_8); } private IoUtils(); } | IoUtils { public static String toUtf8String(InputStream is) throws IOException { return new String(toByteArray(is), StandardCharsets.UTF_8); } private IoUtils(); static byte[] toByteArray(InputStream is); static String toUtf8String(InputStream is); static void closeQuietly(AutoCloseable is, Logger log); static void closeIfCloseable(Object maybeCloseable, Logger log); static long copy(InputStream in, OutputStream out); static long copy(InputStream in, OutputStream out, long readLimit); static void drainInputStream(InputStream in); static void markStreamWithMaxReadLimit(InputStream s); } | IoUtils { public static String toUtf8String(InputStream is) throws IOException { return new String(toByteArray(is), StandardCharsets.UTF_8); } private IoUtils(); static byte[] toByteArray(InputStream is); static String toUtf8String(InputStream is); static void closeQuietly(AutoCloseable is, Logger log); static void closeIfCloseable(Object maybeCloseable, Logger log); static long copy(InputStream in, OutputStream out); static long copy(InputStream in, OutputStream out, long readLimit); static void drainInputStream(InputStream in); static void markStreamWithMaxReadLimit(InputStream s); } |
@Test public void testZeroByteStream() throws Exception { String s = IoUtils.toUtf8String(new InputStream() { @Override public int read() throws IOException { return -1; } }); assertEquals("", s); } | public static String toUtf8String(InputStream is) throws IOException { return new String(toByteArray(is), StandardCharsets.UTF_8); } | IoUtils { public static String toUtf8String(InputStream is) throws IOException { return new String(toByteArray(is), StandardCharsets.UTF_8); } } | IoUtils { public static String toUtf8String(InputStream is) throws IOException { return new String(toByteArray(is), StandardCharsets.UTF_8); } private IoUtils(); } | IoUtils { public static String toUtf8String(InputStream is) throws IOException { return new String(toByteArray(is), StandardCharsets.UTF_8); } private IoUtils(); static byte[] toByteArray(InputStream is); static String toUtf8String(InputStream is); static void closeQuietly(AutoCloseable is, Logger log); static void closeIfCloseable(Object maybeCloseable, Logger log); static long copy(InputStream in, OutputStream out); static long copy(InputStream in, OutputStream out, long readLimit); static void drainInputStream(InputStream in); static void markStreamWithMaxReadLimit(InputStream s); } | IoUtils { public static String toUtf8String(InputStream is) throws IOException { return new String(toByteArray(is), StandardCharsets.UTF_8); } private IoUtils(); static byte[] toByteArray(InputStream is); static String toUtf8String(InputStream is); static void closeQuietly(AutoCloseable is, Logger log); static void closeIfCloseable(Object maybeCloseable, Logger log); static long copy(InputStream in, OutputStream out); static long copy(InputStream in, OutputStream out, long readLimit); static void drainInputStream(InputStream in); static void markStreamWithMaxReadLimit(InputStream s); } |
@Test public void test() throws Exception { String s = IoUtils.toUtf8String(new ByteArrayInputStream("Testing".getBytes(StandardCharsets.UTF_8))); assertEquals("Testing", s); } | public static String toUtf8String(InputStream is) throws IOException { return new String(toByteArray(is), StandardCharsets.UTF_8); } | IoUtils { public static String toUtf8String(InputStream is) throws IOException { return new String(toByteArray(is), StandardCharsets.UTF_8); } } | IoUtils { public static String toUtf8String(InputStream is) throws IOException { return new String(toByteArray(is), StandardCharsets.UTF_8); } private IoUtils(); } | IoUtils { public static String toUtf8String(InputStream is) throws IOException { return new String(toByteArray(is), StandardCharsets.UTF_8); } private IoUtils(); static byte[] toByteArray(InputStream is); static String toUtf8String(InputStream is); static void closeQuietly(AutoCloseable is, Logger log); static void closeIfCloseable(Object maybeCloseable, Logger log); static long copy(InputStream in, OutputStream out); static long copy(InputStream in, OutputStream out, long readLimit); static void drainInputStream(InputStream in); static void markStreamWithMaxReadLimit(InputStream s); } | IoUtils { public static String toUtf8String(InputStream is) throws IOException { return new String(toByteArray(is), StandardCharsets.UTF_8); } private IoUtils(); static byte[] toByteArray(InputStream is); static String toUtf8String(InputStream is); static void closeQuietly(AutoCloseable is, Logger log); static void closeIfCloseable(Object maybeCloseable, Logger log); static long copy(InputStream in, OutputStream out); static long copy(InputStream in, OutputStream out, long readLimit); static void drainInputStream(InputStream in); static void markStreamWithMaxReadLimit(InputStream s); } |
@Test public void drainInputStream_AlreadyEos_DoesNotThrowException() throws IOException { final InputStream inputStream = randomInputStream(); while (inputStream.read() != -1) { } IoUtils.drainInputStream(inputStream); } | public static void drainInputStream(InputStream in) { try { while (in.read() != -1) { } } catch (IOException ignored) { } } | IoUtils { public static void drainInputStream(InputStream in) { try { while (in.read() != -1) { } } catch (IOException ignored) { } } } | IoUtils { public static void drainInputStream(InputStream in) { try { while (in.read() != -1) { } } catch (IOException ignored) { } } private IoUtils(); } | IoUtils { public static void drainInputStream(InputStream in) { try { while (in.read() != -1) { } } catch (IOException ignored) { } } private IoUtils(); static byte[] toByteArray(InputStream is); static String toUtf8String(InputStream is); static void closeQuietly(AutoCloseable is, Logger log); static void closeIfCloseable(Object maybeCloseable, Logger log); static long copy(InputStream in, OutputStream out); static long copy(InputStream in, OutputStream out, long readLimit); static void drainInputStream(InputStream in); static void markStreamWithMaxReadLimit(InputStream s); } | IoUtils { public static void drainInputStream(InputStream in) { try { while (in.read() != -1) { } } catch (IOException ignored) { } } private IoUtils(); static byte[] toByteArray(InputStream is); static String toUtf8String(InputStream is); static void closeQuietly(AutoCloseable is, Logger log); static void closeIfCloseable(Object maybeCloseable, Logger log); static long copy(InputStream in, OutputStream out); static long copy(InputStream in, OutputStream out, long readLimit); static void drainInputStream(InputStream in); static void markStreamWithMaxReadLimit(InputStream s); } |
@Test public void drainInputStream_RemainingBytesInStream_ReadsAllRemainingData() throws IOException { final InputStream inputStream = randomInputStream(); IoUtils.drainInputStream(inputStream); assertEquals(-1, inputStream.read()); } | public static void drainInputStream(InputStream in) { try { while (in.read() != -1) { } } catch (IOException ignored) { } } | IoUtils { public static void drainInputStream(InputStream in) { try { while (in.read() != -1) { } } catch (IOException ignored) { } } } | IoUtils { public static void drainInputStream(InputStream in) { try { while (in.read() != -1) { } } catch (IOException ignored) { } } private IoUtils(); } | IoUtils { public static void drainInputStream(InputStream in) { try { while (in.read() != -1) { } } catch (IOException ignored) { } } private IoUtils(); static byte[] toByteArray(InputStream is); static String toUtf8String(InputStream is); static void closeQuietly(AutoCloseable is, Logger log); static void closeIfCloseable(Object maybeCloseable, Logger log); static long copy(InputStream in, OutputStream out); static long copy(InputStream in, OutputStream out, long readLimit); static void drainInputStream(InputStream in); static void markStreamWithMaxReadLimit(InputStream s); } | IoUtils { public static void drainInputStream(InputStream in) { try { while (in.read() != -1) { } } catch (IOException ignored) { } } private IoUtils(); static byte[] toByteArray(InputStream is); static String toUtf8String(InputStream is); static void closeQuietly(AutoCloseable is, Logger log); static void closeIfCloseable(Object maybeCloseable, Logger log); static long copy(InputStream in, OutputStream out); static long copy(InputStream in, OutputStream out, long readLimit); static void drainInputStream(InputStream in); static void markStreamWithMaxReadLimit(InputStream s); } |
@Test public void allCallsBeforeInitializationBlock() { try (WaitingSupplier waitingSupplier = new WaitingSupplier(future(), future())) { CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier).build(); performAsyncGets(cachedSupplier, 2); waitingSupplier.waitForGetsToHaveStarted(2); } } | public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } | CachedSupplier implements Supplier<T>, SdkAutoCloseable { public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } } | CachedSupplier implements Supplier<T>, SdkAutoCloseable { public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } private CachedSupplier(Builder<T> builder); } | CachedSupplier implements Supplier<T>, SdkAutoCloseable { public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } private CachedSupplier(Builder<T> builder); static CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier); @Override T get(); @Override void close(); } | CachedSupplier implements Supplier<T>, SdkAutoCloseable { public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } private CachedSupplier(Builder<T> builder); static CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier); @Override T get(); @Override void close(); } |
@Test public void staleValueBlocksAllCalls() { try (WaitingSupplier waitingSupplier = new WaitingSupplier(past(), future())) { CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier).build(); waitingSupplier.permits.release(1); waitFor(performAsyncGet(cachedSupplier)); performAsyncGets(cachedSupplier, 2); waitingSupplier.waitForGetsToHaveStarted(3); waitingSupplier.permits.release(50); waitForAsyncGetsToFinish(); waitingSupplier.waitForGetsToHaveFinished(3); } } | public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } | CachedSupplier implements Supplier<T>, SdkAutoCloseable { public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } } | CachedSupplier implements Supplier<T>, SdkAutoCloseable { public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } private CachedSupplier(Builder<T> builder); } | CachedSupplier implements Supplier<T>, SdkAutoCloseable { public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } private CachedSupplier(Builder<T> builder); static CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier); @Override T get(); @Override void close(); } | CachedSupplier implements Supplier<T>, SdkAutoCloseable { public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } private CachedSupplier(Builder<T> builder); static CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier); @Override T get(); @Override void close(); } |
@Test public void basicCachingWorks() { try (WaitingSupplier waitingSupplier = new WaitingSupplier(future(), future())) { CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier).build(); waitingSupplier.permits.release(5); waitFor(performAsyncGets(cachedSupplier, 5)); waitingSupplier.waitForGetsToHaveFinished(1); } } | public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } | CachedSupplier implements Supplier<T>, SdkAutoCloseable { public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } } | CachedSupplier implements Supplier<T>, SdkAutoCloseable { public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } private CachedSupplier(Builder<T> builder); } | CachedSupplier implements Supplier<T>, SdkAutoCloseable { public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } private CachedSupplier(Builder<T> builder); static CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier); @Override T get(); @Override void close(); } | CachedSupplier implements Supplier<T>, SdkAutoCloseable { public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } private CachedSupplier(Builder<T> builder); static CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier); @Override T get(); @Override void close(); } |
@Test public void oneCallerBlocksPrefetchStrategyWorks() throws InterruptedException { try (WaitingSupplier waitingSupplier = new WaitingSupplier(future(), past())) { CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier) .prefetchStrategy(new OneCallerBlocks()) .build(); waitingSupplier.permits.release(1); waitFor(performAsyncGet(cachedSupplier)); performAsyncGet(cachedSupplier); waitingSupplier.waitForGetsToHaveStarted(2); waitFor(performAsyncGet(cachedSupplier)); waitingSupplier.permits.release(50); waitForAsyncGetsToFinish(); waitingSupplier.waitForGetsToHaveFinished(2); } } | public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } | CachedSupplier implements Supplier<T>, SdkAutoCloseable { public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } } | CachedSupplier implements Supplier<T>, SdkAutoCloseable { public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } private CachedSupplier(Builder<T> builder); } | CachedSupplier implements Supplier<T>, SdkAutoCloseable { public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } private CachedSupplier(Builder<T> builder); static CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier); @Override T get(); @Override void close(); } | CachedSupplier implements Supplier<T>, SdkAutoCloseable { public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } private CachedSupplier(Builder<T> builder); static CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier); @Override T get(); @Override void close(); } |
@Test public void nonBlockingPrefetchStrategyWorks() { try (WaitingSupplier waitingSupplier = new WaitingSupplier(future(), past()); CachedSupplier<String> cachedSupplier = CachedSupplier.builder(waitingSupplier) .prefetchStrategy(new NonBlocking("test-%s")) .build()) { waitingSupplier.permits.release(1); waitFor(performAsyncGet(cachedSupplier)); waitFor(performAsyncGet(cachedSupplier)); waitingSupplier.waitForGetsToHaveStarted(2); waitingSupplier.waitForGetsToHaveFinished(1); } } | public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } | CachedSupplier implements Supplier<T>, SdkAutoCloseable { public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } } | CachedSupplier implements Supplier<T>, SdkAutoCloseable { public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } private CachedSupplier(Builder<T> builder); } | CachedSupplier implements Supplier<T>, SdkAutoCloseable { public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } private CachedSupplier(Builder<T> builder); static CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier); @Override T get(); @Override void close(); } | CachedSupplier implements Supplier<T>, SdkAutoCloseable { public static <T> CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier) { return new CachedSupplier.Builder<>(valueSupplier); } private CachedSupplier(Builder<T> builder); static CachedSupplier.Builder<T> builder(Supplier<RefreshResult<T>> valueSupplier); @Override T get(); @Override void close(); } |
@Test public void modifyAsyncHttpContent_nonPutObjectRequest_shouldNotModify() { ExecutionAttributes executionAttributes = getExecutionAttributes(); Context.ModifyHttpRequest modifyHttpRequest = InterceptorTestUtils.modifyHttpRequestContext(GetObjectRequest.builder().build()); Optional<AsyncRequestBody> asyncRequestBody = interceptor.modifyAsyncHttpContent(modifyHttpRequest, executionAttributes); assertThat(asyncRequestBody).isEqualTo(modifyHttpRequest.asyncRequestBody()); } | @Override public Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { boolean shouldRecordChecksum = shouldRecordChecksum(context.request(), ASYNC, executionAttributes, context.httpRequest()); if (shouldRecordChecksum && context.asyncRequestBody().isPresent()) { SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(ASYNC_RECORDING_CHECKSUM, true); executionAttributes.putAttribute(CHECKSUM, checksum); return Optional.of(new ChecksumCalculatingAsyncRequestBody(context.asyncRequestBody().get(), checksum)); } return context.asyncRequestBody(); } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { boolean shouldRecordChecksum = shouldRecordChecksum(context.request(), ASYNC, executionAttributes, context.httpRequest()); if (shouldRecordChecksum && context.asyncRequestBody().isPresent()) { SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(ASYNC_RECORDING_CHECKSUM, true); executionAttributes.putAttribute(CHECKSUM, checksum); return Optional.of(new ChecksumCalculatingAsyncRequestBody(context.asyncRequestBody().get(), checksum)); } return context.asyncRequestBody(); } } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { boolean shouldRecordChecksum = shouldRecordChecksum(context.request(), ASYNC, executionAttributes, context.httpRequest()); if (shouldRecordChecksum && context.asyncRequestBody().isPresent()) { SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(ASYNC_RECORDING_CHECKSUM, true); executionAttributes.putAttribute(CHECKSUM, checksum); return Optional.of(new ChecksumCalculatingAsyncRequestBody(context.asyncRequestBody().get(), checksum)); } return context.asyncRequestBody(); } } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { boolean shouldRecordChecksum = shouldRecordChecksum(context.request(), ASYNC, executionAttributes, context.httpRequest()); if (shouldRecordChecksum && context.asyncRequestBody().isPresent()) { SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(ASYNC_RECORDING_CHECKSUM, true); executionAttributes.putAttribute(CHECKSUM, checksum); return Optional.of(new ChecksumCalculatingAsyncRequestBody(context.asyncRequestBody().get(), checksum)); } return context.asyncRequestBody(); } @Override Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { boolean shouldRecordChecksum = shouldRecordChecksum(context.request(), ASYNC, executionAttributes, context.httpRequest()); if (shouldRecordChecksum && context.asyncRequestBody().isPresent()) { SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(ASYNC_RECORDING_CHECKSUM, true); executionAttributes.putAttribute(CHECKSUM, checksum); return Optional.of(new ChecksumCalculatingAsyncRequestBody(context.asyncRequestBody().get(), checksum)); } return context.asyncRequestBody(); } @Override Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); } |
@Test public void safeCompare_SecondNull_ReturnsPositive() { assertThat(ComparableUtils.safeCompare(1.0, null), greaterThan(0)); } | 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; } } | ComparableUtils { public static <T> int safeCompare(Comparable<T> d1, T d2) { if (d1 != null && d2 != null) { return d1.compareTo(d2); } else if (d1 == null && d2 != null) { return -1; } else if (d1 != null) { return 1; } else { return 0; } } } | ComparableUtils { public static <T> int safeCompare(Comparable<T> d1, T d2) { if (d1 != null && d2 != null) { return d1.compareTo(d2); } else if (d1 == null && d2 != null) { return -1; } else if (d1 != null) { return 1; } else { return 0; } } private ComparableUtils(); } | ComparableUtils { public static <T> int safeCompare(Comparable<T> d1, T d2) { if (d1 != null && d2 != null) { return d1.compareTo(d2); } else if (d1 == null && d2 != null) { return -1; } else if (d1 != null) { return 1; } else { return 0; } } private ComparableUtils(); static int safeCompare(Comparable<T> d1, T d2); @SafeVarargs static T minimum(T... values); } | ComparableUtils { public static <T> int safeCompare(Comparable<T> d1, T d2) { if (d1 != null && d2 != null) { return d1.compareTo(d2); } else if (d1 == null && d2 != null) { return -1; } else if (d1 != null) { return 1; } else { return 0; } } private ComparableUtils(); static int safeCompare(Comparable<T> d1, T d2); @SafeVarargs static T minimum(T... values); } |
@Test public void safeCompare_FirstNull_ReturnsNegative() { assertThat(ComparableUtils.safeCompare(null, 7.0), lessThan(0)); } | 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; } } | ComparableUtils { public static <T> int safeCompare(Comparable<T> d1, T d2) { if (d1 != null && d2 != null) { return d1.compareTo(d2); } else if (d1 == null && d2 != null) { return -1; } else if (d1 != null) { return 1; } else { return 0; } } } | ComparableUtils { public static <T> int safeCompare(Comparable<T> d1, T d2) { if (d1 != null && d2 != null) { return d1.compareTo(d2); } else if (d1 == null && d2 != null) { return -1; } else if (d1 != null) { return 1; } else { return 0; } } private ComparableUtils(); } | ComparableUtils { public static <T> int safeCompare(Comparable<T> d1, T d2) { if (d1 != null && d2 != null) { return d1.compareTo(d2); } else if (d1 == null && d2 != null) { return -1; } else if (d1 != null) { return 1; } else { return 0; } } private ComparableUtils(); static int safeCompare(Comparable<T> d1, T d2); @SafeVarargs static T minimum(T... values); } | ComparableUtils { public static <T> int safeCompare(Comparable<T> d1, T d2) { if (d1 != null && d2 != null) { return d1.compareTo(d2); } else if (d1 == null && d2 != null) { return -1; } else if (d1 != null) { return 1; } else { return 0; } } private ComparableUtils(); static int safeCompare(Comparable<T> d1, T d2); @SafeVarargs static T minimum(T... values); } |
@Test public void safeCompare_BothNull_ReturnsZero() { assertThat(ComparableUtils.safeCompare(null, null), equalTo(0)); } | 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; } } | ComparableUtils { public static <T> int safeCompare(Comparable<T> d1, T d2) { if (d1 != null && d2 != null) { return d1.compareTo(d2); } else if (d1 == null && d2 != null) { return -1; } else if (d1 != null) { return 1; } else { return 0; } } } | ComparableUtils { public static <T> int safeCompare(Comparable<T> d1, T d2) { if (d1 != null && d2 != null) { return d1.compareTo(d2); } else if (d1 == null && d2 != null) { return -1; } else if (d1 != null) { return 1; } else { return 0; } } private ComparableUtils(); } | ComparableUtils { public static <T> int safeCompare(Comparable<T> d1, T d2) { if (d1 != null && d2 != null) { return d1.compareTo(d2); } else if (d1 == null && d2 != null) { return -1; } else if (d1 != null) { return 1; } else { return 0; } } private ComparableUtils(); static int safeCompare(Comparable<T> d1, T d2); @SafeVarargs static T minimum(T... values); } | ComparableUtils { public static <T> int safeCompare(Comparable<T> d1, T d2) { if (d1 != null && d2 != null) { return d1.compareTo(d2); } else if (d1 == null && d2 != null) { return -1; } else if (d1 != null) { return 1; } else { return 0; } } private ComparableUtils(); static int safeCompare(Comparable<T> d1, T d2); @SafeVarargs static T minimum(T... values); } |
@Test public void safeCompare_FirstLarger_ReturnsPositive() { assertThat(ComparableUtils.safeCompare(7.0, 6.0), greaterThan(0)); } | 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; } } | ComparableUtils { public static <T> int safeCompare(Comparable<T> d1, T d2) { if (d1 != null && d2 != null) { return d1.compareTo(d2); } else if (d1 == null && d2 != null) { return -1; } else if (d1 != null) { return 1; } else { return 0; } } } | ComparableUtils { public static <T> int safeCompare(Comparable<T> d1, T d2) { if (d1 != null && d2 != null) { return d1.compareTo(d2); } else if (d1 == null && d2 != null) { return -1; } else if (d1 != null) { return 1; } else { return 0; } } private ComparableUtils(); } | ComparableUtils { public static <T> int safeCompare(Comparable<T> d1, T d2) { if (d1 != null && d2 != null) { return d1.compareTo(d2); } else if (d1 == null && d2 != null) { return -1; } else if (d1 != null) { return 1; } else { return 0; } } private ComparableUtils(); static int safeCompare(Comparable<T> d1, T d2); @SafeVarargs static T minimum(T... values); } | ComparableUtils { public static <T> int safeCompare(Comparable<T> d1, T d2) { if (d1 != null && d2 != null) { return d1.compareTo(d2); } else if (d1 == null && d2 != null) { return -1; } else if (d1 != null) { return 1; } else { return 0; } } private ComparableUtils(); static int safeCompare(Comparable<T> d1, T d2); @SafeVarargs static T minimum(T... values); } |
@Test public void safeCompare_SecondLarger_ReturnsNegative() { assertThat(ComparableUtils.safeCompare(6.0, 7.0), lessThan(0)); } | 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; } } | ComparableUtils { public static <T> int safeCompare(Comparable<T> d1, T d2) { if (d1 != null && d2 != null) { return d1.compareTo(d2); } else if (d1 == null && d2 != null) { return -1; } else if (d1 != null) { return 1; } else { return 0; } } } | ComparableUtils { public static <T> int safeCompare(Comparable<T> d1, T d2) { if (d1 != null && d2 != null) { return d1.compareTo(d2); } else if (d1 == null && d2 != null) { return -1; } else if (d1 != null) { return 1; } else { return 0; } } private ComparableUtils(); } | ComparableUtils { public static <T> int safeCompare(Comparable<T> d1, T d2) { if (d1 != null && d2 != null) { return d1.compareTo(d2); } else if (d1 == null && d2 != null) { return -1; } else if (d1 != null) { return 1; } else { return 0; } } private ComparableUtils(); static int safeCompare(Comparable<T> d1, T d2); @SafeVarargs static T minimum(T... values); } | ComparableUtils { public static <T> int safeCompare(Comparable<T> d1, T d2) { if (d1 != null && d2 != null) { return d1.compareTo(d2); } else if (d1 == null && d2 != null) { return -1; } else if (d1 != null) { return 1; } else { return 0; } } private ComparableUtils(); static int safeCompare(Comparable<T> d1, T d2); @SafeVarargs static T minimum(T... values); } |
@Test public void testHex() { { String hex = BinaryUtils.toHex(new byte[] {0}); System.out.println(hex); String hex2 = Base16Lower.encodeAsString(new byte[] {0}); assertEquals(hex, hex2); } { String hex = BinaryUtils.toHex(new byte[] {-1}); System.out.println(hex); String hex2 = Base16Lower.encodeAsString(new byte[] {-1}); assertEquals(hex, hex2); } } | public static String toHex(byte[] data) { return Base16Lower.encodeAsString(data); } | BinaryUtils { public static String toHex(byte[] data) { return Base16Lower.encodeAsString(data); } } | BinaryUtils { public static String toHex(byte[] data) { return Base16Lower.encodeAsString(data); } private BinaryUtils(); } | BinaryUtils { public static String toHex(byte[] data) { return Base16Lower.encodeAsString(data); } private BinaryUtils(); static String toHex(byte[] data); static byte[] fromHex(String hexData); static String toBase64(byte[] data); static byte[] toBase64Bytes(byte[] data); static byte[] fromBase64(String b64Data); static byte[] fromBase64Bytes(byte[] b64Data); static ByteArrayInputStream toStream(ByteBuffer byteBuffer); static byte[] copyAllBytesFrom(ByteBuffer bb); static byte[] copyRemainingBytesFrom(ByteBuffer bb); static byte[] copyBytesFrom(ByteBuffer bb); } | BinaryUtils { public static String toHex(byte[] data) { return Base16Lower.encodeAsString(data); } private BinaryUtils(); static String toHex(byte[] data); static byte[] fromHex(String hexData); static String toBase64(byte[] data); static byte[] toBase64Bytes(byte[] data); static byte[] fromBase64(String b64Data); static byte[] fromBase64Bytes(byte[] b64Data); static ByteArrayInputStream toStream(ByteBuffer byteBuffer); static byte[] copyAllBytesFrom(ByteBuffer bb); static byte[] copyRemainingBytesFrom(ByteBuffer bb); static byte[] copyBytesFrom(ByteBuffer bb); } |
@Test public void testCopyRemainingBytesFrom_nullBuffer() { assertThat(BinaryUtils.copyRemainingBytesFrom(null)).isNull(); } | 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; } | BinaryUtils { public static byte[] copyRemainingBytesFrom(ByteBuffer bb) { if (bb == null) { return null; } if (!bb.hasRemaining()) { return EMPTY_BYTE_ARRAY; } if (bb.hasArray()) { int endIdx = bb.arrayOffset() + bb.limit(); int startIdx = endIdx - bb.remaining(); return Arrays.copyOfRange(bb.array(), startIdx, endIdx); } ByteBuffer copy = bb.asReadOnlyBuffer(); byte[] dst = new byte[copy.remaining()]; copy.get(dst); return dst; } } | BinaryUtils { public static byte[] copyRemainingBytesFrom(ByteBuffer bb) { if (bb == null) { return null; } if (!bb.hasRemaining()) { return EMPTY_BYTE_ARRAY; } if (bb.hasArray()) { int endIdx = bb.arrayOffset() + bb.limit(); int startIdx = endIdx - bb.remaining(); return Arrays.copyOfRange(bb.array(), startIdx, endIdx); } ByteBuffer copy = bb.asReadOnlyBuffer(); byte[] dst = new byte[copy.remaining()]; copy.get(dst); return dst; } private BinaryUtils(); } | BinaryUtils { public static byte[] copyRemainingBytesFrom(ByteBuffer bb) { if (bb == null) { return null; } if (!bb.hasRemaining()) { return EMPTY_BYTE_ARRAY; } if (bb.hasArray()) { int endIdx = bb.arrayOffset() + bb.limit(); int startIdx = endIdx - bb.remaining(); return Arrays.copyOfRange(bb.array(), startIdx, endIdx); } ByteBuffer copy = bb.asReadOnlyBuffer(); byte[] dst = new byte[copy.remaining()]; copy.get(dst); return dst; } private BinaryUtils(); static String toHex(byte[] data); static byte[] fromHex(String hexData); static String toBase64(byte[] data); static byte[] toBase64Bytes(byte[] data); static byte[] fromBase64(String b64Data); static byte[] fromBase64Bytes(byte[] b64Data); static ByteArrayInputStream toStream(ByteBuffer byteBuffer); static byte[] copyAllBytesFrom(ByteBuffer bb); static byte[] copyRemainingBytesFrom(ByteBuffer bb); static byte[] copyBytesFrom(ByteBuffer bb); } | BinaryUtils { public static byte[] copyRemainingBytesFrom(ByteBuffer bb) { if (bb == null) { return null; } if (!bb.hasRemaining()) { return EMPTY_BYTE_ARRAY; } if (bb.hasArray()) { int endIdx = bb.arrayOffset() + bb.limit(); int startIdx = endIdx - bb.remaining(); return Arrays.copyOfRange(bb.array(), startIdx, endIdx); } ByteBuffer copy = bb.asReadOnlyBuffer(); byte[] dst = new byte[copy.remaining()]; copy.get(dst); return dst; } private BinaryUtils(); static String toHex(byte[] data); static byte[] fromHex(String hexData); static String toBase64(byte[] data); static byte[] toBase64Bytes(byte[] data); static byte[] fromBase64(String b64Data); static byte[] fromBase64Bytes(byte[] b64Data); static ByteArrayInputStream toStream(ByteBuffer byteBuffer); static byte[] copyAllBytesFrom(ByteBuffer bb); static byte[] copyRemainingBytesFrom(ByteBuffer bb); static byte[] copyBytesFrom(ByteBuffer bb); } |
@Test public void testCopyRemainingBytesFrom_noRemainingBytes() { ByteBuffer bb = ByteBuffer.allocate(1); bb.put(new byte[]{1}); bb.flip(); bb.get(); assertThat(BinaryUtils.copyRemainingBytesFrom(bb)).hasSize(0); } | 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; } | BinaryUtils { public static byte[] copyRemainingBytesFrom(ByteBuffer bb) { if (bb == null) { return null; } if (!bb.hasRemaining()) { return EMPTY_BYTE_ARRAY; } if (bb.hasArray()) { int endIdx = bb.arrayOffset() + bb.limit(); int startIdx = endIdx - bb.remaining(); return Arrays.copyOfRange(bb.array(), startIdx, endIdx); } ByteBuffer copy = bb.asReadOnlyBuffer(); byte[] dst = new byte[copy.remaining()]; copy.get(dst); return dst; } } | BinaryUtils { public static byte[] copyRemainingBytesFrom(ByteBuffer bb) { if (bb == null) { return null; } if (!bb.hasRemaining()) { return EMPTY_BYTE_ARRAY; } if (bb.hasArray()) { int endIdx = bb.arrayOffset() + bb.limit(); int startIdx = endIdx - bb.remaining(); return Arrays.copyOfRange(bb.array(), startIdx, endIdx); } ByteBuffer copy = bb.asReadOnlyBuffer(); byte[] dst = new byte[copy.remaining()]; copy.get(dst); return dst; } private BinaryUtils(); } | BinaryUtils { public static byte[] copyRemainingBytesFrom(ByteBuffer bb) { if (bb == null) { return null; } if (!bb.hasRemaining()) { return EMPTY_BYTE_ARRAY; } if (bb.hasArray()) { int endIdx = bb.arrayOffset() + bb.limit(); int startIdx = endIdx - bb.remaining(); return Arrays.copyOfRange(bb.array(), startIdx, endIdx); } ByteBuffer copy = bb.asReadOnlyBuffer(); byte[] dst = new byte[copy.remaining()]; copy.get(dst); return dst; } private BinaryUtils(); static String toHex(byte[] data); static byte[] fromHex(String hexData); static String toBase64(byte[] data); static byte[] toBase64Bytes(byte[] data); static byte[] fromBase64(String b64Data); static byte[] fromBase64Bytes(byte[] b64Data); static ByteArrayInputStream toStream(ByteBuffer byteBuffer); static byte[] copyAllBytesFrom(ByteBuffer bb); static byte[] copyRemainingBytesFrom(ByteBuffer bb); static byte[] copyBytesFrom(ByteBuffer bb); } | BinaryUtils { public static byte[] copyRemainingBytesFrom(ByteBuffer bb) { if (bb == null) { return null; } if (!bb.hasRemaining()) { return EMPTY_BYTE_ARRAY; } if (bb.hasArray()) { int endIdx = bb.arrayOffset() + bb.limit(); int startIdx = endIdx - bb.remaining(); return Arrays.copyOfRange(bb.array(), startIdx, endIdx); } ByteBuffer copy = bb.asReadOnlyBuffer(); byte[] dst = new byte[copy.remaining()]; copy.get(dst); return dst; } private BinaryUtils(); static String toHex(byte[] data); static byte[] fromHex(String hexData); static String toBase64(byte[] data); static byte[] toBase64Bytes(byte[] data); static byte[] fromBase64(String b64Data); static byte[] fromBase64Bytes(byte[] b64Data); static ByteArrayInputStream toStream(ByteBuffer byteBuffer); static byte[] copyAllBytesFrom(ByteBuffer bb); static byte[] copyRemainingBytesFrom(ByteBuffer bb); static byte[] copyBytesFrom(ByteBuffer bb); } |
@Test public void testCopyRemainingBytesFrom_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); } | 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; } | BinaryUtils { public static byte[] copyRemainingBytesFrom(ByteBuffer bb) { if (bb == null) { return null; } if (!bb.hasRemaining()) { return EMPTY_BYTE_ARRAY; } if (bb.hasArray()) { int endIdx = bb.arrayOffset() + bb.limit(); int startIdx = endIdx - bb.remaining(); return Arrays.copyOfRange(bb.array(), startIdx, endIdx); } ByteBuffer copy = bb.asReadOnlyBuffer(); byte[] dst = new byte[copy.remaining()]; copy.get(dst); return dst; } } | BinaryUtils { public static byte[] copyRemainingBytesFrom(ByteBuffer bb) { if (bb == null) { return null; } if (!bb.hasRemaining()) { return EMPTY_BYTE_ARRAY; } if (bb.hasArray()) { int endIdx = bb.arrayOffset() + bb.limit(); int startIdx = endIdx - bb.remaining(); return Arrays.copyOfRange(bb.array(), startIdx, endIdx); } ByteBuffer copy = bb.asReadOnlyBuffer(); byte[] dst = new byte[copy.remaining()]; copy.get(dst); return dst; } private BinaryUtils(); } | BinaryUtils { public static byte[] copyRemainingBytesFrom(ByteBuffer bb) { if (bb == null) { return null; } if (!bb.hasRemaining()) { return EMPTY_BYTE_ARRAY; } if (bb.hasArray()) { int endIdx = bb.arrayOffset() + bb.limit(); int startIdx = endIdx - bb.remaining(); return Arrays.copyOfRange(bb.array(), startIdx, endIdx); } ByteBuffer copy = bb.asReadOnlyBuffer(); byte[] dst = new byte[copy.remaining()]; copy.get(dst); return dst; } private BinaryUtils(); static String toHex(byte[] data); static byte[] fromHex(String hexData); static String toBase64(byte[] data); static byte[] toBase64Bytes(byte[] data); static byte[] fromBase64(String b64Data); static byte[] fromBase64Bytes(byte[] b64Data); static ByteArrayInputStream toStream(ByteBuffer byteBuffer); static byte[] copyAllBytesFrom(ByteBuffer bb); static byte[] copyRemainingBytesFrom(ByteBuffer bb); static byte[] copyBytesFrom(ByteBuffer bb); } | BinaryUtils { public static byte[] copyRemainingBytesFrom(ByteBuffer bb) { if (bb == null) { return null; } if (!bb.hasRemaining()) { return EMPTY_BYTE_ARRAY; } if (bb.hasArray()) { int endIdx = bb.arrayOffset() + bb.limit(); int startIdx = endIdx - bb.remaining(); return Arrays.copyOfRange(bb.array(), startIdx, endIdx); } ByteBuffer copy = bb.asReadOnlyBuffer(); byte[] dst = new byte[copy.remaining()]; copy.get(dst); return dst; } private BinaryUtils(); static String toHex(byte[] data); static byte[] fromHex(String hexData); static String toBase64(byte[] data); static byte[] toBase64Bytes(byte[] data); static byte[] fromBase64(String b64Data); static byte[] fromBase64Bytes(byte[] b64Data); static ByteArrayInputStream toStream(ByteBuffer byteBuffer); static byte[] copyAllBytesFrom(ByteBuffer bb); static byte[] copyRemainingBytesFrom(ByteBuffer bb); static byte[] copyBytesFrom(ByteBuffer bb); } |
@Test public void testCopyRemainingBytesFrom_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); } | 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; } | BinaryUtils { public static byte[] copyRemainingBytesFrom(ByteBuffer bb) { if (bb == null) { return null; } if (!bb.hasRemaining()) { return EMPTY_BYTE_ARRAY; } if (bb.hasArray()) { int endIdx = bb.arrayOffset() + bb.limit(); int startIdx = endIdx - bb.remaining(); return Arrays.copyOfRange(bb.array(), startIdx, endIdx); } ByteBuffer copy = bb.asReadOnlyBuffer(); byte[] dst = new byte[copy.remaining()]; copy.get(dst); return dst; } } | BinaryUtils { public static byte[] copyRemainingBytesFrom(ByteBuffer bb) { if (bb == null) { return null; } if (!bb.hasRemaining()) { return EMPTY_BYTE_ARRAY; } if (bb.hasArray()) { int endIdx = bb.arrayOffset() + bb.limit(); int startIdx = endIdx - bb.remaining(); return Arrays.copyOfRange(bb.array(), startIdx, endIdx); } ByteBuffer copy = bb.asReadOnlyBuffer(); byte[] dst = new byte[copy.remaining()]; copy.get(dst); return dst; } private BinaryUtils(); } | BinaryUtils { public static byte[] copyRemainingBytesFrom(ByteBuffer bb) { if (bb == null) { return null; } if (!bb.hasRemaining()) { return EMPTY_BYTE_ARRAY; } if (bb.hasArray()) { int endIdx = bb.arrayOffset() + bb.limit(); int startIdx = endIdx - bb.remaining(); return Arrays.copyOfRange(bb.array(), startIdx, endIdx); } ByteBuffer copy = bb.asReadOnlyBuffer(); byte[] dst = new byte[copy.remaining()]; copy.get(dst); return dst; } private BinaryUtils(); static String toHex(byte[] data); static byte[] fromHex(String hexData); static String toBase64(byte[] data); static byte[] toBase64Bytes(byte[] data); static byte[] fromBase64(String b64Data); static byte[] fromBase64Bytes(byte[] b64Data); static ByteArrayInputStream toStream(ByteBuffer byteBuffer); static byte[] copyAllBytesFrom(ByteBuffer bb); static byte[] copyRemainingBytesFrom(ByteBuffer bb); static byte[] copyBytesFrom(ByteBuffer bb); } | BinaryUtils { public static byte[] copyRemainingBytesFrom(ByteBuffer bb) { if (bb == null) { return null; } if (!bb.hasRemaining()) { return EMPTY_BYTE_ARRAY; } if (bb.hasArray()) { int endIdx = bb.arrayOffset() + bb.limit(); int startIdx = endIdx - bb.remaining(); return Arrays.copyOfRange(bb.array(), startIdx, endIdx); } ByteBuffer copy = bb.asReadOnlyBuffer(); byte[] dst = new byte[copy.remaining()]; copy.get(dst); return dst; } private BinaryUtils(); static String toHex(byte[] data); static byte[] fromHex(String hexData); static String toBase64(byte[] data); static byte[] toBase64Bytes(byte[] data); static byte[] fromBase64(String b64Data); static byte[] fromBase64Bytes(byte[] b64Data); static ByteArrayInputStream toStream(ByteBuffer byteBuffer); static byte[] copyAllBytesFrom(ByteBuffer bb); static byte[] copyRemainingBytesFrom(ByteBuffer bb); static byte[] copyBytesFrom(ByteBuffer bb); } |
@Test public void modifyAsyncHttpContent_putObjectRequest_checksumDisabled_shouldNotModify() { ExecutionAttributes executionAttributes = getExecutionAttributesWithChecksumDisabled(); Context.ModifyHttpRequest modifyHttpRequest = InterceptorTestUtils.modifyHttpRequestContext(GetObjectRequest.builder().build()); Optional<AsyncRequestBody> asyncRequestBody = interceptor.modifyAsyncHttpContent(modifyHttpRequest, executionAttributes); assertThat(asyncRequestBody).isEqualTo(modifyHttpRequest.asyncRequestBody()); } | @Override public Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { boolean shouldRecordChecksum = shouldRecordChecksum(context.request(), ASYNC, executionAttributes, context.httpRequest()); if (shouldRecordChecksum && context.asyncRequestBody().isPresent()) { SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(ASYNC_RECORDING_CHECKSUM, true); executionAttributes.putAttribute(CHECKSUM, checksum); return Optional.of(new ChecksumCalculatingAsyncRequestBody(context.asyncRequestBody().get(), checksum)); } return context.asyncRequestBody(); } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { boolean shouldRecordChecksum = shouldRecordChecksum(context.request(), ASYNC, executionAttributes, context.httpRequest()); if (shouldRecordChecksum && context.asyncRequestBody().isPresent()) { SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(ASYNC_RECORDING_CHECKSUM, true); executionAttributes.putAttribute(CHECKSUM, checksum); return Optional.of(new ChecksumCalculatingAsyncRequestBody(context.asyncRequestBody().get(), checksum)); } return context.asyncRequestBody(); } } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { boolean shouldRecordChecksum = shouldRecordChecksum(context.request(), ASYNC, executionAttributes, context.httpRequest()); if (shouldRecordChecksum && context.asyncRequestBody().isPresent()) { SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(ASYNC_RECORDING_CHECKSUM, true); executionAttributes.putAttribute(CHECKSUM, checksum); return Optional.of(new ChecksumCalculatingAsyncRequestBody(context.asyncRequestBody().get(), checksum)); } return context.asyncRequestBody(); } } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { boolean shouldRecordChecksum = shouldRecordChecksum(context.request(), ASYNC, executionAttributes, context.httpRequest()); if (shouldRecordChecksum && context.asyncRequestBody().isPresent()) { SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(ASYNC_RECORDING_CHECKSUM, true); executionAttributes.putAttribute(CHECKSUM, checksum); return Optional.of(new ChecksumCalculatingAsyncRequestBody(context.asyncRequestBody().get(), checksum)); } return context.asyncRequestBody(); } @Override Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { boolean shouldRecordChecksum = shouldRecordChecksum(context.request(), ASYNC, executionAttributes, context.httpRequest()); if (shouldRecordChecksum && context.asyncRequestBody().isPresent()) { SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(ASYNC_RECORDING_CHECKSUM, true); executionAttributes.putAttribute(CHECKSUM, checksum); return Optional.of(new ChecksumCalculatingAsyncRequestBody(context.asyncRequestBody().get(), checksum)); } return context.asyncRequestBody(); } @Override Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); } |
@Test public void nullIsNotCached() { Mockito.when(mockDelegate.get()).thenReturn(null); lazy.getValue(); lazy.getValue(); Mockito.verify(mockDelegate, times(2)).get(); } | public T getValue() { T result = value; if (result == null) { synchronized (this) { result = value; if (result == null) { result = initializer.get(); value = result; } } } return result; } | Lazy { public T getValue() { T result = value; if (result == null) { synchronized (this) { result = value; if (result == null) { result = initializer.get(); value = result; } } } return result; } } | Lazy { public T getValue() { T result = value; if (result == null) { synchronized (this) { result = value; if (result == null) { result = initializer.get(); value = result; } } } return result; } Lazy(Supplier<T> initializer); } | Lazy { public T getValue() { T result = value; if (result == null) { synchronized (this) { result = value; if (result == null) { result = initializer.get(); value = result; } } } return result; } Lazy(Supplier<T> initializer); T getValue(); @Override String toString(); } | Lazy { public T getValue() { T result = value; if (result == null) { synchronized (this) { result = value; if (result == null) { result = initializer.get(); value = result; } } } return result; } Lazy(Supplier<T> initializer); T getValue(); @Override String toString(); } |
@Test(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(); } } | public T getValue() { T result = value; if (result == null) { synchronized (this) { result = value; if (result == null) { result = initializer.get(); value = result; } } } return result; } | Lazy { public T getValue() { T result = value; if (result == null) { synchronized (this) { result = value; if (result == null) { result = initializer.get(); value = result; } } } return result; } } | Lazy { public T getValue() { T result = value; if (result == null) { synchronized (this) { result = value; if (result == null) { result = initializer.get(); value = result; } } } return result; } Lazy(Supplier<T> initializer); } | Lazy { public T getValue() { T result = value; if (result == null) { synchronized (this) { result = value; if (result == null) { result = initializer.get(); value = result; } } } return result; } Lazy(Supplier<T> initializer); T getValue(); @Override String toString(); } | Lazy { public T getValue() { T result = value; if (result == null) { synchronized (this) { result = value; if (result == null) { result = initializer.get(); value = result; } } } return result; } Lazy(Supplier<T> initializer); T getValue(); @Override String toString(); } |
@Test(expected = IllegalArgumentException.class) public void putAll_ThrowsRuntimeExceptionWhenTypesMismatched() { Map<AttributeMap.Key<?>, Object> attributes = new HashMap<>(); attributes.put(STRING_KEY, 42); AttributeMap.builder() .putAll(attributes) .build(); } | public static Builder builder() { return new Builder(); } | AttributeMap implements ToCopyableBuilder<AttributeMap.Builder, AttributeMap>, SdkAutoCloseable { public static Builder builder() { return new Builder(); } } | AttributeMap implements ToCopyableBuilder<AttributeMap.Builder, AttributeMap>, SdkAutoCloseable { public static Builder builder() { return new Builder(); } private AttributeMap(Map<? extends Key<?>, ?> attributes); } | AttributeMap implements ToCopyableBuilder<AttributeMap.Builder, AttributeMap>, SdkAutoCloseable { public static Builder builder() { return new Builder(); } private AttributeMap(Map<? extends Key<?>, ?> attributes); boolean containsKey(Key<T> typedKey); T get(Key<T> key); AttributeMap merge(AttributeMap lowerPrecedence); static AttributeMap empty(); AttributeMap copy(); @Override void close(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); @Override Builder toBuilder(); static Builder builder(); } | AttributeMap implements ToCopyableBuilder<AttributeMap.Builder, AttributeMap>, SdkAutoCloseable { public static Builder builder() { return new Builder(); } private AttributeMap(Map<? extends Key<?>, ?> attributes); boolean containsKey(Key<T> typedKey); T get(Key<T> key); AttributeMap merge(AttributeMap lowerPrecedence); static AttributeMap empty(); AttributeMap copy(); @Override void close(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); @Override Builder toBuilder(); static Builder builder(); } |
@Test public void isEmpty_NullCollection_ReturnsTrue() { assertTrue(CollectionUtils.isNullOrEmpty((Collection<?>) null)); } | public static boolean isNullOrEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } | CollectionUtils { public static boolean isNullOrEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } } | CollectionUtils { public static boolean isNullOrEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } private CollectionUtils(); } | CollectionUtils { public static boolean isNullOrEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } private CollectionUtils(); static boolean isNullOrEmpty(Collection<?> collection); static boolean isNullOrEmpty(Map<?, ?> map); static List<T> mergeLists(List<T> list1, List<T> list2); static T firstIfPresent(List<T> list); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map, Supplier<Map<T, List<U>>> mapConstructor); static Map<T, List<U>> unmodifiableMapOfLists(Map<T, List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map,
Supplier<Map<T, List<U>>> mapConstructor); static Collector<Map.Entry<K, V>, ?, Map<K, V>> toMap(); static Map<K, VOutT> mapValues(Map<K, VInT> inputMap, Function<VInT, VOutT> mapper); } | CollectionUtils { public static boolean isNullOrEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } private CollectionUtils(); static boolean isNullOrEmpty(Collection<?> collection); static boolean isNullOrEmpty(Map<?, ?> map); static List<T> mergeLists(List<T> list1, List<T> list2); static T firstIfPresent(List<T> list); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map, Supplier<Map<T, List<U>>> mapConstructor); static Map<T, List<U>> unmodifiableMapOfLists(Map<T, List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map,
Supplier<Map<T, List<U>>> mapConstructor); static Collector<Map.Entry<K, V>, ?, Map<K, V>> toMap(); static Map<K, VOutT> mapValues(Map<K, VInT> inputMap, Function<VInT, VOutT> mapper); } |
@Test public void isEmpty_EmptyCollection_ReturnsTrue() { assertTrue(CollectionUtils.isNullOrEmpty(Collections.emptyList())); } | public static boolean isNullOrEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } | CollectionUtils { public static boolean isNullOrEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } } | CollectionUtils { public static boolean isNullOrEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } private CollectionUtils(); } | CollectionUtils { public static boolean isNullOrEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } private CollectionUtils(); static boolean isNullOrEmpty(Collection<?> collection); static boolean isNullOrEmpty(Map<?, ?> map); static List<T> mergeLists(List<T> list1, List<T> list2); static T firstIfPresent(List<T> list); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map, Supplier<Map<T, List<U>>> mapConstructor); static Map<T, List<U>> unmodifiableMapOfLists(Map<T, List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map,
Supplier<Map<T, List<U>>> mapConstructor); static Collector<Map.Entry<K, V>, ?, Map<K, V>> toMap(); static Map<K, VOutT> mapValues(Map<K, VInT> inputMap, Function<VInT, VOutT> mapper); } | CollectionUtils { public static boolean isNullOrEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } private CollectionUtils(); static boolean isNullOrEmpty(Collection<?> collection); static boolean isNullOrEmpty(Map<?, ?> map); static List<T> mergeLists(List<T> list1, List<T> list2); static T firstIfPresent(List<T> list); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map, Supplier<Map<T, List<U>>> mapConstructor); static Map<T, List<U>> unmodifiableMapOfLists(Map<T, List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map,
Supplier<Map<T, List<U>>> mapConstructor); static Collector<Map.Entry<K, V>, ?, Map<K, V>> toMap(); static Map<K, VOutT> mapValues(Map<K, VInT> inputMap, Function<VInT, VOutT> mapper); } |
@Test public void isEmpty_NonEmptyCollection_ReturnsFalse() { assertFalse(CollectionUtils.isNullOrEmpty(Arrays.asList("something"))); } | public static boolean isNullOrEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } | CollectionUtils { public static boolean isNullOrEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } } | CollectionUtils { public static boolean isNullOrEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } private CollectionUtils(); } | CollectionUtils { public static boolean isNullOrEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } private CollectionUtils(); static boolean isNullOrEmpty(Collection<?> collection); static boolean isNullOrEmpty(Map<?, ?> map); static List<T> mergeLists(List<T> list1, List<T> list2); static T firstIfPresent(List<T> list); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map, Supplier<Map<T, List<U>>> mapConstructor); static Map<T, List<U>> unmodifiableMapOfLists(Map<T, List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map,
Supplier<Map<T, List<U>>> mapConstructor); static Collector<Map.Entry<K, V>, ?, Map<K, V>> toMap(); static Map<K, VOutT> mapValues(Map<K, VInT> inputMap, Function<VInT, VOutT> mapper); } | CollectionUtils { public static boolean isNullOrEmpty(Collection<?> collection) { return collection == null || collection.isEmpty(); } private CollectionUtils(); static boolean isNullOrEmpty(Collection<?> collection); static boolean isNullOrEmpty(Map<?, ?> map); static List<T> mergeLists(List<T> list1, List<T> list2); static T firstIfPresent(List<T> list); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map, Supplier<Map<T, List<U>>> mapConstructor); static Map<T, List<U>> unmodifiableMapOfLists(Map<T, List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map,
Supplier<Map<T, List<U>>> mapConstructor); static Collector<Map.Entry<K, V>, ?, Map<K, V>> toMap(); static Map<K, VOutT> mapValues(Map<K, VInT> inputMap, Function<VInT, VOutT> mapper); } |
@Test public void firstIfPresent_NullList_ReturnsNull() { List<String> list = null; assertThat(CollectionUtils.firstIfPresent(list)).isNull(); } | public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } | CollectionUtils { public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } } | CollectionUtils { public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } private CollectionUtils(); } | CollectionUtils { public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } private CollectionUtils(); static boolean isNullOrEmpty(Collection<?> collection); static boolean isNullOrEmpty(Map<?, ?> map); static List<T> mergeLists(List<T> list1, List<T> list2); static T firstIfPresent(List<T> list); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map, Supplier<Map<T, List<U>>> mapConstructor); static Map<T, List<U>> unmodifiableMapOfLists(Map<T, List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map,
Supplier<Map<T, List<U>>> mapConstructor); static Collector<Map.Entry<K, V>, ?, Map<K, V>> toMap(); static Map<K, VOutT> mapValues(Map<K, VInT> inputMap, Function<VInT, VOutT> mapper); } | CollectionUtils { public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } private CollectionUtils(); static boolean isNullOrEmpty(Collection<?> collection); static boolean isNullOrEmpty(Map<?, ?> map); static List<T> mergeLists(List<T> list1, List<T> list2); static T firstIfPresent(List<T> list); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map, Supplier<Map<T, List<U>>> mapConstructor); static Map<T, List<U>> unmodifiableMapOfLists(Map<T, List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map,
Supplier<Map<T, List<U>>> mapConstructor); static Collector<Map.Entry<K, V>, ?, Map<K, V>> toMap(); static Map<K, VOutT> mapValues(Map<K, VInT> inputMap, Function<VInT, VOutT> mapper); } |
@Test public void firstIfPresent_EmptyList_ReturnsNull() { List<String> list = Collections.emptyList(); assertThat(CollectionUtils.firstIfPresent(list)).isNull(); } | public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } | CollectionUtils { public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } } | CollectionUtils { public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } private CollectionUtils(); } | CollectionUtils { public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } private CollectionUtils(); static boolean isNullOrEmpty(Collection<?> collection); static boolean isNullOrEmpty(Map<?, ?> map); static List<T> mergeLists(List<T> list1, List<T> list2); static T firstIfPresent(List<T> list); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map, Supplier<Map<T, List<U>>> mapConstructor); static Map<T, List<U>> unmodifiableMapOfLists(Map<T, List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map,
Supplier<Map<T, List<U>>> mapConstructor); static Collector<Map.Entry<K, V>, ?, Map<K, V>> toMap(); static Map<K, VOutT> mapValues(Map<K, VInT> inputMap, Function<VInT, VOutT> mapper); } | CollectionUtils { public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } private CollectionUtils(); static boolean isNullOrEmpty(Collection<?> collection); static boolean isNullOrEmpty(Map<?, ?> map); static List<T> mergeLists(List<T> list1, List<T> list2); static T firstIfPresent(List<T> list); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map, Supplier<Map<T, List<U>>> mapConstructor); static Map<T, List<U>> unmodifiableMapOfLists(Map<T, List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map,
Supplier<Map<T, List<U>>> mapConstructor); static Collector<Map.Entry<K, V>, ?, Map<K, V>> toMap(); static Map<K, VOutT> mapValues(Map<K, VInT> inputMap, Function<VInT, VOutT> mapper); } |
@Test public void firstIfPresent_SingleElementList_ReturnsOnlyElement() { assertThat(CollectionUtils.firstIfPresent(singletonList("foo"))).isEqualTo("foo"); } | public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } | CollectionUtils { public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } } | CollectionUtils { public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } private CollectionUtils(); } | CollectionUtils { public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } private CollectionUtils(); static boolean isNullOrEmpty(Collection<?> collection); static boolean isNullOrEmpty(Map<?, ?> map); static List<T> mergeLists(List<T> list1, List<T> list2); static T firstIfPresent(List<T> list); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map, Supplier<Map<T, List<U>>> mapConstructor); static Map<T, List<U>> unmodifiableMapOfLists(Map<T, List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map,
Supplier<Map<T, List<U>>> mapConstructor); static Collector<Map.Entry<K, V>, ?, Map<K, V>> toMap(); static Map<K, VOutT> mapValues(Map<K, VInT> inputMap, Function<VInT, VOutT> mapper); } | CollectionUtils { public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } private CollectionUtils(); static boolean isNullOrEmpty(Collection<?> collection); static boolean isNullOrEmpty(Map<?, ?> map); static List<T> mergeLists(List<T> list1, List<T> list2); static T firstIfPresent(List<T> list); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map, Supplier<Map<T, List<U>>> mapConstructor); static Map<T, List<U>> unmodifiableMapOfLists(Map<T, List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map,
Supplier<Map<T, List<U>>> mapConstructor); static Collector<Map.Entry<K, V>, ?, Map<K, V>> toMap(); static Map<K, VOutT> mapValues(Map<K, VInT> inputMap, Function<VInT, VOutT> mapper); } |
@Test public void firstIfPresent_MultipleElementList_ReturnsFirstElement() { assertThat(CollectionUtils.firstIfPresent(Arrays.asList("foo", "bar", "baz"))).isEqualTo("foo"); } | public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } | CollectionUtils { public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } } | CollectionUtils { public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } private CollectionUtils(); } | CollectionUtils { public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } private CollectionUtils(); static boolean isNullOrEmpty(Collection<?> collection); static boolean isNullOrEmpty(Map<?, ?> map); static List<T> mergeLists(List<T> list1, List<T> list2); static T firstIfPresent(List<T> list); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map, Supplier<Map<T, List<U>>> mapConstructor); static Map<T, List<U>> unmodifiableMapOfLists(Map<T, List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map,
Supplier<Map<T, List<U>>> mapConstructor); static Collector<Map.Entry<K, V>, ?, Map<K, V>> toMap(); static Map<K, VOutT> mapValues(Map<K, VInT> inputMap, Function<VInT, VOutT> mapper); } | CollectionUtils { public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } private CollectionUtils(); static boolean isNullOrEmpty(Collection<?> collection); static boolean isNullOrEmpty(Map<?, ?> map); static List<T> mergeLists(List<T> list1, List<T> list2); static T firstIfPresent(List<T> list); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map, Supplier<Map<T, List<U>>> mapConstructor); static Map<T, List<U>> unmodifiableMapOfLists(Map<T, List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map,
Supplier<Map<T, List<U>>> mapConstructor); static Collector<Map.Entry<K, V>, ?, Map<K, V>> toMap(); static Map<K, VOutT> mapValues(Map<K, VInT> inputMap, Function<VInT, VOutT> mapper); } |
@Test public void modifyAsyncHttpResponseContent_getObjectRequest_checksumEnabled_shouldWrapChecksumValidatingPublisher() { SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader(); Context.ModifyHttpResponse modifyHttpResponse = InterceptorTestUtils.modifyHttpResponse(GetObjectRequest.builder().build(), sdkHttpResponse); Optional<Publisher<ByteBuffer>> publisher = interceptor.modifyAsyncHttpResponseContent(modifyHttpResponse, getExecutionAttributes()); assertThat(publisher.get()).isExactlyInstanceOf(ChecksumValidatingPublisher.class); } | @Override public Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse()) && context.responsePublisher().isPresent()) { long contentLength = context.httpResponse() .firstMatchingHeader(CONTENT_LENGTH_HEADER) .map(Long::parseLong) .orElse(0L); SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(CHECKSUM, checksum); if (contentLength > 0) { return Optional.of(new ChecksumValidatingPublisher(context.responsePublisher().get(), checksum, contentLength)); } } return context.responsePublisher(); } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse()) && context.responsePublisher().isPresent()) { long contentLength = context.httpResponse() .firstMatchingHeader(CONTENT_LENGTH_HEADER) .map(Long::parseLong) .orElse(0L); SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(CHECKSUM, checksum); if (contentLength > 0) { return Optional.of(new ChecksumValidatingPublisher(context.responsePublisher().get(), checksum, contentLength)); } } return context.responsePublisher(); } } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse()) && context.responsePublisher().isPresent()) { long contentLength = context.httpResponse() .firstMatchingHeader(CONTENT_LENGTH_HEADER) .map(Long::parseLong) .orElse(0L); SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(CHECKSUM, checksum); if (contentLength > 0) { return Optional.of(new ChecksumValidatingPublisher(context.responsePublisher().get(), checksum, contentLength)); } } return context.responsePublisher(); } } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse()) && context.responsePublisher().isPresent()) { long contentLength = context.httpResponse() .firstMatchingHeader(CONTENT_LENGTH_HEADER) .map(Long::parseLong) .orElse(0L); SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(CHECKSUM, checksum); if (contentLength > 0) { return Optional.of(new ChecksumValidatingPublisher(context.responsePublisher().get(), checksum, contentLength)); } } return context.responsePublisher(); } @Override Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse()) && context.responsePublisher().isPresent()) { long contentLength = context.httpResponse() .firstMatchingHeader(CONTENT_LENGTH_HEADER) .map(Long::parseLong) .orElse(0L); SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(CHECKSUM, checksum); if (contentLength > 0) { return Optional.of(new ChecksumValidatingPublisher(context.responsePublisher().get(), checksum, contentLength)); } } return context.responsePublisher(); } @Override Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); } |
@Test public void firstIfPresent_FirstElementNull_ReturnsNull() { assertThat(CollectionUtils.firstIfPresent(Arrays.asList(null, "bar", "baz"))).isNull(); } | public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } | CollectionUtils { public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } } | CollectionUtils { public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } private CollectionUtils(); } | CollectionUtils { public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } private CollectionUtils(); static boolean isNullOrEmpty(Collection<?> collection); static boolean isNullOrEmpty(Map<?, ?> map); static List<T> mergeLists(List<T> list1, List<T> list2); static T firstIfPresent(List<T> list); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map, Supplier<Map<T, List<U>>> mapConstructor); static Map<T, List<U>> unmodifiableMapOfLists(Map<T, List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map,
Supplier<Map<T, List<U>>> mapConstructor); static Collector<Map.Entry<K, V>, ?, Map<K, V>> toMap(); static Map<K, VOutT> mapValues(Map<K, VInT> inputMap, Function<VInT, VOutT> mapper); } | CollectionUtils { public static <T> T firstIfPresent(List<T> list) { if (list == null || list.isEmpty()) { return null; } else { return list.get(0); } } private CollectionUtils(); static boolean isNullOrEmpty(Collection<?> collection); static boolean isNullOrEmpty(Map<?, ?> map); static List<T> mergeLists(List<T> list1, List<T> list2); static T firstIfPresent(List<T> list); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepCopyMap(Map<T, ? extends List<U>> map, Supplier<Map<T, List<U>>> mapConstructor); static Map<T, List<U>> unmodifiableMapOfLists(Map<T, List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map); static Map<T, List<U>> deepUnmodifiableMap(Map<T, ? extends List<U>> map,
Supplier<Map<T, List<U>>> mapConstructor); static Collector<Map.Entry<K, V>, ?, Map<K, V>> toMap(); static Map<K, VOutT> mapValues(Map<K, VInT> inputMap, Function<VInT, VOutT> mapper); } |
@Test public void createIsCorrect() { assertThat(ToString.create("Foo")).isEqualTo("Foo()"); } | public static String create(String className) { return className + "()"; } | ToString { public static String create(String className) { return className + "()"; } } | ToString { public static String create(String className) { return className + "()"; } private ToString(String className); } | ToString { public static String create(String className) { return className + "()"; } private ToString(String className); static String create(String className); static ToString builder(String className); ToString add(String fieldName, Object field); String build(); } | ToString { public static String create(String className) { return className + "()"; } private ToString(String className); static String create(String className); static ToString builder(String className); ToString add(String fieldName, Object field); String build(); } |
@Test public void testErrorOnDuplicateKeys() { try { Map<Integer, String> builtMap = new ImmutableMap.Builder<Integer, String>() .put(1, "one") .put(1, "two") .build(); fail("IllegalArgumentException expected."); } catch (IllegalArgumentException iae) { } catch (Exception e) { fail("IllegalArgumentException expected."); } } | public V put(K key, V value) { throw new UnsupportedOperationException(UNMODIFIABLE_MESSAGE); } | ImmutableMap implements Map<K, V> { public V put(K key, V value) { throw new UnsupportedOperationException(UNMODIFIABLE_MESSAGE); } } | ImmutableMap implements Map<K, V> { public V put(K key, V value) { throw new UnsupportedOperationException(UNMODIFIABLE_MESSAGE); } private ImmutableMap(Map<K, V> map); } | ImmutableMap implements Map<K, V> { public V put(K key, V value) { throw new UnsupportedOperationException(UNMODIFIABLE_MESSAGE); } private ImmutableMap(Map<K, V> map); static Builder<K, V> builder(); static ImmutableMap<K, V> of(K k0, V v0); static ImmutableMap<K, V> of(K k0, V v0, K k1, V v1); static ImmutableMap<K, V> of(K k0, V v0, K k1, V v1,
K k2, V v2); static ImmutableMap<K, V> of(K k0, V v0, K k1, V v1,
K k2, V v2, K k3, V v3); static ImmutableMap<K, V> of(K k0, V v0, K k1, V v1,
K k2, V v2, K k3, V v3, K k4, V v4); boolean containsKey(Object key); boolean containsValue(Object value); Set<Entry<K, V>> entrySet(); V get(Object key); boolean isEmpty(); Set<K> keySet(); int size(); Collection<V> values(); void clear(); V put(K key, V value); void putAll(Map<? extends K, ? extends V> map); V remove(Object key); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } | ImmutableMap implements Map<K, V> { public V put(K key, V value) { throw new UnsupportedOperationException(UNMODIFIABLE_MESSAGE); } private ImmutableMap(Map<K, V> map); static Builder<K, V> builder(); static ImmutableMap<K, V> of(K k0, V v0); static ImmutableMap<K, V> of(K k0, V v0, K k1, V v1); static ImmutableMap<K, V> of(K k0, V v0, K k1, V v1,
K k2, V v2); static ImmutableMap<K, V> of(K k0, V v0, K k1, V v1,
K k2, V v2, K k3, V v3); static ImmutableMap<K, V> of(K k0, V v0, K k1, V v1,
K k2, V v2, K k3, V v3, K k4, V v4); boolean containsKey(Object key); boolean containsValue(Object value); Set<Entry<K, V>> entrySet(); V get(Object key); boolean isEmpty(); Set<K> keySet(); int size(); Collection<V> values(); void clear(); V put(K key, V value); void putAll(Map<? extends K, ? extends V> map); V remove(Object key); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); } |
@Test public void poolNumberWrapsAround() { for (int i = 0; i < 9_9999; i++) { new ThreadFactoryBuilder().build(); } Thread threadBeforeWrap = new ThreadFactoryBuilder().build().newThread(this::doNothing); assertThat(threadBeforeWrap.getName()).isEqualTo("aws-java-sdk-9999-0"); Thread threadAfterWrap = new ThreadFactoryBuilder().build().newThread(this::doNothing); assertThat(threadAfterWrap.getName()).isEqualTo("aws-java-sdk-0-0"); } | public ThreadFactory build() { String threadNamePrefixWithPoolNumber = threadNamePrefix + "-" + POOL_NUMBER.getAndIncrement() % POOL_NUMBER_MAX; ThreadFactory result = new NamedThreadFactory(Executors.defaultThreadFactory(), threadNamePrefixWithPoolNumber); if (daemonThreads) { result = new DaemonThreadFactory(result); } return result; } | ThreadFactoryBuilder { public ThreadFactory build() { String threadNamePrefixWithPoolNumber = threadNamePrefix + "-" + POOL_NUMBER.getAndIncrement() % POOL_NUMBER_MAX; ThreadFactory result = new NamedThreadFactory(Executors.defaultThreadFactory(), threadNamePrefixWithPoolNumber); if (daemonThreads) { result = new DaemonThreadFactory(result); } return result; } } | ThreadFactoryBuilder { public ThreadFactory build() { String threadNamePrefixWithPoolNumber = threadNamePrefix + "-" + POOL_NUMBER.getAndIncrement() % POOL_NUMBER_MAX; ThreadFactory result = new NamedThreadFactory(Executors.defaultThreadFactory(), threadNamePrefixWithPoolNumber); if (daemonThreads) { result = new DaemonThreadFactory(result); } return result; } } | ThreadFactoryBuilder { public ThreadFactory build() { String threadNamePrefixWithPoolNumber = threadNamePrefix + "-" + POOL_NUMBER.getAndIncrement() % POOL_NUMBER_MAX; ThreadFactory result = new NamedThreadFactory(Executors.defaultThreadFactory(), threadNamePrefixWithPoolNumber); if (daemonThreads) { result = new DaemonThreadFactory(result); } return result; } ThreadFactoryBuilder threadNamePrefix(String threadNamePrefix); ThreadFactoryBuilder daemonThreads(Boolean daemonThreads); ThreadFactory build(); } | ThreadFactoryBuilder { public ThreadFactory build() { String threadNamePrefixWithPoolNumber = threadNamePrefix + "-" + POOL_NUMBER.getAndIncrement() % POOL_NUMBER_MAX; ThreadFactory result = new NamedThreadFactory(Executors.defaultThreadFactory(), threadNamePrefixWithPoolNumber); if (daemonThreads) { result = new DaemonThreadFactory(result); } return result; } ThreadFactoryBuilder threadNamePrefix(String threadNamePrefix); ThreadFactoryBuilder daemonThreads(Boolean daemonThreads); ThreadFactory build(); } |
@Test public void maximumRequestsIsHonored() { List<PutMetricDataRequest> requests; requests = aggregatorWithUniqueMetricsAdded(MetricCollectionAggregator.MAX_METRIC_DATA_PER_REQUEST).getRequests(); assertThat(requests).hasOnlyOneElementSatisfying(request -> { assertThat(request.metricData()).hasSize(MetricCollectionAggregator.MAX_METRIC_DATA_PER_REQUEST); }); requests = aggregatorWithUniqueMetricsAdded(MetricCollectionAggregator.MAX_METRIC_DATA_PER_REQUEST + 1).getRequests(); assertThat(requests).hasSize(2); assertThat(requests.get(0).metricData()).hasSize(MetricCollectionAggregator.MAX_METRIC_DATA_PER_REQUEST); assertThat(requests.get(1).metricData()).hasSize(1); } | public List<PutMetricDataRequest> getRequests() { List<PutMetricDataRequest> requests = new ArrayList<>(); List<MetricDatum> requestMetricDatums = new ArrayList<>(); ValuesInRequestCounter valuesInRequestCounter = new ValuesInRequestCounter(); Map<Instant, Collection<MetricAggregator>> metrics = timeBucketedMetrics.timeBucketedMetrics(); for (Map.Entry<Instant, Collection<MetricAggregator>> entry : metrics.entrySet()) { Instant timeBucket = entry.getKey(); for (MetricAggregator metric : entry.getValue()) { if (requestMetricDatums.size() >= MAX_METRIC_DATA_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); } metric.ifSummary(summaryAggregator -> requestMetricDatums.add(summaryMetricDatum(timeBucket, summaryAggregator))); metric.ifDetailed(detailedAggregator -> { int startIndex = 0; Collection<DetailedMetrics> detailedMetrics = detailedAggregator.detailedMetrics(); while (startIndex < detailedMetrics.size()) { if (valuesInRequestCounter.get() >= MAX_VALUES_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); valuesInRequestCounter.reset(); } MetricDatum data = detailedMetricDatum(timeBucket, detailedAggregator, startIndex, MAX_VALUES_PER_REQUEST - valuesInRequestCounter.get()); int valuesAdded = data.values().size(); startIndex += valuesAdded; valuesInRequestCounter.add(valuesAdded); requestMetricDatums.add(data); } }); } } if (!requestMetricDatums.isEmpty()) { requests.add(newPutRequest(requestMetricDatums)); } timeBucketedMetrics.reset(); return requests; } | MetricCollectionAggregator { public List<PutMetricDataRequest> getRequests() { List<PutMetricDataRequest> requests = new ArrayList<>(); List<MetricDatum> requestMetricDatums = new ArrayList<>(); ValuesInRequestCounter valuesInRequestCounter = new ValuesInRequestCounter(); Map<Instant, Collection<MetricAggregator>> metrics = timeBucketedMetrics.timeBucketedMetrics(); for (Map.Entry<Instant, Collection<MetricAggregator>> entry : metrics.entrySet()) { Instant timeBucket = entry.getKey(); for (MetricAggregator metric : entry.getValue()) { if (requestMetricDatums.size() >= MAX_METRIC_DATA_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); } metric.ifSummary(summaryAggregator -> requestMetricDatums.add(summaryMetricDatum(timeBucket, summaryAggregator))); metric.ifDetailed(detailedAggregator -> { int startIndex = 0; Collection<DetailedMetrics> detailedMetrics = detailedAggregator.detailedMetrics(); while (startIndex < detailedMetrics.size()) { if (valuesInRequestCounter.get() >= MAX_VALUES_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); valuesInRequestCounter.reset(); } MetricDatum data = detailedMetricDatum(timeBucket, detailedAggregator, startIndex, MAX_VALUES_PER_REQUEST - valuesInRequestCounter.get()); int valuesAdded = data.values().size(); startIndex += valuesAdded; valuesInRequestCounter.add(valuesAdded); requestMetricDatums.add(data); } }); } } if (!requestMetricDatums.isEmpty()) { requests.add(newPutRequest(requestMetricDatums)); } timeBucketedMetrics.reset(); return requests; } } | MetricCollectionAggregator { public List<PutMetricDataRequest> getRequests() { List<PutMetricDataRequest> requests = new ArrayList<>(); List<MetricDatum> requestMetricDatums = new ArrayList<>(); ValuesInRequestCounter valuesInRequestCounter = new ValuesInRequestCounter(); Map<Instant, Collection<MetricAggregator>> metrics = timeBucketedMetrics.timeBucketedMetrics(); for (Map.Entry<Instant, Collection<MetricAggregator>> entry : metrics.entrySet()) { Instant timeBucket = entry.getKey(); for (MetricAggregator metric : entry.getValue()) { if (requestMetricDatums.size() >= MAX_METRIC_DATA_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); } metric.ifSummary(summaryAggregator -> requestMetricDatums.add(summaryMetricDatum(timeBucket, summaryAggregator))); metric.ifDetailed(detailedAggregator -> { int startIndex = 0; Collection<DetailedMetrics> detailedMetrics = detailedAggregator.detailedMetrics(); while (startIndex < detailedMetrics.size()) { if (valuesInRequestCounter.get() >= MAX_VALUES_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); valuesInRequestCounter.reset(); } MetricDatum data = detailedMetricDatum(timeBucket, detailedAggregator, startIndex, MAX_VALUES_PER_REQUEST - valuesInRequestCounter.get()); int valuesAdded = data.values().size(); startIndex += valuesAdded; valuesInRequestCounter.add(valuesAdded); requestMetricDatums.add(data); } }); } } if (!requestMetricDatums.isEmpty()) { requests.add(newPutRequest(requestMetricDatums)); } timeBucketedMetrics.reset(); return requests; } MetricCollectionAggregator(String namespace,
Set<SdkMetric<String>> dimensions,
Set<MetricCategory> metricCategories,
MetricLevel metricLevel,
Set<SdkMetric<?>> detailedMetrics); } | MetricCollectionAggregator { public List<PutMetricDataRequest> getRequests() { List<PutMetricDataRequest> requests = new ArrayList<>(); List<MetricDatum> requestMetricDatums = new ArrayList<>(); ValuesInRequestCounter valuesInRequestCounter = new ValuesInRequestCounter(); Map<Instant, Collection<MetricAggregator>> metrics = timeBucketedMetrics.timeBucketedMetrics(); for (Map.Entry<Instant, Collection<MetricAggregator>> entry : metrics.entrySet()) { Instant timeBucket = entry.getKey(); for (MetricAggregator metric : entry.getValue()) { if (requestMetricDatums.size() >= MAX_METRIC_DATA_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); } metric.ifSummary(summaryAggregator -> requestMetricDatums.add(summaryMetricDatum(timeBucket, summaryAggregator))); metric.ifDetailed(detailedAggregator -> { int startIndex = 0; Collection<DetailedMetrics> detailedMetrics = detailedAggregator.detailedMetrics(); while (startIndex < detailedMetrics.size()) { if (valuesInRequestCounter.get() >= MAX_VALUES_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); valuesInRequestCounter.reset(); } MetricDatum data = detailedMetricDatum(timeBucket, detailedAggregator, startIndex, MAX_VALUES_PER_REQUEST - valuesInRequestCounter.get()); int valuesAdded = data.values().size(); startIndex += valuesAdded; valuesInRequestCounter.add(valuesAdded); requestMetricDatums.add(data); } }); } } if (!requestMetricDatums.isEmpty()) { requests.add(newPutRequest(requestMetricDatums)); } timeBucketedMetrics.reset(); return requests; } MetricCollectionAggregator(String namespace,
Set<SdkMetric<String>> dimensions,
Set<MetricCategory> metricCategories,
MetricLevel metricLevel,
Set<SdkMetric<?>> detailedMetrics); void addCollection(MetricCollection collection); List<PutMetricDataRequest> getRequests(); } | MetricCollectionAggregator { public List<PutMetricDataRequest> getRequests() { List<PutMetricDataRequest> requests = new ArrayList<>(); List<MetricDatum> requestMetricDatums = new ArrayList<>(); ValuesInRequestCounter valuesInRequestCounter = new ValuesInRequestCounter(); Map<Instant, Collection<MetricAggregator>> metrics = timeBucketedMetrics.timeBucketedMetrics(); for (Map.Entry<Instant, Collection<MetricAggregator>> entry : metrics.entrySet()) { Instant timeBucket = entry.getKey(); for (MetricAggregator metric : entry.getValue()) { if (requestMetricDatums.size() >= MAX_METRIC_DATA_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); } metric.ifSummary(summaryAggregator -> requestMetricDatums.add(summaryMetricDatum(timeBucket, summaryAggregator))); metric.ifDetailed(detailedAggregator -> { int startIndex = 0; Collection<DetailedMetrics> detailedMetrics = detailedAggregator.detailedMetrics(); while (startIndex < detailedMetrics.size()) { if (valuesInRequestCounter.get() >= MAX_VALUES_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); valuesInRequestCounter.reset(); } MetricDatum data = detailedMetricDatum(timeBucket, detailedAggregator, startIndex, MAX_VALUES_PER_REQUEST - valuesInRequestCounter.get()); int valuesAdded = data.values().size(); startIndex += valuesAdded; valuesInRequestCounter.add(valuesAdded); requestMetricDatums.add(data); } }); } } if (!requestMetricDatums.isEmpty()) { requests.add(newPutRequest(requestMetricDatums)); } timeBucketedMetrics.reset(); return requests; } MetricCollectionAggregator(String namespace,
Set<SdkMetric<String>> dimensions,
Set<MetricCategory> metricCategories,
MetricLevel metricLevel,
Set<SdkMetric<?>> detailedMetrics); void addCollection(MetricCollection collection); List<PutMetricDataRequest> getRequests(); static final int MAX_METRIC_DATA_PER_REQUEST; static final int MAX_VALUES_PER_REQUEST; } |
@Test public void maximumMetricValuesIsHonored() { List<PutMetricDataRequest> requests; requests = aggregatorWithUniqueValuesAdded(HttpMetric.MAX_CONCURRENCY, MetricCollectionAggregator.MAX_VALUES_PER_REQUEST).getRequests(); assertThat(requests).hasSize(1); validateValuesCount(requests.get(0), MetricCollectionAggregator.MAX_VALUES_PER_REQUEST); requests = aggregatorWithUniqueValuesAdded(HttpMetric.MAX_CONCURRENCY, MetricCollectionAggregator.MAX_VALUES_PER_REQUEST + 1).getRequests(); assertThat(requests).hasSize(2); validateValuesCount(requests.get(0), MetricCollectionAggregator.MAX_VALUES_PER_REQUEST); validateValuesCount(requests.get(1), 1); } | public List<PutMetricDataRequest> getRequests() { List<PutMetricDataRequest> requests = new ArrayList<>(); List<MetricDatum> requestMetricDatums = new ArrayList<>(); ValuesInRequestCounter valuesInRequestCounter = new ValuesInRequestCounter(); Map<Instant, Collection<MetricAggregator>> metrics = timeBucketedMetrics.timeBucketedMetrics(); for (Map.Entry<Instant, Collection<MetricAggregator>> entry : metrics.entrySet()) { Instant timeBucket = entry.getKey(); for (MetricAggregator metric : entry.getValue()) { if (requestMetricDatums.size() >= MAX_METRIC_DATA_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); } metric.ifSummary(summaryAggregator -> requestMetricDatums.add(summaryMetricDatum(timeBucket, summaryAggregator))); metric.ifDetailed(detailedAggregator -> { int startIndex = 0; Collection<DetailedMetrics> detailedMetrics = detailedAggregator.detailedMetrics(); while (startIndex < detailedMetrics.size()) { if (valuesInRequestCounter.get() >= MAX_VALUES_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); valuesInRequestCounter.reset(); } MetricDatum data = detailedMetricDatum(timeBucket, detailedAggregator, startIndex, MAX_VALUES_PER_REQUEST - valuesInRequestCounter.get()); int valuesAdded = data.values().size(); startIndex += valuesAdded; valuesInRequestCounter.add(valuesAdded); requestMetricDatums.add(data); } }); } } if (!requestMetricDatums.isEmpty()) { requests.add(newPutRequest(requestMetricDatums)); } timeBucketedMetrics.reset(); return requests; } | MetricCollectionAggregator { public List<PutMetricDataRequest> getRequests() { List<PutMetricDataRequest> requests = new ArrayList<>(); List<MetricDatum> requestMetricDatums = new ArrayList<>(); ValuesInRequestCounter valuesInRequestCounter = new ValuesInRequestCounter(); Map<Instant, Collection<MetricAggregator>> metrics = timeBucketedMetrics.timeBucketedMetrics(); for (Map.Entry<Instant, Collection<MetricAggregator>> entry : metrics.entrySet()) { Instant timeBucket = entry.getKey(); for (MetricAggregator metric : entry.getValue()) { if (requestMetricDatums.size() >= MAX_METRIC_DATA_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); } metric.ifSummary(summaryAggregator -> requestMetricDatums.add(summaryMetricDatum(timeBucket, summaryAggregator))); metric.ifDetailed(detailedAggregator -> { int startIndex = 0; Collection<DetailedMetrics> detailedMetrics = detailedAggregator.detailedMetrics(); while (startIndex < detailedMetrics.size()) { if (valuesInRequestCounter.get() >= MAX_VALUES_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); valuesInRequestCounter.reset(); } MetricDatum data = detailedMetricDatum(timeBucket, detailedAggregator, startIndex, MAX_VALUES_PER_REQUEST - valuesInRequestCounter.get()); int valuesAdded = data.values().size(); startIndex += valuesAdded; valuesInRequestCounter.add(valuesAdded); requestMetricDatums.add(data); } }); } } if (!requestMetricDatums.isEmpty()) { requests.add(newPutRequest(requestMetricDatums)); } timeBucketedMetrics.reset(); return requests; } } | MetricCollectionAggregator { public List<PutMetricDataRequest> getRequests() { List<PutMetricDataRequest> requests = new ArrayList<>(); List<MetricDatum> requestMetricDatums = new ArrayList<>(); ValuesInRequestCounter valuesInRequestCounter = new ValuesInRequestCounter(); Map<Instant, Collection<MetricAggregator>> metrics = timeBucketedMetrics.timeBucketedMetrics(); for (Map.Entry<Instant, Collection<MetricAggregator>> entry : metrics.entrySet()) { Instant timeBucket = entry.getKey(); for (MetricAggregator metric : entry.getValue()) { if (requestMetricDatums.size() >= MAX_METRIC_DATA_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); } metric.ifSummary(summaryAggregator -> requestMetricDatums.add(summaryMetricDatum(timeBucket, summaryAggregator))); metric.ifDetailed(detailedAggregator -> { int startIndex = 0; Collection<DetailedMetrics> detailedMetrics = detailedAggregator.detailedMetrics(); while (startIndex < detailedMetrics.size()) { if (valuesInRequestCounter.get() >= MAX_VALUES_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); valuesInRequestCounter.reset(); } MetricDatum data = detailedMetricDatum(timeBucket, detailedAggregator, startIndex, MAX_VALUES_PER_REQUEST - valuesInRequestCounter.get()); int valuesAdded = data.values().size(); startIndex += valuesAdded; valuesInRequestCounter.add(valuesAdded); requestMetricDatums.add(data); } }); } } if (!requestMetricDatums.isEmpty()) { requests.add(newPutRequest(requestMetricDatums)); } timeBucketedMetrics.reset(); return requests; } MetricCollectionAggregator(String namespace,
Set<SdkMetric<String>> dimensions,
Set<MetricCategory> metricCategories,
MetricLevel metricLevel,
Set<SdkMetric<?>> detailedMetrics); } | MetricCollectionAggregator { public List<PutMetricDataRequest> getRequests() { List<PutMetricDataRequest> requests = new ArrayList<>(); List<MetricDatum> requestMetricDatums = new ArrayList<>(); ValuesInRequestCounter valuesInRequestCounter = new ValuesInRequestCounter(); Map<Instant, Collection<MetricAggregator>> metrics = timeBucketedMetrics.timeBucketedMetrics(); for (Map.Entry<Instant, Collection<MetricAggregator>> entry : metrics.entrySet()) { Instant timeBucket = entry.getKey(); for (MetricAggregator metric : entry.getValue()) { if (requestMetricDatums.size() >= MAX_METRIC_DATA_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); } metric.ifSummary(summaryAggregator -> requestMetricDatums.add(summaryMetricDatum(timeBucket, summaryAggregator))); metric.ifDetailed(detailedAggregator -> { int startIndex = 0; Collection<DetailedMetrics> detailedMetrics = detailedAggregator.detailedMetrics(); while (startIndex < detailedMetrics.size()) { if (valuesInRequestCounter.get() >= MAX_VALUES_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); valuesInRequestCounter.reset(); } MetricDatum data = detailedMetricDatum(timeBucket, detailedAggregator, startIndex, MAX_VALUES_PER_REQUEST - valuesInRequestCounter.get()); int valuesAdded = data.values().size(); startIndex += valuesAdded; valuesInRequestCounter.add(valuesAdded); requestMetricDatums.add(data); } }); } } if (!requestMetricDatums.isEmpty()) { requests.add(newPutRequest(requestMetricDatums)); } timeBucketedMetrics.reset(); return requests; } MetricCollectionAggregator(String namespace,
Set<SdkMetric<String>> dimensions,
Set<MetricCategory> metricCategories,
MetricLevel metricLevel,
Set<SdkMetric<?>> detailedMetrics); void addCollection(MetricCollection collection); List<PutMetricDataRequest> getRequests(); } | MetricCollectionAggregator { public List<PutMetricDataRequest> getRequests() { List<PutMetricDataRequest> requests = new ArrayList<>(); List<MetricDatum> requestMetricDatums = new ArrayList<>(); ValuesInRequestCounter valuesInRequestCounter = new ValuesInRequestCounter(); Map<Instant, Collection<MetricAggregator>> metrics = timeBucketedMetrics.timeBucketedMetrics(); for (Map.Entry<Instant, Collection<MetricAggregator>> entry : metrics.entrySet()) { Instant timeBucket = entry.getKey(); for (MetricAggregator metric : entry.getValue()) { if (requestMetricDatums.size() >= MAX_METRIC_DATA_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); } metric.ifSummary(summaryAggregator -> requestMetricDatums.add(summaryMetricDatum(timeBucket, summaryAggregator))); metric.ifDetailed(detailedAggregator -> { int startIndex = 0; Collection<DetailedMetrics> detailedMetrics = detailedAggregator.detailedMetrics(); while (startIndex < detailedMetrics.size()) { if (valuesInRequestCounter.get() >= MAX_VALUES_PER_REQUEST) { requests.add(newPutRequest(requestMetricDatums)); requestMetricDatums.clear(); valuesInRequestCounter.reset(); } MetricDatum data = detailedMetricDatum(timeBucket, detailedAggregator, startIndex, MAX_VALUES_PER_REQUEST - valuesInRequestCounter.get()); int valuesAdded = data.values().size(); startIndex += valuesAdded; valuesInRequestCounter.add(valuesAdded); requestMetricDatums.add(data); } }); } } if (!requestMetricDatums.isEmpty()) { requests.add(newPutRequest(requestMetricDatums)); } timeBucketedMetrics.reset(); return requests; } MetricCollectionAggregator(String namespace,
Set<SdkMetric<String>> dimensions,
Set<MetricCategory> metricCategories,
MetricLevel metricLevel,
Set<SdkMetric<?>> detailedMetrics); void addCollection(MetricCollection collection); List<PutMetricDataRequest> getRequests(); static final int MAX_METRIC_DATA_PER_REQUEST; static final int MAX_VALUES_PER_REQUEST; } |
@Test public void extraTasksAboveMaximumAreDropped() { List<PutMetricDataRequest> requests = Arrays.asList(PutMetricDataRequest.builder().build(), PutMetricDataRequest.builder().build(), PutMetricDataRequest.builder().build()); Mockito.when(aggregator.getRequests()).thenReturn(requests); task.call(); ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class); Mockito.verify(uploader).upload(captor.capture()); List<PutMetricDataRequest> uploadedRequests = captor.getValue(); assertThat(uploadedRequests).hasSize(2); assertThat(uploadedRequests).containsOnlyElementsOf(requests); } | @Override public CompletableFuture<?> call() { try { List<PutMetricDataRequest> allRequests = collectionAggregator.getRequests(); List<PutMetricDataRequest> requests = allRequests; if (requests.size() > maximumRequestsPerFlush) { METRIC_LOGGER.warn(() -> "Maximum AWS SDK client-side metric call count exceeded: " + allRequests.size() + " > " + maximumRequestsPerFlush + ". Some metric requests will be dropped. This occurs " + "when the caller has configured too many metrics or too unique of dimensions without " + "an associated increase in the maximum-calls-per-upload configured on the publisher."); requests = requests.subList(0, maximumRequestsPerFlush); } return uploader.upload(requests); } catch (Throwable t) { return CompletableFutureUtils.failedFuture(t); } } | UploadMetricsTasks implements Callable<CompletableFuture<?>> { @Override public CompletableFuture<?> call() { try { List<PutMetricDataRequest> allRequests = collectionAggregator.getRequests(); List<PutMetricDataRequest> requests = allRequests; if (requests.size() > maximumRequestsPerFlush) { METRIC_LOGGER.warn(() -> "Maximum AWS SDK client-side metric call count exceeded: " + allRequests.size() + " > " + maximumRequestsPerFlush + ". Some metric requests will be dropped. This occurs " + "when the caller has configured too many metrics or too unique of dimensions without " + "an associated increase in the maximum-calls-per-upload configured on the publisher."); requests = requests.subList(0, maximumRequestsPerFlush); } return uploader.upload(requests); } catch (Throwable t) { return CompletableFutureUtils.failedFuture(t); } } } | UploadMetricsTasks implements Callable<CompletableFuture<?>> { @Override public CompletableFuture<?> call() { try { List<PutMetricDataRequest> allRequests = collectionAggregator.getRequests(); List<PutMetricDataRequest> requests = allRequests; if (requests.size() > maximumRequestsPerFlush) { METRIC_LOGGER.warn(() -> "Maximum AWS SDK client-side metric call count exceeded: " + allRequests.size() + " > " + maximumRequestsPerFlush + ". Some metric requests will be dropped. This occurs " + "when the caller has configured too many metrics or too unique of dimensions without " + "an associated increase in the maximum-calls-per-upload configured on the publisher."); requests = requests.subList(0, maximumRequestsPerFlush); } return uploader.upload(requests); } catch (Throwable t) { return CompletableFutureUtils.failedFuture(t); } } UploadMetricsTasks(MetricCollectionAggregator collectionAggregator,
MetricUploader uploader,
int maximumRequestsPerFlush); } | UploadMetricsTasks implements Callable<CompletableFuture<?>> { @Override public CompletableFuture<?> call() { try { List<PutMetricDataRequest> allRequests = collectionAggregator.getRequests(); List<PutMetricDataRequest> requests = allRequests; if (requests.size() > maximumRequestsPerFlush) { METRIC_LOGGER.warn(() -> "Maximum AWS SDK client-side metric call count exceeded: " + allRequests.size() + " > " + maximumRequestsPerFlush + ". Some metric requests will be dropped. This occurs " + "when the caller has configured too many metrics or too unique of dimensions without " + "an associated increase in the maximum-calls-per-upload configured on the publisher."); requests = requests.subList(0, maximumRequestsPerFlush); } return uploader.upload(requests); } catch (Throwable t) { return CompletableFutureUtils.failedFuture(t); } } UploadMetricsTasks(MetricCollectionAggregator collectionAggregator,
MetricUploader uploader,
int maximumRequestsPerFlush); @Override CompletableFuture<?> call(); } | UploadMetricsTasks implements Callable<CompletableFuture<?>> { @Override public CompletableFuture<?> call() { try { List<PutMetricDataRequest> allRequests = collectionAggregator.getRequests(); List<PutMetricDataRequest> requests = allRequests; if (requests.size() > maximumRequestsPerFlush) { METRIC_LOGGER.warn(() -> "Maximum AWS SDK client-side metric call count exceeded: " + allRequests.size() + " > " + maximumRequestsPerFlush + ". Some metric requests will be dropped. This occurs " + "when the caller has configured too many metrics or too unique of dimensions without " + "an associated increase in the maximum-calls-per-upload configured on the publisher."); requests = requests.subList(0, maximumRequestsPerFlush); } return uploader.upload(requests); } catch (Throwable t) { return CompletableFutureUtils.failedFuture(t); } } UploadMetricsTasks(MetricCollectionAggregator collectionAggregator,
MetricUploader uploader,
int maximumRequestsPerFlush); @Override CompletableFuture<?> call(); } |
@Test public void uploadSuccessIsPropagated() { CompletableFuture<Void> uploadFuture = uploader.upload(Arrays.asList(PutMetricDataRequest.builder().build(), PutMetricDataRequest.builder().build())); assertThat(putMetricDataResponseFutures).hasSize(2); assertThat(uploadFuture).isNotCompleted(); putMetricDataResponseFutures.get(0).complete(PutMetricDataResponse.builder().build()); assertThat(uploadFuture).isNotCompleted(); putMetricDataResponseFutures.get(1).complete(PutMetricDataResponse.builder().build()); assertThat(uploadFuture).isCompleted(); } | public CompletableFuture<Void> upload(List<PutMetricDataRequest> requests) { CompletableFuture<?>[] publishResults = startCalls(requests); return CompletableFuture.allOf(publishResults).whenComplete((r, t) -> { int numRequests = publishResults.length; if (t != null) { METRIC_LOGGER.warn(() -> "Failed while publishing some or all AWS SDK client-side metrics to CloudWatch.", t); } else { METRIC_LOGGER.debug(() -> "Successfully published " + numRequests + " AWS SDK client-side metric requests to CloudWatch."); } }); } | MetricUploader { public CompletableFuture<Void> upload(List<PutMetricDataRequest> requests) { CompletableFuture<?>[] publishResults = startCalls(requests); return CompletableFuture.allOf(publishResults).whenComplete((r, t) -> { int numRequests = publishResults.length; if (t != null) { METRIC_LOGGER.warn(() -> "Failed while publishing some or all AWS SDK client-side metrics to CloudWatch.", t); } else { METRIC_LOGGER.debug(() -> "Successfully published " + numRequests + " AWS SDK client-side metric requests to CloudWatch."); } }); } } | MetricUploader { public CompletableFuture<Void> upload(List<PutMetricDataRequest> requests) { CompletableFuture<?>[] publishResults = startCalls(requests); return CompletableFuture.allOf(publishResults).whenComplete((r, t) -> { int numRequests = publishResults.length; if (t != null) { METRIC_LOGGER.warn(() -> "Failed while publishing some or all AWS SDK client-side metrics to CloudWatch.", t); } else { METRIC_LOGGER.debug(() -> "Successfully published " + numRequests + " AWS SDK client-side metric requests to CloudWatch."); } }); } MetricUploader(CloudWatchAsyncClient cloudWatchClient); } | MetricUploader { public CompletableFuture<Void> upload(List<PutMetricDataRequest> requests) { CompletableFuture<?>[] publishResults = startCalls(requests); return CompletableFuture.allOf(publishResults).whenComplete((r, t) -> { int numRequests = publishResults.length; if (t != null) { METRIC_LOGGER.warn(() -> "Failed while publishing some or all AWS SDK client-side metrics to CloudWatch.", t); } else { METRIC_LOGGER.debug(() -> "Successfully published " + numRequests + " AWS SDK client-side metric requests to CloudWatch."); } }); } MetricUploader(CloudWatchAsyncClient cloudWatchClient); CompletableFuture<Void> upload(List<PutMetricDataRequest> requests); void close(boolean closeClient); } | MetricUploader { public CompletableFuture<Void> upload(List<PutMetricDataRequest> requests) { CompletableFuture<?>[] publishResults = startCalls(requests); return CompletableFuture.allOf(publishResults).whenComplete((r, t) -> { int numRequests = publishResults.length; if (t != null) { METRIC_LOGGER.warn(() -> "Failed while publishing some or all AWS SDK client-side metrics to CloudWatch.", t); } else { METRIC_LOGGER.debug(() -> "Successfully published " + numRequests + " AWS SDK client-side metric requests to CloudWatch."); } }); } MetricUploader(CloudWatchAsyncClient cloudWatchClient); CompletableFuture<Void> upload(List<PutMetricDataRequest> requests); void close(boolean closeClient); } |
@Test public void uploadFailureIsPropagated() { CompletableFuture<Void> uploadFuture = uploader.upload(Arrays.asList(PutMetricDataRequest.builder().build(), PutMetricDataRequest.builder().build())); assertThat(putMetricDataResponseFutures).hasSize(2); assertThat(uploadFuture).isNotCompleted(); putMetricDataResponseFutures.get(0).completeExceptionally(new Throwable()); putMetricDataResponseFutures.get(1).complete(PutMetricDataResponse.builder().build()); assertThat(uploadFuture).isCompletedExceptionally(); } | public CompletableFuture<Void> upload(List<PutMetricDataRequest> requests) { CompletableFuture<?>[] publishResults = startCalls(requests); return CompletableFuture.allOf(publishResults).whenComplete((r, t) -> { int numRequests = publishResults.length; if (t != null) { METRIC_LOGGER.warn(() -> "Failed while publishing some or all AWS SDK client-side metrics to CloudWatch.", t); } else { METRIC_LOGGER.debug(() -> "Successfully published " + numRequests + " AWS SDK client-side metric requests to CloudWatch."); } }); } | MetricUploader { public CompletableFuture<Void> upload(List<PutMetricDataRequest> requests) { CompletableFuture<?>[] publishResults = startCalls(requests); return CompletableFuture.allOf(publishResults).whenComplete((r, t) -> { int numRequests = publishResults.length; if (t != null) { METRIC_LOGGER.warn(() -> "Failed while publishing some or all AWS SDK client-side metrics to CloudWatch.", t); } else { METRIC_LOGGER.debug(() -> "Successfully published " + numRequests + " AWS SDK client-side metric requests to CloudWatch."); } }); } } | MetricUploader { public CompletableFuture<Void> upload(List<PutMetricDataRequest> requests) { CompletableFuture<?>[] publishResults = startCalls(requests); return CompletableFuture.allOf(publishResults).whenComplete((r, t) -> { int numRequests = publishResults.length; if (t != null) { METRIC_LOGGER.warn(() -> "Failed while publishing some or all AWS SDK client-side metrics to CloudWatch.", t); } else { METRIC_LOGGER.debug(() -> "Successfully published " + numRequests + " AWS SDK client-side metric requests to CloudWatch."); } }); } MetricUploader(CloudWatchAsyncClient cloudWatchClient); } | MetricUploader { public CompletableFuture<Void> upload(List<PutMetricDataRequest> requests) { CompletableFuture<?>[] publishResults = startCalls(requests); return CompletableFuture.allOf(publishResults).whenComplete((r, t) -> { int numRequests = publishResults.length; if (t != null) { METRIC_LOGGER.warn(() -> "Failed while publishing some or all AWS SDK client-side metrics to CloudWatch.", t); } else { METRIC_LOGGER.debug(() -> "Successfully published " + numRequests + " AWS SDK client-side metric requests to CloudWatch."); } }); } MetricUploader(CloudWatchAsyncClient cloudWatchClient); CompletableFuture<Void> upload(List<PutMetricDataRequest> requests); void close(boolean closeClient); } | MetricUploader { public CompletableFuture<Void> upload(List<PutMetricDataRequest> requests) { CompletableFuture<?>[] publishResults = startCalls(requests); return CompletableFuture.allOf(publishResults).whenComplete((r, t) -> { int numRequests = publishResults.length; if (t != null) { METRIC_LOGGER.warn(() -> "Failed while publishing some or all AWS SDK client-side metrics to CloudWatch.", t); } else { METRIC_LOGGER.debug(() -> "Successfully published " + numRequests + " AWS SDK client-side metric requests to CloudWatch."); } }); } MetricUploader(CloudWatchAsyncClient cloudWatchClient); CompletableFuture<Void> upload(List<PutMetricDataRequest> requests); void close(boolean closeClient); } |
@Test public void closeFalseDoesNotCloseClient() { uploader.close(false); Mockito.verify(client, never()).close(); } | public void close(boolean closeClient) { if (closeClient) { this.cloudWatchClient.close(); } } | MetricUploader { public void close(boolean closeClient) { if (closeClient) { this.cloudWatchClient.close(); } } } | MetricUploader { public void close(boolean closeClient) { if (closeClient) { this.cloudWatchClient.close(); } } MetricUploader(CloudWatchAsyncClient cloudWatchClient); } | MetricUploader { public void close(boolean closeClient) { if (closeClient) { this.cloudWatchClient.close(); } } MetricUploader(CloudWatchAsyncClient cloudWatchClient); CompletableFuture<Void> upload(List<PutMetricDataRequest> requests); void close(boolean closeClient); } | MetricUploader { public void close(boolean closeClient) { if (closeClient) { this.cloudWatchClient.close(); } } MetricUploader(CloudWatchAsyncClient cloudWatchClient); CompletableFuture<Void> upload(List<PutMetricDataRequest> requests); void close(boolean closeClient); } |
@Test public void modifyAsyncHttpResponseContent_getObjectRequest_responseDoesNotContainChecksum_shouldNotModify() { ExecutionAttributes executionAttributes = getExecutionAttributesWithChecksumDisabled(); SdkHttpResponse sdkHttpResponse = SdkHttpResponse.builder() .putHeader(CONTENT_LENGTH_HEADER, "100") .build(); Context.ModifyHttpResponse modifyHttpResponse = InterceptorTestUtils.modifyHttpResponse(GetObjectRequest.builder().build(), sdkHttpResponse); Optional<Publisher<ByteBuffer>> publisher = interceptor.modifyAsyncHttpResponseContent(modifyHttpResponse, executionAttributes); assertThat(publisher).isEqualTo(modifyHttpResponse.responsePublisher()); } | @Override public Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse()) && context.responsePublisher().isPresent()) { long contentLength = context.httpResponse() .firstMatchingHeader(CONTENT_LENGTH_HEADER) .map(Long::parseLong) .orElse(0L); SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(CHECKSUM, checksum); if (contentLength > 0) { return Optional.of(new ChecksumValidatingPublisher(context.responsePublisher().get(), checksum, contentLength)); } } return context.responsePublisher(); } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse()) && context.responsePublisher().isPresent()) { long contentLength = context.httpResponse() .firstMatchingHeader(CONTENT_LENGTH_HEADER) .map(Long::parseLong) .orElse(0L); SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(CHECKSUM, checksum); if (contentLength > 0) { return Optional.of(new ChecksumValidatingPublisher(context.responsePublisher().get(), checksum, contentLength)); } } return context.responsePublisher(); } } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse()) && context.responsePublisher().isPresent()) { long contentLength = context.httpResponse() .firstMatchingHeader(CONTENT_LENGTH_HEADER) .map(Long::parseLong) .orElse(0L); SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(CHECKSUM, checksum); if (contentLength > 0) { return Optional.of(new ChecksumValidatingPublisher(context.responsePublisher().get(), checksum, contentLength)); } } return context.responsePublisher(); } } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse()) && context.responsePublisher().isPresent()) { long contentLength = context.httpResponse() .firstMatchingHeader(CONTENT_LENGTH_HEADER) .map(Long::parseLong) .orElse(0L); SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(CHECKSUM, checksum); if (contentLength > 0) { return Optional.of(new ChecksumValidatingPublisher(context.responsePublisher().get(), checksum, contentLength)); } } return context.responsePublisher(); } @Override Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse()) && context.responsePublisher().isPresent()) { long contentLength = context.httpResponse() .firstMatchingHeader(CONTENT_LENGTH_HEADER) .map(Long::parseLong) .orElse(0L); SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(CHECKSUM, checksum); if (contentLength > 0) { return Optional.of(new ChecksumValidatingPublisher(context.responsePublisher().get(), checksum, contentLength)); } } return context.responsePublisher(); } @Override Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); } |
@Test public void closeTrueClosesClient() { uploader.close(true); Mockito.verify(client, times(1)).close(); } | public void close(boolean closeClient) { if (closeClient) { this.cloudWatchClient.close(); } } | MetricUploader { public void close(boolean closeClient) { if (closeClient) { this.cloudWatchClient.close(); } } } | MetricUploader { public void close(boolean closeClient) { if (closeClient) { this.cloudWatchClient.close(); } } MetricUploader(CloudWatchAsyncClient cloudWatchClient); } | MetricUploader { public void close(boolean closeClient) { if (closeClient) { this.cloudWatchClient.close(); } } MetricUploader(CloudWatchAsyncClient cloudWatchClient); CompletableFuture<Void> upload(List<PutMetricDataRequest> requests); void close(boolean closeClient); } | MetricUploader { public void close(boolean closeClient) { if (closeClient) { this.cloudWatchClient.close(); } } MetricUploader(CloudWatchAsyncClient cloudWatchClient); CompletableFuture<Void> upload(List<PutMetricDataRequest> requests); void close(boolean closeClient); } |
@Test public void namespaceSettingIsHonored() { try (CloudWatchMetricPublisher publisher = publisherBuilder.namespace("namespace").build()) { MetricCollector collector = newCollector(); collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, 5); publisher.publish(new FixedTimeMetricCollection(collector.collect())); } assertThat(getPutMetricCall().namespace()).isEqualTo("namespace"); } | @Override public void publish(MetricCollection metricCollection) { try { executor.submit(new AggregateMetricsTask(metricAggregator, metricCollection)); } catch (RejectedExecutionException e) { METRIC_LOGGER.warn(() -> "Some AWS SDK client-side metrics have been dropped because an internal executor did not " + "accept them. This usually occurs because your publisher has been shut down or you have " + "generated too many requests for the publisher to handle in a timely fashion.", e); } } | CloudWatchMetricPublisher implements MetricPublisher { @Override public void publish(MetricCollection metricCollection) { try { executor.submit(new AggregateMetricsTask(metricAggregator, metricCollection)); } catch (RejectedExecutionException e) { METRIC_LOGGER.warn(() -> "Some AWS SDK client-side metrics have been dropped because an internal executor did not " + "accept them. This usually occurs because your publisher has been shut down or you have " + "generated too many requests for the publisher to handle in a timely fashion.", e); } } } | CloudWatchMetricPublisher implements MetricPublisher { @Override public void publish(MetricCollection metricCollection) { try { executor.submit(new AggregateMetricsTask(metricAggregator, metricCollection)); } catch (RejectedExecutionException e) { METRIC_LOGGER.warn(() -> "Some AWS SDK client-side metrics have been dropped because an internal executor did not " + "accept them. This usually occurs because your publisher has been shut down or you have " + "generated too many requests for the publisher to handle in a timely fashion.", e); } } private CloudWatchMetricPublisher(Builder builder); } | CloudWatchMetricPublisher implements MetricPublisher { @Override public void publish(MetricCollection metricCollection) { try { executor.submit(new AggregateMetricsTask(metricAggregator, metricCollection)); } catch (RejectedExecutionException e) { METRIC_LOGGER.warn(() -> "Some AWS SDK client-side metrics have been dropped because an internal executor did not " + "accept them. This usually occurs because your publisher has been shut down or you have " + "generated too many requests for the publisher to handle in a timely fashion.", e); } } private CloudWatchMetricPublisher(Builder builder); @Override void publish(MetricCollection metricCollection); @Override void close(); static Builder builder(); static CloudWatchMetricPublisher create(); } | CloudWatchMetricPublisher implements MetricPublisher { @Override public void publish(MetricCollection metricCollection) { try { executor.submit(new AggregateMetricsTask(metricAggregator, metricCollection)); } catch (RejectedExecutionException e) { METRIC_LOGGER.warn(() -> "Some AWS SDK client-side metrics have been dropped because an internal executor did not " + "accept them. This usually occurs because your publisher has been shut down or you have " + "generated too many requests for the publisher to handle in a timely fashion.", e); } } private CloudWatchMetricPublisher(Builder builder); @Override void publish(MetricCollection metricCollection); @Override void close(); static Builder builder(); static CloudWatchMetricPublisher create(); } |
@Test public void maximumCallsPerPublishSettingIsHonored() { try (CloudWatchMetricPublisher publisher = publisherBuilder.maximumCallsPerUpload(1) .detailedMetrics(HttpMetric.AVAILABLE_CONCURRENCY) .build()) { for (int i = 0; i < MetricCollectionAggregator.MAX_VALUES_PER_REQUEST + 1; ++i) { MetricCollector collector = newCollector(); collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, i); publisher.publish(new FixedTimeMetricCollection(collector.collect())); } } assertThat(getPutMetricCalls()).hasSize(1); } | @Override public void publish(MetricCollection metricCollection) { try { executor.submit(new AggregateMetricsTask(metricAggregator, metricCollection)); } catch (RejectedExecutionException e) { METRIC_LOGGER.warn(() -> "Some AWS SDK client-side metrics have been dropped because an internal executor did not " + "accept them. This usually occurs because your publisher has been shut down or you have " + "generated too many requests for the publisher to handle in a timely fashion.", e); } } | CloudWatchMetricPublisher implements MetricPublisher { @Override public void publish(MetricCollection metricCollection) { try { executor.submit(new AggregateMetricsTask(metricAggregator, metricCollection)); } catch (RejectedExecutionException e) { METRIC_LOGGER.warn(() -> "Some AWS SDK client-side metrics have been dropped because an internal executor did not " + "accept them. This usually occurs because your publisher has been shut down or you have " + "generated too many requests for the publisher to handle in a timely fashion.", e); } } } | CloudWatchMetricPublisher implements MetricPublisher { @Override public void publish(MetricCollection metricCollection) { try { executor.submit(new AggregateMetricsTask(metricAggregator, metricCollection)); } catch (RejectedExecutionException e) { METRIC_LOGGER.warn(() -> "Some AWS SDK client-side metrics have been dropped because an internal executor did not " + "accept them. This usually occurs because your publisher has been shut down or you have " + "generated too many requests for the publisher to handle in a timely fashion.", e); } } private CloudWatchMetricPublisher(Builder builder); } | CloudWatchMetricPublisher implements MetricPublisher { @Override public void publish(MetricCollection metricCollection) { try { executor.submit(new AggregateMetricsTask(metricAggregator, metricCollection)); } catch (RejectedExecutionException e) { METRIC_LOGGER.warn(() -> "Some AWS SDK client-side metrics have been dropped because an internal executor did not " + "accept them. This usually occurs because your publisher has been shut down or you have " + "generated too many requests for the publisher to handle in a timely fashion.", e); } } private CloudWatchMetricPublisher(Builder builder); @Override void publish(MetricCollection metricCollection); @Override void close(); static Builder builder(); static CloudWatchMetricPublisher create(); } | CloudWatchMetricPublisher implements MetricPublisher { @Override public void publish(MetricCollection metricCollection) { try { executor.submit(new AggregateMetricsTask(metricAggregator, metricCollection)); } catch (RejectedExecutionException e) { METRIC_LOGGER.warn(() -> "Some AWS SDK client-side metrics have been dropped because an internal executor did not " + "accept them. This usually occurs because your publisher has been shut down or you have " + "generated too many requests for the publisher to handle in a timely fashion.", e); } } private CloudWatchMetricPublisher(Builder builder); @Override void publish(MetricCollection metricCollection); @Override void close(); static Builder builder(); static CloudWatchMetricPublisher create(); } |
@Test public void detailedMetricsSettingIsHonored() { try (CloudWatchMetricPublisher publisher = publisherBuilder.detailedMetrics(HttpMetric.AVAILABLE_CONCURRENCY).build()) { for (int i = 0; i < 10; ++i) { MetricCollector collector = newCollector(); collector.reportMetric(HttpMetric.MAX_CONCURRENCY, 10); collector.reportMetric(HttpMetric.AVAILABLE_CONCURRENCY, i); publisher.publish(new FixedTimeMetricCollection(collector.collect())); } } PutMetricDataRequest call = getPutMetricCall(); MetricDatum concurrencyMetric = getDatum(call, HttpMetric.MAX_CONCURRENCY); MetricDatum availableConcurrency = getDatum(call, HttpMetric.AVAILABLE_CONCURRENCY); assertThat(concurrencyMetric.values()).isEmpty(); assertThat(concurrencyMetric.counts()).isEmpty(); assertThat(concurrencyMetric.statisticValues()).isNotNull(); assertThat(availableConcurrency.values()).isNotEmpty(); assertThat(availableConcurrency.counts()).isNotEmpty(); assertThat(availableConcurrency.statisticValues()).isNull(); } | @Override public void publish(MetricCollection metricCollection) { try { executor.submit(new AggregateMetricsTask(metricAggregator, metricCollection)); } catch (RejectedExecutionException e) { METRIC_LOGGER.warn(() -> "Some AWS SDK client-side metrics have been dropped because an internal executor did not " + "accept them. This usually occurs because your publisher has been shut down or you have " + "generated too many requests for the publisher to handle in a timely fashion.", e); } } | CloudWatchMetricPublisher implements MetricPublisher { @Override public void publish(MetricCollection metricCollection) { try { executor.submit(new AggregateMetricsTask(metricAggregator, metricCollection)); } catch (RejectedExecutionException e) { METRIC_LOGGER.warn(() -> "Some AWS SDK client-side metrics have been dropped because an internal executor did not " + "accept them. This usually occurs because your publisher has been shut down or you have " + "generated too many requests for the publisher to handle in a timely fashion.", e); } } } | CloudWatchMetricPublisher implements MetricPublisher { @Override public void publish(MetricCollection metricCollection) { try { executor.submit(new AggregateMetricsTask(metricAggregator, metricCollection)); } catch (RejectedExecutionException e) { METRIC_LOGGER.warn(() -> "Some AWS SDK client-side metrics have been dropped because an internal executor did not " + "accept them. This usually occurs because your publisher has been shut down or you have " + "generated too many requests for the publisher to handle in a timely fashion.", e); } } private CloudWatchMetricPublisher(Builder builder); } | CloudWatchMetricPublisher implements MetricPublisher { @Override public void publish(MetricCollection metricCollection) { try { executor.submit(new AggregateMetricsTask(metricAggregator, metricCollection)); } catch (RejectedExecutionException e) { METRIC_LOGGER.warn(() -> "Some AWS SDK client-side metrics have been dropped because an internal executor did not " + "accept them. This usually occurs because your publisher has been shut down or you have " + "generated too many requests for the publisher to handle in a timely fashion.", e); } } private CloudWatchMetricPublisher(Builder builder); @Override void publish(MetricCollection metricCollection); @Override void close(); static Builder builder(); static CloudWatchMetricPublisher create(); } | CloudWatchMetricPublisher implements MetricPublisher { @Override public void publish(MetricCollection metricCollection) { try { executor.submit(new AggregateMetricsTask(metricAggregator, metricCollection)); } catch (RejectedExecutionException e) { METRIC_LOGGER.warn(() -> "Some AWS SDK client-side metrics have been dropped because an internal executor did not " + "accept them. This usually occurs because your publisher has been shut down or you have " + "generated too many requests for the publisher to handle in a timely fashion.", e); } } private CloudWatchMetricPublisher(Builder builder); @Override void publish(MetricCollection metricCollection); @Override void close(); static Builder builder(); static CloudWatchMetricPublisher create(); } |
@Test public void propertiesNotSet_returnsNull() { assertThat(PROVIDER.keyManagers()).isNull(); } | @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } private SystemPropertyTlsKeyManagersProvider(); } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } private SystemPropertyTlsKeyManagersProvider(); @Override KeyManager[] keyManagers(); static SystemPropertyTlsKeyManagersProvider create(); } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } private SystemPropertyTlsKeyManagersProvider(); @Override KeyManager[] keyManagers(); static SystemPropertyTlsKeyManagersProvider create(); } |
@Test public void propertiesSet_createsKeyManager() { System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD); assertThat(PROVIDER.keyManagers()).hasSize(1); } | @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } private SystemPropertyTlsKeyManagersProvider(); } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } private SystemPropertyTlsKeyManagersProvider(); @Override KeyManager[] keyManagers(); static SystemPropertyTlsKeyManagersProvider create(); } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } private SystemPropertyTlsKeyManagersProvider(); @Override KeyManager[] keyManagers(); static SystemPropertyTlsKeyManagersProvider create(); } |
@Test public void storeDoesNotExist_returnsNull() { System.setProperty(SSL_KEY_STORE.property(), Paths.get("does", "not", "exist").toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD); assertThat(PROVIDER.keyManagers()).isNull(); } | @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } private SystemPropertyTlsKeyManagersProvider(); } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } private SystemPropertyTlsKeyManagersProvider(); @Override KeyManager[] keyManagers(); static SystemPropertyTlsKeyManagersProvider create(); } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } private SystemPropertyTlsKeyManagersProvider(); @Override KeyManager[] keyManagers(); static SystemPropertyTlsKeyManagersProvider create(); } |
@Test public void invalidStoreType_returnsNull() { System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), "invalid"); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD); assertThat(PROVIDER.keyManagers()).isNull(); } | @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } private SystemPropertyTlsKeyManagersProvider(); } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } private SystemPropertyTlsKeyManagersProvider(); @Override KeyManager[] keyManagers(); static SystemPropertyTlsKeyManagersProvider create(); } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } private SystemPropertyTlsKeyManagersProvider(); @Override KeyManager[] keyManagers(); static SystemPropertyTlsKeyManagersProvider create(); } |
@Test public void passwordIncorrect_returnsNull() { System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), "not correct password"); assertThat(PROVIDER.keyManagers()).isNull(); } | @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } private SystemPropertyTlsKeyManagersProvider(); } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } private SystemPropertyTlsKeyManagersProvider(); @Override KeyManager[] keyManagers(); static SystemPropertyTlsKeyManagersProvider create(); } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } private SystemPropertyTlsKeyManagersProvider(); @Override KeyManager[] keyManagers(); static SystemPropertyTlsKeyManagersProvider create(); } |
@Test public void customKmfAlgorithmSetInProperty_usesAlgorithm() { System.setProperty(SSL_KEY_STORE.property(), clientKeyStore.toAbsolutePath().toString()); System.setProperty(SSL_KEY_STORE_TYPE.property(), CLIENT_STORE_TYPE); System.setProperty(SSL_KEY_STORE_PASSWORD.property(), STORE_PASSWORD); assertThat(PROVIDER.keyManagers()).isNotNull(); String property = "ssl.KeyManagerFactory.algorithm"; String previousValue = Security.getProperty(property); Security.setProperty(property, "some-bogus-value"); try { assertThat(PROVIDER.keyManagers()).isNull(); } finally { Security.setProperty(property, previousValue); } } | @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } private SystemPropertyTlsKeyManagersProvider(); } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } private SystemPropertyTlsKeyManagersProvider(); @Override KeyManager[] keyManagers(); static SystemPropertyTlsKeyManagersProvider create(); } | SystemPropertyTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { @Override public KeyManager[] keyManagers() { return getKeyStore().map(p -> { Path path = Paths.get(p); String type = getKeyStoreType(); char[] password = getKeyStorePassword().map(String::toCharArray).orElse(null); try { return createKeyManagers(path, type, password); } catch (Exception e) { log.warn(() -> String.format("Unable to create KeyManagers from %s property value '%s'", SSL_KEY_STORE.property(), p), e); return null; } }).orElse(null); } private SystemPropertyTlsKeyManagersProvider(); @Override KeyManager[] keyManagers(); static SystemPropertyTlsKeyManagersProvider create(); } |
@Test public void modifyAsyncHttpResponseContent_nonGetObjectRequest_shouldNotModify() { ExecutionAttributes executionAttributes = getExecutionAttributes(); SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader(); sdkHttpResponse.toBuilder().clearHeaders(); Context.ModifyHttpResponse modifyHttpResponse = InterceptorTestUtils.modifyHttpResponse(PutObjectRequest.builder().build(), sdkHttpResponse); Optional<Publisher<ByteBuffer>> publisher = interceptor.modifyAsyncHttpResponseContent(modifyHttpResponse, executionAttributes); assertThat(publisher).isEqualTo(modifyHttpResponse.responsePublisher()); } | @Override public Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse()) && context.responsePublisher().isPresent()) { long contentLength = context.httpResponse() .firstMatchingHeader(CONTENT_LENGTH_HEADER) .map(Long::parseLong) .orElse(0L); SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(CHECKSUM, checksum); if (contentLength > 0) { return Optional.of(new ChecksumValidatingPublisher(context.responsePublisher().get(), checksum, contentLength)); } } return context.responsePublisher(); } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse()) && context.responsePublisher().isPresent()) { long contentLength = context.httpResponse() .firstMatchingHeader(CONTENT_LENGTH_HEADER) .map(Long::parseLong) .orElse(0L); SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(CHECKSUM, checksum); if (contentLength > 0) { return Optional.of(new ChecksumValidatingPublisher(context.responsePublisher().get(), checksum, contentLength)); } } return context.responsePublisher(); } } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse()) && context.responsePublisher().isPresent()) { long contentLength = context.httpResponse() .firstMatchingHeader(CONTENT_LENGTH_HEADER) .map(Long::parseLong) .orElse(0L); SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(CHECKSUM, checksum); if (contentLength > 0) { return Optional.of(new ChecksumValidatingPublisher(context.responsePublisher().get(), checksum, contentLength)); } } return context.responsePublisher(); } } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse()) && context.responsePublisher().isPresent()) { long contentLength = context.httpResponse() .firstMatchingHeader(CONTENT_LENGTH_HEADER) .map(Long::parseLong) .orElse(0L); SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(CHECKSUM, checksum); if (contentLength > 0) { return Optional.of(new ChecksumValidatingPublisher(context.responsePublisher().get(), checksum, contentLength)); } } return context.responsePublisher(); } @Override Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context, ExecutionAttributes executionAttributes) { if (getObjectChecksumEnabledPerResponse(context.request(), context.httpResponse()) && context.responsePublisher().isPresent()) { long contentLength = context.httpResponse() .firstMatchingHeader(CONTENT_LENGTH_HEADER) .map(Long::parseLong) .orElse(0L); SdkChecksum checksum = new Md5Checksum(); executionAttributes.putAttribute(CHECKSUM, checksum); if (contentLength > 0) { return Optional.of(new ChecksumValidatingPublisher(context.responsePublisher().get(), checksum, contentLength)); } } return context.responsePublisher(); } @Override Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); } |
@Test(expected = NullPointerException.class) public void storePathNull_throwsValidationException() { FileStoreTlsKeyManagersProvider.create(null, CLIENT_STORE_TYPE, STORE_PASSWORD); } | public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } | FileStoreTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } } | FileStoreTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } private FileStoreTlsKeyManagersProvider(Path storePath, String storeType, char[] password); } | FileStoreTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } private FileStoreTlsKeyManagersProvider(Path storePath, String storeType, char[] password); @Override KeyManager[] keyManagers(); static FileStoreTlsKeyManagersProvider create(Path path, String type, String password); } | FileStoreTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } private FileStoreTlsKeyManagersProvider(Path storePath, String storeType, char[] password); @Override KeyManager[] keyManagers(); static FileStoreTlsKeyManagersProvider create(Path path, String type, String password); } |
@Test(expected = NullPointerException.class) public void storeTypeNull_throwsValidationException() { FileStoreTlsKeyManagersProvider.create(clientKeyStore, null, STORE_PASSWORD); } | public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } | FileStoreTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } } | FileStoreTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } private FileStoreTlsKeyManagersProvider(Path storePath, String storeType, char[] password); } | FileStoreTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } private FileStoreTlsKeyManagersProvider(Path storePath, String storeType, char[] password); @Override KeyManager[] keyManagers(); static FileStoreTlsKeyManagersProvider create(Path path, String type, String password); } | FileStoreTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } private FileStoreTlsKeyManagersProvider(Path storePath, String storeType, char[] password); @Override KeyManager[] keyManagers(); static FileStoreTlsKeyManagersProvider create(Path path, String type, String password); } |
@Test(expected = IllegalArgumentException.class) public void storeTypeEmpty_throwsValidationException() { FileStoreTlsKeyManagersProvider.create(clientKeyStore, "", STORE_PASSWORD); } | public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } | FileStoreTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } } | FileStoreTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } private FileStoreTlsKeyManagersProvider(Path storePath, String storeType, char[] password); } | FileStoreTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } private FileStoreTlsKeyManagersProvider(Path storePath, String storeType, char[] password); @Override KeyManager[] keyManagers(); static FileStoreTlsKeyManagersProvider create(Path path, String type, String password); } | FileStoreTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } private FileStoreTlsKeyManagersProvider(Path storePath, String storeType, char[] password); @Override KeyManager[] keyManagers(); static FileStoreTlsKeyManagersProvider create(Path path, String type, String password); } |
@Test public void passwordNotGiven_doesNotThrowValidationException() { FileStoreTlsKeyManagersProvider.create(clientKeyStore, CLIENT_STORE_TYPE, null); } | public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } | FileStoreTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } } | FileStoreTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } private FileStoreTlsKeyManagersProvider(Path storePath, String storeType, char[] password); } | FileStoreTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } private FileStoreTlsKeyManagersProvider(Path storePath, String storeType, char[] password); @Override KeyManager[] keyManagers(); static FileStoreTlsKeyManagersProvider create(Path path, String type, String password); } | FileStoreTlsKeyManagersProvider extends AbstractFileStoreTlsKeyManagersProvider { public static FileStoreTlsKeyManagersProvider create(Path path, String type, String password) { char[] passwordChars = password != null ? password.toCharArray() : null; return new FileStoreTlsKeyManagersProvider(path, type, passwordChars); } private FileStoreTlsKeyManagersProvider(Path storePath, String storeType, char[] password); @Override KeyManager[] keyManagers(); static FileStoreTlsKeyManagersProvider create(Path path, String type, String password); } |
@Test public void cannotFindShapeWhenNoShapesExist() { ServiceMetadata metadata = new ServiceMetadata(); metadata.setProtocol(Protocol.REST_JSON.getValue()); metadata.setServiceId("empty-service"); metadata.setSignatureVersion("V4"); IntermediateModel testModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(new ServiceModel(metadata, Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap())) .customizationConfig(CustomizationConfig.create()) .build()) .build(); assertThatThrownBy(() -> testModel.getShapeByNameAndC2jName("AnyShape", "AnyShape")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("C2J shape AnyShape with shape name AnyShape does not exist in the intermediate model."); } | public ShapeModel getShapeByNameAndC2jName(String shapeName, String shapeC2jName) { for (ShapeModel sm : getShapes().values()) { if (shapeName.equals(sm.getShapeName()) && shapeC2jName.equals(sm.getC2jName())) { return sm; } } throw new IllegalArgumentException("C2J shape " + shapeC2jName + " with shape name " + shapeName + " does not exist in " + "the intermediate model."); } | IntermediateModel { public ShapeModel getShapeByNameAndC2jName(String shapeName, String shapeC2jName) { for (ShapeModel sm : getShapes().values()) { if (shapeName.equals(sm.getShapeName()) && shapeC2jName.equals(sm.getC2jName())) { return sm; } } throw new IllegalArgumentException("C2J shape " + shapeC2jName + " with shape name " + shapeName + " does not exist in " + "the intermediate model."); } } | IntermediateModel { public ShapeModel getShapeByNameAndC2jName(String shapeName, String shapeC2jName) { for (ShapeModel sm : getShapes().values()) { if (shapeName.equals(sm.getShapeName()) && shapeC2jName.equals(sm.getC2jName())) { return sm; } } throw new IllegalArgumentException("C2J shape " + shapeC2jName + " with shape name " + shapeName + " does not exist in " + "the intermediate model."); } IntermediateModel(); IntermediateModel(Metadata metadata,
Map<String, OperationModel> operations,
Map<String, ShapeModel> shapes,
CustomizationConfig customizationConfig); IntermediateModel(
Metadata metadata,
Map<String, OperationModel> operations,
Map<String, ShapeModel> shapes,
CustomizationConfig customizationConfig,
OperationModel endpointOperation,
Map<String, AuthorizerModel> customAuthorizers,
Map<String, PaginatorDefinition> paginators,
NamingStrategy namingStrategy,
Map<String, WaiterDefinition> waiters); } | IntermediateModel { public ShapeModel getShapeByNameAndC2jName(String shapeName, String shapeC2jName) { for (ShapeModel sm : getShapes().values()) { if (shapeName.equals(sm.getShapeName()) && shapeC2jName.equals(sm.getC2jName())) { return sm; } } throw new IllegalArgumentException("C2J shape " + shapeC2jName + " with shape name " + shapeName + " does not exist in " + "the intermediate model."); } IntermediateModel(); IntermediateModel(Metadata metadata,
Map<String, OperationModel> operations,
Map<String, ShapeModel> shapes,
CustomizationConfig customizationConfig); IntermediateModel(
Metadata metadata,
Map<String, OperationModel> operations,
Map<String, ShapeModel> shapes,
CustomizationConfig customizationConfig,
OperationModel endpointOperation,
Map<String, AuthorizerModel> customAuthorizers,
Map<String, PaginatorDefinition> paginators,
NamingStrategy namingStrategy,
Map<String, WaiterDefinition> waiters); Metadata getMetadata(); void setMetadata(Metadata metadata); Map<String, OperationModel> getOperations(); void setOperations(Map<String, OperationModel> operations); OperationModel getOperation(String operationName); Map<String, ShapeModel> getShapes(); void setShapes(Map<String, ShapeModel> shapes); ShapeModel getShapeByNameAndC2jName(String shapeName, String shapeC2jName); CustomizationConfig getCustomizationConfig(); void setCustomizationConfig(CustomizationConfig customizationConfig); Map<String, PaginatorDefinition> getPaginators(); Map<String, WaiterDefinition> getWaiters(); void setPaginators(Map<String, PaginatorDefinition> paginators); NamingStrategy getNamingStrategy(); void setNamingStrategy(NamingStrategy namingStrategy); String getCustomRetryPolicy(); String getSdkModeledExceptionBaseFqcn(); String getSdkModeledExceptionBaseClassName(); String getSdkRequestBaseClassName(); String getSdkResponseBaseClassName(); String getFileHeader(); String getSdkBaseResponseFqcn(); @JsonIgnore List<OperationModel> simpleMethodsRequiringTesting(); Map<String, AuthorizerModel> getCustomAuthorizers(); void setCustomAuthorizers(Map<String, AuthorizerModel> customAuthorizers); Optional<OperationModel> getEndpointOperation(); void setEndpointOperation(OperationModel endpointOperation); boolean hasPaginators(); boolean hasWaiters(); boolean containsRequestSigners(); boolean containsRequestEventStreams(); } | IntermediateModel { public ShapeModel getShapeByNameAndC2jName(String shapeName, String shapeC2jName) { for (ShapeModel sm : getShapes().values()) { if (shapeName.equals(sm.getShapeName()) && shapeC2jName.equals(sm.getC2jName())) { return sm; } } throw new IllegalArgumentException("C2J shape " + shapeC2jName + " with shape name " + shapeName + " does not exist in " + "the intermediate model."); } IntermediateModel(); IntermediateModel(Metadata metadata,
Map<String, OperationModel> operations,
Map<String, ShapeModel> shapes,
CustomizationConfig customizationConfig); IntermediateModel(
Metadata metadata,
Map<String, OperationModel> operations,
Map<String, ShapeModel> shapes,
CustomizationConfig customizationConfig,
OperationModel endpointOperation,
Map<String, AuthorizerModel> customAuthorizers,
Map<String, PaginatorDefinition> paginators,
NamingStrategy namingStrategy,
Map<String, WaiterDefinition> waiters); Metadata getMetadata(); void setMetadata(Metadata metadata); Map<String, OperationModel> getOperations(); void setOperations(Map<String, OperationModel> operations); OperationModel getOperation(String operationName); Map<String, ShapeModel> getShapes(); void setShapes(Map<String, ShapeModel> shapes); ShapeModel getShapeByNameAndC2jName(String shapeName, String shapeC2jName); CustomizationConfig getCustomizationConfig(); void setCustomizationConfig(CustomizationConfig customizationConfig); Map<String, PaginatorDefinition> getPaginators(); Map<String, WaiterDefinition> getWaiters(); void setPaginators(Map<String, PaginatorDefinition> paginators); NamingStrategy getNamingStrategy(); void setNamingStrategy(NamingStrategy namingStrategy); String getCustomRetryPolicy(); String getSdkModeledExceptionBaseFqcn(); String getSdkModeledExceptionBaseClassName(); String getSdkRequestBaseClassName(); String getSdkResponseBaseClassName(); String getFileHeader(); String getSdkBaseResponseFqcn(); @JsonIgnore List<OperationModel> simpleMethodsRequiringTesting(); Map<String, AuthorizerModel> getCustomAuthorizers(); void setCustomAuthorizers(Map<String, AuthorizerModel> customAuthorizers); Optional<OperationModel> getEndpointOperation(); void setEndpointOperation(OperationModel endpointOperation); boolean hasPaginators(); boolean hasWaiters(); boolean containsRequestSigners(); boolean containsRequestEventStreams(); } |
@Test public void getShapeByNameAndC2jNameVerifiesC2JName() { final File modelFile = new File(IntermediateModelTest.class .getResource("../../poet/client/c2j/shared-output/service-2.json").getFile()); IntermediateModel testModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.loadModel(ServiceModel.class, modelFile)) .customizationConfig(CustomizationConfig.create()) .build()) .build(); assertThatThrownBy(() -> testModel.getShapeByNameAndC2jName("PingResponse", "AnyShape")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("C2J shape AnyShape with shape name PingResponse does not exist in the intermediate model."); } | public ShapeModel getShapeByNameAndC2jName(String shapeName, String shapeC2jName) { for (ShapeModel sm : getShapes().values()) { if (shapeName.equals(sm.getShapeName()) && shapeC2jName.equals(sm.getC2jName())) { return sm; } } throw new IllegalArgumentException("C2J shape " + shapeC2jName + " with shape name " + shapeName + " does not exist in " + "the intermediate model."); } | IntermediateModel { public ShapeModel getShapeByNameAndC2jName(String shapeName, String shapeC2jName) { for (ShapeModel sm : getShapes().values()) { if (shapeName.equals(sm.getShapeName()) && shapeC2jName.equals(sm.getC2jName())) { return sm; } } throw new IllegalArgumentException("C2J shape " + shapeC2jName + " with shape name " + shapeName + " does not exist in " + "the intermediate model."); } } | IntermediateModel { public ShapeModel getShapeByNameAndC2jName(String shapeName, String shapeC2jName) { for (ShapeModel sm : getShapes().values()) { if (shapeName.equals(sm.getShapeName()) && shapeC2jName.equals(sm.getC2jName())) { return sm; } } throw new IllegalArgumentException("C2J shape " + shapeC2jName + " with shape name " + shapeName + " does not exist in " + "the intermediate model."); } IntermediateModel(); IntermediateModel(Metadata metadata,
Map<String, OperationModel> operations,
Map<String, ShapeModel> shapes,
CustomizationConfig customizationConfig); IntermediateModel(
Metadata metadata,
Map<String, OperationModel> operations,
Map<String, ShapeModel> shapes,
CustomizationConfig customizationConfig,
OperationModel endpointOperation,
Map<String, AuthorizerModel> customAuthorizers,
Map<String, PaginatorDefinition> paginators,
NamingStrategy namingStrategy,
Map<String, WaiterDefinition> waiters); } | IntermediateModel { public ShapeModel getShapeByNameAndC2jName(String shapeName, String shapeC2jName) { for (ShapeModel sm : getShapes().values()) { if (shapeName.equals(sm.getShapeName()) && shapeC2jName.equals(sm.getC2jName())) { return sm; } } throw new IllegalArgumentException("C2J shape " + shapeC2jName + " with shape name " + shapeName + " does not exist in " + "the intermediate model."); } IntermediateModel(); IntermediateModel(Metadata metadata,
Map<String, OperationModel> operations,
Map<String, ShapeModel> shapes,
CustomizationConfig customizationConfig); IntermediateModel(
Metadata metadata,
Map<String, OperationModel> operations,
Map<String, ShapeModel> shapes,
CustomizationConfig customizationConfig,
OperationModel endpointOperation,
Map<String, AuthorizerModel> customAuthorizers,
Map<String, PaginatorDefinition> paginators,
NamingStrategy namingStrategy,
Map<String, WaiterDefinition> waiters); Metadata getMetadata(); void setMetadata(Metadata metadata); Map<String, OperationModel> getOperations(); void setOperations(Map<String, OperationModel> operations); OperationModel getOperation(String operationName); Map<String, ShapeModel> getShapes(); void setShapes(Map<String, ShapeModel> shapes); ShapeModel getShapeByNameAndC2jName(String shapeName, String shapeC2jName); CustomizationConfig getCustomizationConfig(); void setCustomizationConfig(CustomizationConfig customizationConfig); Map<String, PaginatorDefinition> getPaginators(); Map<String, WaiterDefinition> getWaiters(); void setPaginators(Map<String, PaginatorDefinition> paginators); NamingStrategy getNamingStrategy(); void setNamingStrategy(NamingStrategy namingStrategy); String getCustomRetryPolicy(); String getSdkModeledExceptionBaseFqcn(); String getSdkModeledExceptionBaseClassName(); String getSdkRequestBaseClassName(); String getSdkResponseBaseClassName(); String getFileHeader(); String getSdkBaseResponseFqcn(); @JsonIgnore List<OperationModel> simpleMethodsRequiringTesting(); Map<String, AuthorizerModel> getCustomAuthorizers(); void setCustomAuthorizers(Map<String, AuthorizerModel> customAuthorizers); Optional<OperationModel> getEndpointOperation(); void setEndpointOperation(OperationModel endpointOperation); boolean hasPaginators(); boolean hasWaiters(); boolean containsRequestSigners(); boolean containsRequestEventStreams(); } | IntermediateModel { public ShapeModel getShapeByNameAndC2jName(String shapeName, String shapeC2jName) { for (ShapeModel sm : getShapes().values()) { if (shapeName.equals(sm.getShapeName()) && shapeC2jName.equals(sm.getC2jName())) { return sm; } } throw new IllegalArgumentException("C2J shape " + shapeC2jName + " with shape name " + shapeName + " does not exist in " + "the intermediate model."); } IntermediateModel(); IntermediateModel(Metadata metadata,
Map<String, OperationModel> operations,
Map<String, ShapeModel> shapes,
CustomizationConfig customizationConfig); IntermediateModel(
Metadata metadata,
Map<String, OperationModel> operations,
Map<String, ShapeModel> shapes,
CustomizationConfig customizationConfig,
OperationModel endpointOperation,
Map<String, AuthorizerModel> customAuthorizers,
Map<String, PaginatorDefinition> paginators,
NamingStrategy namingStrategy,
Map<String, WaiterDefinition> waiters); Metadata getMetadata(); void setMetadata(Metadata metadata); Map<String, OperationModel> getOperations(); void setOperations(Map<String, OperationModel> operations); OperationModel getOperation(String operationName); Map<String, ShapeModel> getShapes(); void setShapes(Map<String, ShapeModel> shapes); ShapeModel getShapeByNameAndC2jName(String shapeName, String shapeC2jName); CustomizationConfig getCustomizationConfig(); void setCustomizationConfig(CustomizationConfig customizationConfig); Map<String, PaginatorDefinition> getPaginators(); Map<String, WaiterDefinition> getWaiters(); void setPaginators(Map<String, PaginatorDefinition> paginators); NamingStrategy getNamingStrategy(); void setNamingStrategy(NamingStrategy namingStrategy); String getCustomRetryPolicy(); String getSdkModeledExceptionBaseFqcn(); String getSdkModeledExceptionBaseClassName(); String getSdkRequestBaseClassName(); String getSdkResponseBaseClassName(); String getFileHeader(); String getSdkBaseResponseFqcn(); @JsonIgnore List<OperationModel> simpleMethodsRequiringTesting(); Map<String, AuthorizerModel> getCustomAuthorizers(); void setCustomAuthorizers(Map<String, AuthorizerModel> customAuthorizers); Optional<OperationModel> getEndpointOperation(); void setEndpointOperation(OperationModel endpointOperation); boolean hasPaginators(); boolean hasWaiters(); boolean containsRequestSigners(); boolean containsRequestEventStreams(); } |
@Test public void canConvertStringsWithNonAlphasToClassNames() { String anInvalidClassName = "a phrase-With_other.delimiters"; assertThat(strat.getJavaClassName(anInvalidClassName)).isEqualTo("APhraseWithOtherDelimiters"); } | @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } |
@Test public void canConvertAuthorizerStartingWithNumber() { String anInvalidClassName = "35-authorizer-implementation"; assertThat(strat.getAuthorizerClassName(anInvalidClassName)).isEqualTo("I35AuthorizerImplementation"); } | @Override public String getAuthorizerClassName(String shapeName) { String converted = getJavaClassName(shapeName); if (converted.length() > 0 && !Character.isLetter(converted.charAt(0))) { return AUTHORIZER_NAME_PREFIX + converted; } return converted; } | DefaultNamingStrategy implements NamingStrategy { @Override public String getAuthorizerClassName(String shapeName) { String converted = getJavaClassName(shapeName); if (converted.length() > 0 && !Character.isLetter(converted.charAt(0))) { return AUTHORIZER_NAME_PREFIX + converted; } return converted; } } | DefaultNamingStrategy implements NamingStrategy { @Override public String getAuthorizerClassName(String shapeName) { String converted = getJavaClassName(shapeName); if (converted.length() > 0 && !Character.isLetter(converted.charAt(0))) { return AUTHORIZER_NAME_PREFIX + converted; } return converted; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getAuthorizerClassName(String shapeName) { String converted = getJavaClassName(shapeName); if (converted.length() > 0 && !Character.isLetter(converted.charAt(0))) { return AUTHORIZER_NAME_PREFIX + converted; } return converted; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getAuthorizerClassName(String shapeName) { String converted = getJavaClassName(shapeName); if (converted.length() > 0 && !Character.isLetter(converted.charAt(0))) { return AUTHORIZER_NAME_PREFIX + converted; } return converted; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } |
@Test public void test_GetFluentSetterMethodName_NoEnum() { when(serviceModel.getShapes()).thenReturn(mockShapeMap); when(mockShape.getEnumValues()).thenReturn(null); when(mockShape.getType()).thenReturn("foo"); assertThat(strat.getFluentSetterMethodName("AwesomeMethod", mockParentShape, mockShape)).isEqualTo("awesomeMethod"); } | @Override public String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape) { String setterMethodName = Utils.unCapitalize(memberName); setterMethodName = rewriteInvalidMemberName(setterMethodName, parentShape); if (Utils.isOrContainsEnumShape(shape, serviceModel.getShapes()) && (Utils.isListShape(shape) || Utils.isMapShape(shape))) { setterMethodName += "WithStrings"; } return setterMethodName; } | DefaultNamingStrategy implements NamingStrategy { @Override public String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape) { String setterMethodName = Utils.unCapitalize(memberName); setterMethodName = rewriteInvalidMemberName(setterMethodName, parentShape); if (Utils.isOrContainsEnumShape(shape, serviceModel.getShapes()) && (Utils.isListShape(shape) || Utils.isMapShape(shape))) { setterMethodName += "WithStrings"; } return setterMethodName; } } | DefaultNamingStrategy implements NamingStrategy { @Override public String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape) { String setterMethodName = Utils.unCapitalize(memberName); setterMethodName = rewriteInvalidMemberName(setterMethodName, parentShape); if (Utils.isOrContainsEnumShape(shape, serviceModel.getShapes()) && (Utils.isListShape(shape) || Utils.isMapShape(shape))) { setterMethodName += "WithStrings"; } return setterMethodName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape) { String setterMethodName = Utils.unCapitalize(memberName); setterMethodName = rewriteInvalidMemberName(setterMethodName, parentShape); if (Utils.isOrContainsEnumShape(shape, serviceModel.getShapes()) && (Utils.isListShape(shape) || Utils.isMapShape(shape))) { setterMethodName += "WithStrings"; } return setterMethodName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape) { String setterMethodName = Utils.unCapitalize(memberName); setterMethodName = rewriteInvalidMemberName(setterMethodName, parentShape); if (Utils.isOrContainsEnumShape(shape, serviceModel.getShapes()) && (Utils.isListShape(shape) || Utils.isMapShape(shape))) { setterMethodName += "WithStrings"; } return setterMethodName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } |
@Test public void test_GetFluentSetterMethodName_NoEnum_WithList() { when(serviceModel.getShapes()).thenReturn(mockShapeMap); when(mockShapeMap.get(eq("MockShape"))).thenReturn(mockShape); when(mockShapeMap.get(eq("MockStringShape"))).thenReturn(mockStringShape); when(mockShape.getEnumValues()).thenReturn(null); when(mockShape.getType()).thenReturn("list"); when(mockShape.getListMember()).thenReturn(member); when(mockStringShape.getEnumValues()).thenReturn(null); when(mockStringShape.getType()).thenReturn("string"); when(member.getShape()).thenReturn("MockStringShape"); assertThat(strat.getFluentSetterMethodName("AwesomeMethod", mockParentShape, mockShape)).isEqualTo("awesomeMethod"); } | @Override public String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape) { String setterMethodName = Utils.unCapitalize(memberName); setterMethodName = rewriteInvalidMemberName(setterMethodName, parentShape); if (Utils.isOrContainsEnumShape(shape, serviceModel.getShapes()) && (Utils.isListShape(shape) || Utils.isMapShape(shape))) { setterMethodName += "WithStrings"; } return setterMethodName; } | DefaultNamingStrategy implements NamingStrategy { @Override public String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape) { String setterMethodName = Utils.unCapitalize(memberName); setterMethodName = rewriteInvalidMemberName(setterMethodName, parentShape); if (Utils.isOrContainsEnumShape(shape, serviceModel.getShapes()) && (Utils.isListShape(shape) || Utils.isMapShape(shape))) { setterMethodName += "WithStrings"; } return setterMethodName; } } | DefaultNamingStrategy implements NamingStrategy { @Override public String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape) { String setterMethodName = Utils.unCapitalize(memberName); setterMethodName = rewriteInvalidMemberName(setterMethodName, parentShape); if (Utils.isOrContainsEnumShape(shape, serviceModel.getShapes()) && (Utils.isListShape(shape) || Utils.isMapShape(shape))) { setterMethodName += "WithStrings"; } return setterMethodName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape) { String setterMethodName = Utils.unCapitalize(memberName); setterMethodName = rewriteInvalidMemberName(setterMethodName, parentShape); if (Utils.isOrContainsEnumShape(shape, serviceModel.getShapes()) && (Utils.isListShape(shape) || Utils.isMapShape(shape))) { setterMethodName += "WithStrings"; } return setterMethodName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape) { String setterMethodName = Utils.unCapitalize(memberName); setterMethodName = rewriteInvalidMemberName(setterMethodName, parentShape); if (Utils.isOrContainsEnumShape(shape, serviceModel.getShapes()) && (Utils.isListShape(shape) || Utils.isMapShape(shape))) { setterMethodName += "WithStrings"; } return setterMethodName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } |
@Test public void afterUnmarshalling_putObjectRequest_shouldValidateChecksum() { SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader(); PutObjectResponse response = PutObjectResponse.builder() .eTag(VALID_CHECKSUM) .build(); PutObjectRequest putObjectRequest = PutObjectRequest.builder() .build(); SdkHttpRequest sdkHttpRequest = SdkHttpFullRequest.builder() .uri(URI.create("http: .method(SdkHttpMethod.PUT) .build(); Context.AfterUnmarshalling afterUnmarshallingContext = InterceptorTestUtils.afterUnmarshallingContext(putObjectRequest, sdkHttpRequest, response, sdkHttpResponse); interceptor.afterUnmarshalling(afterUnmarshallingContext, getExecutionAttributesWithChecksum()); } | @Override public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) { boolean recordingChecksum = Boolean.TRUE.equals(executionAttributes.getAttribute(ASYNC_RECORDING_CHECKSUM)); boolean responseChecksumIsValid = responseChecksumIsValid(context.httpResponse()); if (recordingChecksum && responseChecksumIsValid) { validatePutObjectChecksum((PutObjectResponse) context.response(), executionAttributes); } } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) { boolean recordingChecksum = Boolean.TRUE.equals(executionAttributes.getAttribute(ASYNC_RECORDING_CHECKSUM)); boolean responseChecksumIsValid = responseChecksumIsValid(context.httpResponse()); if (recordingChecksum && responseChecksumIsValid) { validatePutObjectChecksum((PutObjectResponse) context.response(), executionAttributes); } } } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) { boolean recordingChecksum = Boolean.TRUE.equals(executionAttributes.getAttribute(ASYNC_RECORDING_CHECKSUM)); boolean responseChecksumIsValid = responseChecksumIsValid(context.httpResponse()); if (recordingChecksum && responseChecksumIsValid) { validatePutObjectChecksum((PutObjectResponse) context.response(), executionAttributes); } } } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) { boolean recordingChecksum = Boolean.TRUE.equals(executionAttributes.getAttribute(ASYNC_RECORDING_CHECKSUM)); boolean responseChecksumIsValid = responseChecksumIsValid(context.httpResponse()); if (recordingChecksum && responseChecksumIsValid) { validatePutObjectChecksum((PutObjectResponse) context.response(), executionAttributes); } } @Override Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) { boolean recordingChecksum = Boolean.TRUE.equals(executionAttributes.getAttribute(ASYNC_RECORDING_CHECKSUM)); boolean responseChecksumIsValid = responseChecksumIsValid(context.httpResponse()); if (recordingChecksum && responseChecksumIsValid) { validatePutObjectChecksum((PutObjectResponse) context.response(), executionAttributes); } } @Override Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); } |
@Test public void test_GetFluentSetterMethodName_WithEnumShape_NoListOrMap() { when(serviceModel.getShapes()).thenReturn(mockShapeMap); when(mockShapeMap.get(any())).thenReturn(mockShape); when(mockShape.getEnumValues()).thenReturn(new ArrayList<>()); when(mockShape.getType()).thenReturn("foo"); assertThat(strat.getFluentSetterMethodName("AwesomeMethod", mockParentShape, mockShape)).isEqualTo("awesomeMethod"); } | @Override public String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape) { String setterMethodName = Utils.unCapitalize(memberName); setterMethodName = rewriteInvalidMemberName(setterMethodName, parentShape); if (Utils.isOrContainsEnumShape(shape, serviceModel.getShapes()) && (Utils.isListShape(shape) || Utils.isMapShape(shape))) { setterMethodName += "WithStrings"; } return setterMethodName; } | DefaultNamingStrategy implements NamingStrategy { @Override public String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape) { String setterMethodName = Utils.unCapitalize(memberName); setterMethodName = rewriteInvalidMemberName(setterMethodName, parentShape); if (Utils.isOrContainsEnumShape(shape, serviceModel.getShapes()) && (Utils.isListShape(shape) || Utils.isMapShape(shape))) { setterMethodName += "WithStrings"; } return setterMethodName; } } | DefaultNamingStrategy implements NamingStrategy { @Override public String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape) { String setterMethodName = Utils.unCapitalize(memberName); setterMethodName = rewriteInvalidMemberName(setterMethodName, parentShape); if (Utils.isOrContainsEnumShape(shape, serviceModel.getShapes()) && (Utils.isListShape(shape) || Utils.isMapShape(shape))) { setterMethodName += "WithStrings"; } return setterMethodName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape) { String setterMethodName = Utils.unCapitalize(memberName); setterMethodName = rewriteInvalidMemberName(setterMethodName, parentShape); if (Utils.isOrContainsEnumShape(shape, serviceModel.getShapes()) && (Utils.isListShape(shape) || Utils.isMapShape(shape))) { setterMethodName += "WithStrings"; } return setterMethodName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape) { String setterMethodName = Utils.unCapitalize(memberName); setterMethodName = rewriteInvalidMemberName(setterMethodName, parentShape); if (Utils.isOrContainsEnumShape(shape, serviceModel.getShapes()) && (Utils.isListShape(shape) || Utils.isMapShape(shape))) { setterMethodName += "WithStrings"; } return setterMethodName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } |
@Test public void test_GetFluentSetterMethodName_WithEnumShape_WithList() { when(serviceModel.getShapes()).thenReturn(mockShapeMap); when(mockShapeMap.get(eq("MockShape"))).thenReturn(mockShape); when(mockShapeMap.get(eq("MockStringShape"))).thenReturn(mockStringShape); when(mockShape.getEnumValues()).thenReturn(null); when(mockShape.getType()).thenReturn("list"); when(mockShape.getListMember()).thenReturn(member); when(mockStringShape.getEnumValues()).thenReturn(Arrays.asList("Enum1", "Enum2")); when(mockStringShape.getType()).thenReturn("string"); when(member.getShape()).thenReturn("MockStringShape"); assertThat(strat.getFluentSetterMethodName("AwesomeMethod", mockParentShape, mockShape)).isEqualTo("awesomeMethodWithStrings"); } | @Override public String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape) { String setterMethodName = Utils.unCapitalize(memberName); setterMethodName = rewriteInvalidMemberName(setterMethodName, parentShape); if (Utils.isOrContainsEnumShape(shape, serviceModel.getShapes()) && (Utils.isListShape(shape) || Utils.isMapShape(shape))) { setterMethodName += "WithStrings"; } return setterMethodName; } | DefaultNamingStrategy implements NamingStrategy { @Override public String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape) { String setterMethodName = Utils.unCapitalize(memberName); setterMethodName = rewriteInvalidMemberName(setterMethodName, parentShape); if (Utils.isOrContainsEnumShape(shape, serviceModel.getShapes()) && (Utils.isListShape(shape) || Utils.isMapShape(shape))) { setterMethodName += "WithStrings"; } return setterMethodName; } } | DefaultNamingStrategy implements NamingStrategy { @Override public String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape) { String setterMethodName = Utils.unCapitalize(memberName); setterMethodName = rewriteInvalidMemberName(setterMethodName, parentShape); if (Utils.isOrContainsEnumShape(shape, serviceModel.getShapes()) && (Utils.isListShape(shape) || Utils.isMapShape(shape))) { setterMethodName += "WithStrings"; } return setterMethodName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape) { String setterMethodName = Utils.unCapitalize(memberName); setterMethodName = rewriteInvalidMemberName(setterMethodName, parentShape); if (Utils.isOrContainsEnumShape(shape, serviceModel.getShapes()) && (Utils.isListShape(shape) || Utils.isMapShape(shape))) { setterMethodName += "WithStrings"; } return setterMethodName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape) { String setterMethodName = Utils.unCapitalize(memberName); setterMethodName = rewriteInvalidMemberName(setterMethodName, parentShape); if (Utils.isOrContainsEnumShape(shape, serviceModel.getShapes()) && (Utils.isListShape(shape) || Utils.isMapShape(shape))) { setterMethodName += "WithStrings"; } return setterMethodName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } |
@Test public void getServiceName_Uses_ServiceId() { when(serviceModel.getMetadata()).thenReturn(serviceMetadata); when(serviceMetadata.getServiceId()).thenReturn("Foo"); when(serviceMetadata.getServiceAbbreviation()).thenReturn("Abbr"); when(serviceMetadata.getServiceFullName()).thenReturn("Foo Service"); assertThat(strat.getServiceName()).isEqualTo("Foo"); } | @Override public String getServiceName() { String baseName = Stream.of(serviceModel.getMetadata().getServiceId()) .filter(Objects::nonNull) .filter(s -> !s.trim().isEmpty()) .findFirst() .orElseThrow(() -> new IllegalStateException("ServiceId is missing in the c2j model.")); baseName = pascalCase(baseName); baseName = Utils.removeLeading(baseName, "Amazon"); baseName = Utils.removeLeading(baseName, "Aws"); baseName = Utils.removeTrailing(baseName, "Service"); return baseName; } | DefaultNamingStrategy implements NamingStrategy { @Override public String getServiceName() { String baseName = Stream.of(serviceModel.getMetadata().getServiceId()) .filter(Objects::nonNull) .filter(s -> !s.trim().isEmpty()) .findFirst() .orElseThrow(() -> new IllegalStateException("ServiceId is missing in the c2j model.")); baseName = pascalCase(baseName); baseName = Utils.removeLeading(baseName, "Amazon"); baseName = Utils.removeLeading(baseName, "Aws"); baseName = Utils.removeTrailing(baseName, "Service"); return baseName; } } | DefaultNamingStrategy implements NamingStrategy { @Override public String getServiceName() { String baseName = Stream.of(serviceModel.getMetadata().getServiceId()) .filter(Objects::nonNull) .filter(s -> !s.trim().isEmpty()) .findFirst() .orElseThrow(() -> new IllegalStateException("ServiceId is missing in the c2j model.")); baseName = pascalCase(baseName); baseName = Utils.removeLeading(baseName, "Amazon"); baseName = Utils.removeLeading(baseName, "Aws"); baseName = Utils.removeTrailing(baseName, "Service"); return baseName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getServiceName() { String baseName = Stream.of(serviceModel.getMetadata().getServiceId()) .filter(Objects::nonNull) .filter(s -> !s.trim().isEmpty()) .findFirst() .orElseThrow(() -> new IllegalStateException("ServiceId is missing in the c2j model.")); baseName = pascalCase(baseName); baseName = Utils.removeLeading(baseName, "Amazon"); baseName = Utils.removeLeading(baseName, "Aws"); baseName = Utils.removeTrailing(baseName, "Service"); return baseName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getServiceName() { String baseName = Stream.of(serviceModel.getMetadata().getServiceId()) .filter(Objects::nonNull) .filter(s -> !s.trim().isEmpty()) .findFirst() .orElseThrow(() -> new IllegalStateException("ServiceId is missing in the c2j model.")); baseName = pascalCase(baseName); baseName = Utils.removeLeading(baseName, "Amazon"); baseName = Utils.removeLeading(baseName, "Aws"); baseName = Utils.removeTrailing(baseName, "Service"); return baseName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } |
@Test (expected = IllegalStateException.class) public void getServiceName_ThrowsException_WhenServiceIdIsNull() { when(serviceModel.getMetadata()).thenReturn(serviceMetadata); when(serviceMetadata.getServiceId()).thenReturn(null); when(serviceMetadata.getServiceAbbreviation()).thenReturn("Abbr"); when(serviceMetadata.getServiceFullName()).thenReturn("Foo Service"); strat.getServiceName(); } | @Override public String getServiceName() { String baseName = Stream.of(serviceModel.getMetadata().getServiceId()) .filter(Objects::nonNull) .filter(s -> !s.trim().isEmpty()) .findFirst() .orElseThrow(() -> new IllegalStateException("ServiceId is missing in the c2j model.")); baseName = pascalCase(baseName); baseName = Utils.removeLeading(baseName, "Amazon"); baseName = Utils.removeLeading(baseName, "Aws"); baseName = Utils.removeTrailing(baseName, "Service"); return baseName; } | DefaultNamingStrategy implements NamingStrategy { @Override public String getServiceName() { String baseName = Stream.of(serviceModel.getMetadata().getServiceId()) .filter(Objects::nonNull) .filter(s -> !s.trim().isEmpty()) .findFirst() .orElseThrow(() -> new IllegalStateException("ServiceId is missing in the c2j model.")); baseName = pascalCase(baseName); baseName = Utils.removeLeading(baseName, "Amazon"); baseName = Utils.removeLeading(baseName, "Aws"); baseName = Utils.removeTrailing(baseName, "Service"); return baseName; } } | DefaultNamingStrategy implements NamingStrategy { @Override public String getServiceName() { String baseName = Stream.of(serviceModel.getMetadata().getServiceId()) .filter(Objects::nonNull) .filter(s -> !s.trim().isEmpty()) .findFirst() .orElseThrow(() -> new IllegalStateException("ServiceId is missing in the c2j model.")); baseName = pascalCase(baseName); baseName = Utils.removeLeading(baseName, "Amazon"); baseName = Utils.removeLeading(baseName, "Aws"); baseName = Utils.removeTrailing(baseName, "Service"); return baseName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getServiceName() { String baseName = Stream.of(serviceModel.getMetadata().getServiceId()) .filter(Objects::nonNull) .filter(s -> !s.trim().isEmpty()) .findFirst() .orElseThrow(() -> new IllegalStateException("ServiceId is missing in the c2j model.")); baseName = pascalCase(baseName); baseName = Utils.removeLeading(baseName, "Amazon"); baseName = Utils.removeLeading(baseName, "Aws"); baseName = Utils.removeTrailing(baseName, "Service"); return baseName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getServiceName() { String baseName = Stream.of(serviceModel.getMetadata().getServiceId()) .filter(Objects::nonNull) .filter(s -> !s.trim().isEmpty()) .findFirst() .orElseThrow(() -> new IllegalStateException("ServiceId is missing in the c2j model.")); baseName = pascalCase(baseName); baseName = Utils.removeLeading(baseName, "Amazon"); baseName = Utils.removeLeading(baseName, "Aws"); baseName = Utils.removeTrailing(baseName, "Service"); return baseName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } |
@Test (expected = IllegalStateException.class) public void getServiceName_ThrowsException_WhenServiceIdIsEmpty() { when(serviceModel.getMetadata()).thenReturn(serviceMetadata); when(serviceMetadata.getServiceId()).thenReturn(""); when(serviceMetadata.getServiceAbbreviation()).thenReturn("Abbr"); when(serviceMetadata.getServiceFullName()).thenReturn("Foo Service"); strat.getServiceName(); } | @Override public String getServiceName() { String baseName = Stream.of(serviceModel.getMetadata().getServiceId()) .filter(Objects::nonNull) .filter(s -> !s.trim().isEmpty()) .findFirst() .orElseThrow(() -> new IllegalStateException("ServiceId is missing in the c2j model.")); baseName = pascalCase(baseName); baseName = Utils.removeLeading(baseName, "Amazon"); baseName = Utils.removeLeading(baseName, "Aws"); baseName = Utils.removeTrailing(baseName, "Service"); return baseName; } | DefaultNamingStrategy implements NamingStrategy { @Override public String getServiceName() { String baseName = Stream.of(serviceModel.getMetadata().getServiceId()) .filter(Objects::nonNull) .filter(s -> !s.trim().isEmpty()) .findFirst() .orElseThrow(() -> new IllegalStateException("ServiceId is missing in the c2j model.")); baseName = pascalCase(baseName); baseName = Utils.removeLeading(baseName, "Amazon"); baseName = Utils.removeLeading(baseName, "Aws"); baseName = Utils.removeTrailing(baseName, "Service"); return baseName; } } | DefaultNamingStrategy implements NamingStrategy { @Override public String getServiceName() { String baseName = Stream.of(serviceModel.getMetadata().getServiceId()) .filter(Objects::nonNull) .filter(s -> !s.trim().isEmpty()) .findFirst() .orElseThrow(() -> new IllegalStateException("ServiceId is missing in the c2j model.")); baseName = pascalCase(baseName); baseName = Utils.removeLeading(baseName, "Amazon"); baseName = Utils.removeLeading(baseName, "Aws"); baseName = Utils.removeTrailing(baseName, "Service"); return baseName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getServiceName() { String baseName = Stream.of(serviceModel.getMetadata().getServiceId()) .filter(Objects::nonNull) .filter(s -> !s.trim().isEmpty()) .findFirst() .orElseThrow(() -> new IllegalStateException("ServiceId is missing in the c2j model.")); baseName = pascalCase(baseName); baseName = Utils.removeLeading(baseName, "Amazon"); baseName = Utils.removeLeading(baseName, "Aws"); baseName = Utils.removeTrailing(baseName, "Service"); return baseName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getServiceName() { String baseName = Stream.of(serviceModel.getMetadata().getServiceId()) .filter(Objects::nonNull) .filter(s -> !s.trim().isEmpty()) .findFirst() .orElseThrow(() -> new IllegalStateException("ServiceId is missing in the c2j model.")); baseName = pascalCase(baseName); baseName = Utils.removeLeading(baseName, "Amazon"); baseName = Utils.removeLeading(baseName, "Aws"); baseName = Utils.removeTrailing(baseName, "Service"); return baseName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } |
@Test (expected = IllegalStateException.class) public void getServiceName_ThrowsException_WhenServiceIdHasWhiteSpace() { when(serviceModel.getMetadata()).thenReturn(serviceMetadata); when(serviceMetadata.getServiceId()).thenReturn(" "); when(serviceMetadata.getServiceAbbreviation()).thenReturn("Abbr"); when(serviceMetadata.getServiceFullName()).thenReturn("Foo Service"); strat.getServiceName(); } | @Override public String getServiceName() { String baseName = Stream.of(serviceModel.getMetadata().getServiceId()) .filter(Objects::nonNull) .filter(s -> !s.trim().isEmpty()) .findFirst() .orElseThrow(() -> new IllegalStateException("ServiceId is missing in the c2j model.")); baseName = pascalCase(baseName); baseName = Utils.removeLeading(baseName, "Amazon"); baseName = Utils.removeLeading(baseName, "Aws"); baseName = Utils.removeTrailing(baseName, "Service"); return baseName; } | DefaultNamingStrategy implements NamingStrategy { @Override public String getServiceName() { String baseName = Stream.of(serviceModel.getMetadata().getServiceId()) .filter(Objects::nonNull) .filter(s -> !s.trim().isEmpty()) .findFirst() .orElseThrow(() -> new IllegalStateException("ServiceId is missing in the c2j model.")); baseName = pascalCase(baseName); baseName = Utils.removeLeading(baseName, "Amazon"); baseName = Utils.removeLeading(baseName, "Aws"); baseName = Utils.removeTrailing(baseName, "Service"); return baseName; } } | DefaultNamingStrategy implements NamingStrategy { @Override public String getServiceName() { String baseName = Stream.of(serviceModel.getMetadata().getServiceId()) .filter(Objects::nonNull) .filter(s -> !s.trim().isEmpty()) .findFirst() .orElseThrow(() -> new IllegalStateException("ServiceId is missing in the c2j model.")); baseName = pascalCase(baseName); baseName = Utils.removeLeading(baseName, "Amazon"); baseName = Utils.removeLeading(baseName, "Aws"); baseName = Utils.removeTrailing(baseName, "Service"); return baseName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getServiceName() { String baseName = Stream.of(serviceModel.getMetadata().getServiceId()) .filter(Objects::nonNull) .filter(s -> !s.trim().isEmpty()) .findFirst() .orElseThrow(() -> new IllegalStateException("ServiceId is missing in the c2j model.")); baseName = pascalCase(baseName); baseName = Utils.removeLeading(baseName, "Amazon"); baseName = Utils.removeLeading(baseName, "Aws"); baseName = Utils.removeTrailing(baseName, "Service"); return baseName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getServiceName() { String baseName = Stream.of(serviceModel.getMetadata().getServiceId()) .filter(Objects::nonNull) .filter(s -> !s.trim().isEmpty()) .findFirst() .orElseThrow(() -> new IllegalStateException("ServiceId is missing in the c2j model.")); baseName = pascalCase(baseName); baseName = Utils.removeLeading(baseName, "Amazon"); baseName = Utils.removeLeading(baseName, "Aws"); baseName = Utils.removeTrailing(baseName, "Service"); return baseName; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } |
@Test public void getSdkFieldFieldName_SingleWord() { assertThat(strat.getSdkFieldFieldName(new MemberModel().withName("foo"))) .isEqualTo("FOO_FIELD"); } | @Override public String getSdkFieldFieldName(MemberModel memberModel) { return screamCase(memberModel.getName()) + "_FIELD"; } | DefaultNamingStrategy implements NamingStrategy { @Override public String getSdkFieldFieldName(MemberModel memberModel) { return screamCase(memberModel.getName()) + "_FIELD"; } } | DefaultNamingStrategy implements NamingStrategy { @Override public String getSdkFieldFieldName(MemberModel memberModel) { return screamCase(memberModel.getName()) + "_FIELD"; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getSdkFieldFieldName(MemberModel memberModel) { return screamCase(memberModel.getName()) + "_FIELD"; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getSdkFieldFieldName(MemberModel memberModel) { return screamCase(memberModel.getName()) + "_FIELD"; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } |
@Test public void getSdkFieldFieldName_CamalCaseConvertedToScreamCase() { assertThat(strat.getSdkFieldFieldName(new MemberModel().withName("fooBar"))) .isEqualTo("FOO_BAR_FIELD"); } | @Override public String getSdkFieldFieldName(MemberModel memberModel) { return screamCase(memberModel.getName()) + "_FIELD"; } | DefaultNamingStrategy implements NamingStrategy { @Override public String getSdkFieldFieldName(MemberModel memberModel) { return screamCase(memberModel.getName()) + "_FIELD"; } } | DefaultNamingStrategy implements NamingStrategy { @Override public String getSdkFieldFieldName(MemberModel memberModel) { return screamCase(memberModel.getName()) + "_FIELD"; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getSdkFieldFieldName(MemberModel memberModel) { return screamCase(memberModel.getName()) + "_FIELD"; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getSdkFieldFieldName(MemberModel memberModel) { return screamCase(memberModel.getName()) + "_FIELD"; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } |
@Test public void getSdkFieldFieldName_PascalCaseConvertedToScreamCase() { assertThat(strat.getSdkFieldFieldName(new MemberModel().withName("FooBar"))) .isEqualTo("FOO_BAR_FIELD"); } | @Override public String getSdkFieldFieldName(MemberModel memberModel) { return screamCase(memberModel.getName()) + "_FIELD"; } | DefaultNamingStrategy implements NamingStrategy { @Override public String getSdkFieldFieldName(MemberModel memberModel) { return screamCase(memberModel.getName()) + "_FIELD"; } } | DefaultNamingStrategy implements NamingStrategy { @Override public String getSdkFieldFieldName(MemberModel memberModel) { return screamCase(memberModel.getName()) + "_FIELD"; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getSdkFieldFieldName(MemberModel memberModel) { return screamCase(memberModel.getName()) + "_FIELD"; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getSdkFieldFieldName(MemberModel memberModel) { return screamCase(memberModel.getName()) + "_FIELD"; } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } |
@Test public void getJavaClassName_ReturnsSanitizedName_ClassStartingWithUnderscore() { NamingStrategy strategy = new DefaultNamingStrategy(null, null); String javaClassName = strategy.getJavaClassName("_MyClass"); assertThat(javaClassName).isEqualTo("MyClass"); } | @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } |
@Test public void afterUnmarshalling_putObjectRequest_with_SSE_shouldNotValidateChecksum() { SdkHttpResponse sdkHttpResponse = getSdkHttpResponseWithChecksumHeader(); PutObjectResponse response = PutObjectResponse.builder() .eTag(INVALID_CHECKSUM) .build(); PutObjectRequest putObjectRequest = PutObjectRequest.builder().build(); SdkHttpRequest sdkHttpRequest = SdkHttpFullRequest.builder() .putHeader(SERVER_SIDE_ENCRYPTION_HEADER, AWS_KMS.toString()) .putHeader("x-amz-server-side-encryption-aws-kms-key-id", ENABLE_MD5_CHECKSUM_HEADER_VALUE) .uri(URI.create("http: .method(SdkHttpMethod.PUT) .build(); Context.AfterUnmarshalling afterUnmarshallingContext = InterceptorTestUtils.afterUnmarshallingContext(putObjectRequest, sdkHttpRequest, response, sdkHttpResponse); interceptor.afterUnmarshalling(afterUnmarshallingContext, getExecutionAttributesWithChecksum()); } | @Override public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) { boolean recordingChecksum = Boolean.TRUE.equals(executionAttributes.getAttribute(ASYNC_RECORDING_CHECKSUM)); boolean responseChecksumIsValid = responseChecksumIsValid(context.httpResponse()); if (recordingChecksum && responseChecksumIsValid) { validatePutObjectChecksum((PutObjectResponse) context.response(), executionAttributes); } } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) { boolean recordingChecksum = Boolean.TRUE.equals(executionAttributes.getAttribute(ASYNC_RECORDING_CHECKSUM)); boolean responseChecksumIsValid = responseChecksumIsValid(context.httpResponse()); if (recordingChecksum && responseChecksumIsValid) { validatePutObjectChecksum((PutObjectResponse) context.response(), executionAttributes); } } } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) { boolean recordingChecksum = Boolean.TRUE.equals(executionAttributes.getAttribute(ASYNC_RECORDING_CHECKSUM)); boolean responseChecksumIsValid = responseChecksumIsValid(context.httpResponse()); if (recordingChecksum && responseChecksumIsValid) { validatePutObjectChecksum((PutObjectResponse) context.response(), executionAttributes); } } } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) { boolean recordingChecksum = Boolean.TRUE.equals(executionAttributes.getAttribute(ASYNC_RECORDING_CHECKSUM)); boolean responseChecksumIsValid = responseChecksumIsValid(context.httpResponse()); if (recordingChecksum && responseChecksumIsValid) { validatePutObjectChecksum((PutObjectResponse) context.response(), executionAttributes); } } @Override Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); } | AsyncChecksumValidationInterceptor implements ExecutionInterceptor { @Override public void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes) { boolean recordingChecksum = Boolean.TRUE.equals(executionAttributes.getAttribute(ASYNC_RECORDING_CHECKSUM)); boolean responseChecksumIsValid = responseChecksumIsValid(context.httpResponse()); if (recordingChecksum && responseChecksumIsValid) { validatePutObjectChecksum((PutObjectResponse) context.response(), executionAttributes); } } @Override Optional<AsyncRequestBody> modifyAsyncHttpContent(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); @Override Optional<Publisher<ByteBuffer>> modifyAsyncHttpResponseContent(Context.ModifyHttpResponse context,
ExecutionAttributes executionAttributes); @Override void afterUnmarshalling(Context.AfterUnmarshalling context, ExecutionAttributes executionAttributes); } |
@Test public void getJavaClassName_ReturnsSanitizedName_ClassStartingWithDoubleUnderscore() { NamingStrategy strategy = new DefaultNamingStrategy(null, null); String javaClassName = strategy.getJavaClassName("__MyClass"); assertThat(javaClassName).isEqualTo("MyClass"); } | @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } |
@Test public void getJavaClassName_ReturnsSanitizedName_ClassStartingWithDoublePeriods() { NamingStrategy strategy = new DefaultNamingStrategy(null, null); String javaClassName = strategy.getJavaClassName("..MyClass"); assertThat(javaClassName).isEqualTo("MyClass"); } | @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } |
@Test public void getJavaClassName_ReturnsSanitizedName_ClassStartingWithDoubleDashes() { NamingStrategy strategy = new DefaultNamingStrategy(null, null); String javaClassName = strategy.getJavaClassName("--MyClass"); assertThat(javaClassName).isEqualTo("MyClass"); } | @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } |
@Test public void getJavaClassName_ReturnsSanitizedName_DoubleUnderscoresInClass() { NamingStrategy strategy = new DefaultNamingStrategy(null, null); String javaClassName = strategy.getJavaClassName("My__Class"); assertThat(javaClassName).isEqualTo("MyClass"); } | @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } |
@Test public void getJavaClassName_ReturnsSanitizedName_DoublePeriodsInClass() { NamingStrategy strategy = new DefaultNamingStrategy(null, null); String javaClassName = strategy.getJavaClassName("My..Class"); assertThat(javaClassName).isEqualTo("MyClass"); } | @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } |
@Test public void getJavaClassName_ReturnsSanitizedName_DoubleDashesInClass() { NamingStrategy strategy = new DefaultNamingStrategy(null, null); String javaClassName = strategy.getJavaClassName("My--Class"); assertThat(javaClassName).isEqualTo("MyClass"); } | @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } | DefaultNamingStrategy implements NamingStrategy { @Override public String getJavaClassName(String shapeName) { return Arrays.stream(shapeName.split("[._-]|\\W")) .filter(s -> !StringUtils.isEmpty(s)) .map(Utils::capitalize) .collect(joining()); } DefaultNamingStrategy(ServiceModel serviceModel,
CustomizationConfig customizationConfig); @Override String getServiceName(); @Override String getClientPackageName(String serviceName); @Override String getModelPackageName(String serviceName); @Override String getTransformPackageName(String serviceName); @Override String getRequestTransformPackageName(String serviceName); @Override String getPaginatorsPackageName(String serviceName); @Override String getWaitersPackageName(String serviceName); @Override String getSmokeTestPackageName(String serviceName); @Override String getExceptionName(String errorShapeName); @Override String getRequestClassName(String operationName); @Override String getResponseClassName(String operationName); @Override String getVariableName(String name); @Override String getEnumValueName(String enumValue); @Override String getJavaClassName(String shapeName); @Override String getAuthorizerClassName(String shapeName); @Override String getFluentGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumGetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getExistenceCheckMethodName(String memberName, Shape parentShape); @Override String getBeanStyleGetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getBeanStyleSetterMethodName(String memberName, Shape parentShape, Shape c2jShape); @Override String getFluentSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getFluentEnumSetterMethodName(String memberName, Shape parentShape, Shape shape); @Override String getSdkFieldFieldName(MemberModel memberModel); } |
@Test public void testServiceAndShapeNameCollisions() throws Exception { final File modelFile = new File(IntermediateModelBuilderTest.class .getResource("poet/client/c2j/collision/service-2.json").getFile()); IntermediateModel testModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.loadModel(ServiceModel.class, modelFile)) .customizationConfig(CustomizationConfig.create()) .build()) .build(); assertThat(testModel.getShapes().values()) .extracting(ShapeModel::getShapeName) .containsExactlyInAnyOrder("DefaultCollisionException", "DefaultCollisionRequest", "DefaultCollisionResponse"); } | public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOperations(this).constructOperations()); Map<String, AuthorizerModel> authorizers = new HashMap<>(new AddCustomAuthorizers(this.service, getNamingStrategy()).constructAuthorizers()); OperationModel endpointOperation = null; boolean endpointCacheRequired = false; for (OperationModel o : operations.values()) { if (o.isEndpointOperation()) { endpointOperation = o; } if (o.getEndpointDiscovery() != null && o.getEndpointDiscovery().isRequired()) { endpointCacheRequired = true; } } if (endpointOperation != null) { endpointOperation.setEndpointCacheRequired(endpointCacheRequired); } for (IntermediateModelShapeProcessor processor : shapeProcessors) { shapes.putAll(processor.process(Collections.unmodifiableMap(operations), Collections.unmodifiableMap(shapes))); } operations.entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); paginators.getPagination().entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); log.info("{} shapes found in total.", shapes.size()); IntermediateModel fullModel = new IntermediateModel( constructMetadata(service, customConfig), operations, shapes, customConfig, endpointOperation, authorizers, paginators.getPagination(), namingStrategy, waiters.getWaiters()); customization.postprocess(fullModel); log.info("{} shapes remained after applying customizations.", fullModel.getShapes().size()); Map<String, ShapeModel> trimmedShapes = removeUnusedShapes(fullModel); trimmedShapes.entrySet().removeIf(e -> customConfig.getDeprecatedShapes().contains(e.getKey())); log.info("{} shapes remained after removing unused shapes.", trimmedShapes.size()); IntermediateModel trimmedModel = new IntermediateModel(fullModel.getMetadata(), fullModel.getOperations(), trimmedShapes, fullModel.getCustomizationConfig(), endpointOperation, fullModel.getCustomAuthorizers(), fullModel.getPaginators(), namingStrategy, fullModel.getWaiters()); linkMembersToShapes(trimmedModel); linkOperationsToInputOutputShapes(trimmedModel); linkCustomAuthorizationToRequestShapes(trimmedModel); setSimpleMethods(trimmedModel); return trimmedModel; } | IntermediateModelBuilder { public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOperations(this).constructOperations()); Map<String, AuthorizerModel> authorizers = new HashMap<>(new AddCustomAuthorizers(this.service, getNamingStrategy()).constructAuthorizers()); OperationModel endpointOperation = null; boolean endpointCacheRequired = false; for (OperationModel o : operations.values()) { if (o.isEndpointOperation()) { endpointOperation = o; } if (o.getEndpointDiscovery() != null && o.getEndpointDiscovery().isRequired()) { endpointCacheRequired = true; } } if (endpointOperation != null) { endpointOperation.setEndpointCacheRequired(endpointCacheRequired); } for (IntermediateModelShapeProcessor processor : shapeProcessors) { shapes.putAll(processor.process(Collections.unmodifiableMap(operations), Collections.unmodifiableMap(shapes))); } operations.entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); paginators.getPagination().entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); log.info("{} shapes found in total.", shapes.size()); IntermediateModel fullModel = new IntermediateModel( constructMetadata(service, customConfig), operations, shapes, customConfig, endpointOperation, authorizers, paginators.getPagination(), namingStrategy, waiters.getWaiters()); customization.postprocess(fullModel); log.info("{} shapes remained after applying customizations.", fullModel.getShapes().size()); Map<String, ShapeModel> trimmedShapes = removeUnusedShapes(fullModel); trimmedShapes.entrySet().removeIf(e -> customConfig.getDeprecatedShapes().contains(e.getKey())); log.info("{} shapes remained after removing unused shapes.", trimmedShapes.size()); IntermediateModel trimmedModel = new IntermediateModel(fullModel.getMetadata(), fullModel.getOperations(), trimmedShapes, fullModel.getCustomizationConfig(), endpointOperation, fullModel.getCustomAuthorizers(), fullModel.getPaginators(), namingStrategy, fullModel.getWaiters()); linkMembersToShapes(trimmedModel); linkOperationsToInputOutputShapes(trimmedModel); linkCustomAuthorizationToRequestShapes(trimmedModel); setSimpleMethods(trimmedModel); return trimmedModel; } } | IntermediateModelBuilder { public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOperations(this).constructOperations()); Map<String, AuthorizerModel> authorizers = new HashMap<>(new AddCustomAuthorizers(this.service, getNamingStrategy()).constructAuthorizers()); OperationModel endpointOperation = null; boolean endpointCacheRequired = false; for (OperationModel o : operations.values()) { if (o.isEndpointOperation()) { endpointOperation = o; } if (o.getEndpointDiscovery() != null && o.getEndpointDiscovery().isRequired()) { endpointCacheRequired = true; } } if (endpointOperation != null) { endpointOperation.setEndpointCacheRequired(endpointCacheRequired); } for (IntermediateModelShapeProcessor processor : shapeProcessors) { shapes.putAll(processor.process(Collections.unmodifiableMap(operations), Collections.unmodifiableMap(shapes))); } operations.entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); paginators.getPagination().entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); log.info("{} shapes found in total.", shapes.size()); IntermediateModel fullModel = new IntermediateModel( constructMetadata(service, customConfig), operations, shapes, customConfig, endpointOperation, authorizers, paginators.getPagination(), namingStrategy, waiters.getWaiters()); customization.postprocess(fullModel); log.info("{} shapes remained after applying customizations.", fullModel.getShapes().size()); Map<String, ShapeModel> trimmedShapes = removeUnusedShapes(fullModel); trimmedShapes.entrySet().removeIf(e -> customConfig.getDeprecatedShapes().contains(e.getKey())); log.info("{} shapes remained after removing unused shapes.", trimmedShapes.size()); IntermediateModel trimmedModel = new IntermediateModel(fullModel.getMetadata(), fullModel.getOperations(), trimmedShapes, fullModel.getCustomizationConfig(), endpointOperation, fullModel.getCustomAuthorizers(), fullModel.getPaginators(), namingStrategy, fullModel.getWaiters()); linkMembersToShapes(trimmedModel); linkOperationsToInputOutputShapes(trimmedModel); linkCustomAuthorizationToRequestShapes(trimmedModel); setSimpleMethods(trimmedModel); return trimmedModel; } IntermediateModelBuilder(C2jModels models); } | IntermediateModelBuilder { public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOperations(this).constructOperations()); Map<String, AuthorizerModel> authorizers = new HashMap<>(new AddCustomAuthorizers(this.service, getNamingStrategy()).constructAuthorizers()); OperationModel endpointOperation = null; boolean endpointCacheRequired = false; for (OperationModel o : operations.values()) { if (o.isEndpointOperation()) { endpointOperation = o; } if (o.getEndpointDiscovery() != null && o.getEndpointDiscovery().isRequired()) { endpointCacheRequired = true; } } if (endpointOperation != null) { endpointOperation.setEndpointCacheRequired(endpointCacheRequired); } for (IntermediateModelShapeProcessor processor : shapeProcessors) { shapes.putAll(processor.process(Collections.unmodifiableMap(operations), Collections.unmodifiableMap(shapes))); } operations.entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); paginators.getPagination().entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); log.info("{} shapes found in total.", shapes.size()); IntermediateModel fullModel = new IntermediateModel( constructMetadata(service, customConfig), operations, shapes, customConfig, endpointOperation, authorizers, paginators.getPagination(), namingStrategy, waiters.getWaiters()); customization.postprocess(fullModel); log.info("{} shapes remained after applying customizations.", fullModel.getShapes().size()); Map<String, ShapeModel> trimmedShapes = removeUnusedShapes(fullModel); trimmedShapes.entrySet().removeIf(e -> customConfig.getDeprecatedShapes().contains(e.getKey())); log.info("{} shapes remained after removing unused shapes.", trimmedShapes.size()); IntermediateModel trimmedModel = new IntermediateModel(fullModel.getMetadata(), fullModel.getOperations(), trimmedShapes, fullModel.getCustomizationConfig(), endpointOperation, fullModel.getCustomAuthorizers(), fullModel.getPaginators(), namingStrategy, fullModel.getWaiters()); linkMembersToShapes(trimmedModel); linkOperationsToInputOutputShapes(trimmedModel); linkCustomAuthorizationToRequestShapes(trimmedModel); setSimpleMethods(trimmedModel); return trimmedModel; } IntermediateModelBuilder(C2jModels models); IntermediateModel build(); CustomizationConfig getCustomConfig(); ServiceModel getService(); NamingStrategy getNamingStrategy(); TypeUtils getTypeUtils(); Paginators getPaginators(); } | IntermediateModelBuilder { public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOperations(this).constructOperations()); Map<String, AuthorizerModel> authorizers = new HashMap<>(new AddCustomAuthorizers(this.service, getNamingStrategy()).constructAuthorizers()); OperationModel endpointOperation = null; boolean endpointCacheRequired = false; for (OperationModel o : operations.values()) { if (o.isEndpointOperation()) { endpointOperation = o; } if (o.getEndpointDiscovery() != null && o.getEndpointDiscovery().isRequired()) { endpointCacheRequired = true; } } if (endpointOperation != null) { endpointOperation.setEndpointCacheRequired(endpointCacheRequired); } for (IntermediateModelShapeProcessor processor : shapeProcessors) { shapes.putAll(processor.process(Collections.unmodifiableMap(operations), Collections.unmodifiableMap(shapes))); } operations.entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); paginators.getPagination().entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); log.info("{} shapes found in total.", shapes.size()); IntermediateModel fullModel = new IntermediateModel( constructMetadata(service, customConfig), operations, shapes, customConfig, endpointOperation, authorizers, paginators.getPagination(), namingStrategy, waiters.getWaiters()); customization.postprocess(fullModel); log.info("{} shapes remained after applying customizations.", fullModel.getShapes().size()); Map<String, ShapeModel> trimmedShapes = removeUnusedShapes(fullModel); trimmedShapes.entrySet().removeIf(e -> customConfig.getDeprecatedShapes().contains(e.getKey())); log.info("{} shapes remained after removing unused shapes.", trimmedShapes.size()); IntermediateModel trimmedModel = new IntermediateModel(fullModel.getMetadata(), fullModel.getOperations(), trimmedShapes, fullModel.getCustomizationConfig(), endpointOperation, fullModel.getCustomAuthorizers(), fullModel.getPaginators(), namingStrategy, fullModel.getWaiters()); linkMembersToShapes(trimmedModel); linkOperationsToInputOutputShapes(trimmedModel); linkCustomAuthorizationToRequestShapes(trimmedModel); setSimpleMethods(trimmedModel); return trimmedModel; } IntermediateModelBuilder(C2jModels models); IntermediateModel build(); CustomizationConfig getCustomConfig(); ServiceModel getService(); NamingStrategy getNamingStrategy(); TypeUtils getTypeUtils(); Paginators getPaginators(); } |
@Test public void sharedOutputShapesLinkCorrectlyToOperationOutputs() { final File modelFile = new File(IntermediateModelBuilderTest.class .getResource("poet/client/c2j/shared-output/service-2.json").getFile()); IntermediateModel testModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.loadModel(ServiceModel.class, modelFile)) .customizationConfig(CustomizationConfig.create()) .build()) .build(); assertEquals("PingResponse", testModel.getOperation("Ping").getOutputShape().getShapeName()); assertEquals("SecurePingResponse", testModel.getOperation("SecurePing").getOutputShape().getShapeName()); } | public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOperations(this).constructOperations()); Map<String, AuthorizerModel> authorizers = new HashMap<>(new AddCustomAuthorizers(this.service, getNamingStrategy()).constructAuthorizers()); OperationModel endpointOperation = null; boolean endpointCacheRequired = false; for (OperationModel o : operations.values()) { if (o.isEndpointOperation()) { endpointOperation = o; } if (o.getEndpointDiscovery() != null && o.getEndpointDiscovery().isRequired()) { endpointCacheRequired = true; } } if (endpointOperation != null) { endpointOperation.setEndpointCacheRequired(endpointCacheRequired); } for (IntermediateModelShapeProcessor processor : shapeProcessors) { shapes.putAll(processor.process(Collections.unmodifiableMap(operations), Collections.unmodifiableMap(shapes))); } operations.entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); paginators.getPagination().entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); log.info("{} shapes found in total.", shapes.size()); IntermediateModel fullModel = new IntermediateModel( constructMetadata(service, customConfig), operations, shapes, customConfig, endpointOperation, authorizers, paginators.getPagination(), namingStrategy, waiters.getWaiters()); customization.postprocess(fullModel); log.info("{} shapes remained after applying customizations.", fullModel.getShapes().size()); Map<String, ShapeModel> trimmedShapes = removeUnusedShapes(fullModel); trimmedShapes.entrySet().removeIf(e -> customConfig.getDeprecatedShapes().contains(e.getKey())); log.info("{} shapes remained after removing unused shapes.", trimmedShapes.size()); IntermediateModel trimmedModel = new IntermediateModel(fullModel.getMetadata(), fullModel.getOperations(), trimmedShapes, fullModel.getCustomizationConfig(), endpointOperation, fullModel.getCustomAuthorizers(), fullModel.getPaginators(), namingStrategy, fullModel.getWaiters()); linkMembersToShapes(trimmedModel); linkOperationsToInputOutputShapes(trimmedModel); linkCustomAuthorizationToRequestShapes(trimmedModel); setSimpleMethods(trimmedModel); return trimmedModel; } | IntermediateModelBuilder { public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOperations(this).constructOperations()); Map<String, AuthorizerModel> authorizers = new HashMap<>(new AddCustomAuthorizers(this.service, getNamingStrategy()).constructAuthorizers()); OperationModel endpointOperation = null; boolean endpointCacheRequired = false; for (OperationModel o : operations.values()) { if (o.isEndpointOperation()) { endpointOperation = o; } if (o.getEndpointDiscovery() != null && o.getEndpointDiscovery().isRequired()) { endpointCacheRequired = true; } } if (endpointOperation != null) { endpointOperation.setEndpointCacheRequired(endpointCacheRequired); } for (IntermediateModelShapeProcessor processor : shapeProcessors) { shapes.putAll(processor.process(Collections.unmodifiableMap(operations), Collections.unmodifiableMap(shapes))); } operations.entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); paginators.getPagination().entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); log.info("{} shapes found in total.", shapes.size()); IntermediateModel fullModel = new IntermediateModel( constructMetadata(service, customConfig), operations, shapes, customConfig, endpointOperation, authorizers, paginators.getPagination(), namingStrategy, waiters.getWaiters()); customization.postprocess(fullModel); log.info("{} shapes remained after applying customizations.", fullModel.getShapes().size()); Map<String, ShapeModel> trimmedShapes = removeUnusedShapes(fullModel); trimmedShapes.entrySet().removeIf(e -> customConfig.getDeprecatedShapes().contains(e.getKey())); log.info("{} shapes remained after removing unused shapes.", trimmedShapes.size()); IntermediateModel trimmedModel = new IntermediateModel(fullModel.getMetadata(), fullModel.getOperations(), trimmedShapes, fullModel.getCustomizationConfig(), endpointOperation, fullModel.getCustomAuthorizers(), fullModel.getPaginators(), namingStrategy, fullModel.getWaiters()); linkMembersToShapes(trimmedModel); linkOperationsToInputOutputShapes(trimmedModel); linkCustomAuthorizationToRequestShapes(trimmedModel); setSimpleMethods(trimmedModel); return trimmedModel; } } | IntermediateModelBuilder { public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOperations(this).constructOperations()); Map<String, AuthorizerModel> authorizers = new HashMap<>(new AddCustomAuthorizers(this.service, getNamingStrategy()).constructAuthorizers()); OperationModel endpointOperation = null; boolean endpointCacheRequired = false; for (OperationModel o : operations.values()) { if (o.isEndpointOperation()) { endpointOperation = o; } if (o.getEndpointDiscovery() != null && o.getEndpointDiscovery().isRequired()) { endpointCacheRequired = true; } } if (endpointOperation != null) { endpointOperation.setEndpointCacheRequired(endpointCacheRequired); } for (IntermediateModelShapeProcessor processor : shapeProcessors) { shapes.putAll(processor.process(Collections.unmodifiableMap(operations), Collections.unmodifiableMap(shapes))); } operations.entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); paginators.getPagination().entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); log.info("{} shapes found in total.", shapes.size()); IntermediateModel fullModel = new IntermediateModel( constructMetadata(service, customConfig), operations, shapes, customConfig, endpointOperation, authorizers, paginators.getPagination(), namingStrategy, waiters.getWaiters()); customization.postprocess(fullModel); log.info("{} shapes remained after applying customizations.", fullModel.getShapes().size()); Map<String, ShapeModel> trimmedShapes = removeUnusedShapes(fullModel); trimmedShapes.entrySet().removeIf(e -> customConfig.getDeprecatedShapes().contains(e.getKey())); log.info("{} shapes remained after removing unused shapes.", trimmedShapes.size()); IntermediateModel trimmedModel = new IntermediateModel(fullModel.getMetadata(), fullModel.getOperations(), trimmedShapes, fullModel.getCustomizationConfig(), endpointOperation, fullModel.getCustomAuthorizers(), fullModel.getPaginators(), namingStrategy, fullModel.getWaiters()); linkMembersToShapes(trimmedModel); linkOperationsToInputOutputShapes(trimmedModel); linkCustomAuthorizationToRequestShapes(trimmedModel); setSimpleMethods(trimmedModel); return trimmedModel; } IntermediateModelBuilder(C2jModels models); } | IntermediateModelBuilder { public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOperations(this).constructOperations()); Map<String, AuthorizerModel> authorizers = new HashMap<>(new AddCustomAuthorizers(this.service, getNamingStrategy()).constructAuthorizers()); OperationModel endpointOperation = null; boolean endpointCacheRequired = false; for (OperationModel o : operations.values()) { if (o.isEndpointOperation()) { endpointOperation = o; } if (o.getEndpointDiscovery() != null && o.getEndpointDiscovery().isRequired()) { endpointCacheRequired = true; } } if (endpointOperation != null) { endpointOperation.setEndpointCacheRequired(endpointCacheRequired); } for (IntermediateModelShapeProcessor processor : shapeProcessors) { shapes.putAll(processor.process(Collections.unmodifiableMap(operations), Collections.unmodifiableMap(shapes))); } operations.entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); paginators.getPagination().entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); log.info("{} shapes found in total.", shapes.size()); IntermediateModel fullModel = new IntermediateModel( constructMetadata(service, customConfig), operations, shapes, customConfig, endpointOperation, authorizers, paginators.getPagination(), namingStrategy, waiters.getWaiters()); customization.postprocess(fullModel); log.info("{} shapes remained after applying customizations.", fullModel.getShapes().size()); Map<String, ShapeModel> trimmedShapes = removeUnusedShapes(fullModel); trimmedShapes.entrySet().removeIf(e -> customConfig.getDeprecatedShapes().contains(e.getKey())); log.info("{} shapes remained after removing unused shapes.", trimmedShapes.size()); IntermediateModel trimmedModel = new IntermediateModel(fullModel.getMetadata(), fullModel.getOperations(), trimmedShapes, fullModel.getCustomizationConfig(), endpointOperation, fullModel.getCustomAuthorizers(), fullModel.getPaginators(), namingStrategy, fullModel.getWaiters()); linkMembersToShapes(trimmedModel); linkOperationsToInputOutputShapes(trimmedModel); linkCustomAuthorizationToRequestShapes(trimmedModel); setSimpleMethods(trimmedModel); return trimmedModel; } IntermediateModelBuilder(C2jModels models); IntermediateModel build(); CustomizationConfig getCustomConfig(); ServiceModel getService(); NamingStrategy getNamingStrategy(); TypeUtils getTypeUtils(); Paginators getPaginators(); } | IntermediateModelBuilder { public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOperations(this).constructOperations()); Map<String, AuthorizerModel> authorizers = new HashMap<>(new AddCustomAuthorizers(this.service, getNamingStrategy()).constructAuthorizers()); OperationModel endpointOperation = null; boolean endpointCacheRequired = false; for (OperationModel o : operations.values()) { if (o.isEndpointOperation()) { endpointOperation = o; } if (o.getEndpointDiscovery() != null && o.getEndpointDiscovery().isRequired()) { endpointCacheRequired = true; } } if (endpointOperation != null) { endpointOperation.setEndpointCacheRequired(endpointCacheRequired); } for (IntermediateModelShapeProcessor processor : shapeProcessors) { shapes.putAll(processor.process(Collections.unmodifiableMap(operations), Collections.unmodifiableMap(shapes))); } operations.entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); paginators.getPagination().entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); log.info("{} shapes found in total.", shapes.size()); IntermediateModel fullModel = new IntermediateModel( constructMetadata(service, customConfig), operations, shapes, customConfig, endpointOperation, authorizers, paginators.getPagination(), namingStrategy, waiters.getWaiters()); customization.postprocess(fullModel); log.info("{} shapes remained after applying customizations.", fullModel.getShapes().size()); Map<String, ShapeModel> trimmedShapes = removeUnusedShapes(fullModel); trimmedShapes.entrySet().removeIf(e -> customConfig.getDeprecatedShapes().contains(e.getKey())); log.info("{} shapes remained after removing unused shapes.", trimmedShapes.size()); IntermediateModel trimmedModel = new IntermediateModel(fullModel.getMetadata(), fullModel.getOperations(), trimmedShapes, fullModel.getCustomizationConfig(), endpointOperation, fullModel.getCustomAuthorizers(), fullModel.getPaginators(), namingStrategy, fullModel.getWaiters()); linkMembersToShapes(trimmedModel); linkOperationsToInputOutputShapes(trimmedModel); linkCustomAuthorizationToRequestShapes(trimmedModel); setSimpleMethods(trimmedModel); return trimmedModel; } IntermediateModelBuilder(C2jModels models); IntermediateModel build(); CustomizationConfig getCustomConfig(); ServiceModel getService(); NamingStrategy getNamingStrategy(); TypeUtils getTypeUtils(); Paginators getPaginators(); } |
@Test public void defaultEndpointDiscovery_true() { final File modelFile = new File(IntermediateModelBuilderTest.class .getResource("poet/client/c2j/endpointdiscovery/service-2.json").getFile()); IntermediateModel testModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.loadModel(ServiceModel.class, modelFile)) .customizationConfig(CustomizationConfig.create()) .build()) .build(); assertTrue(testModel.getEndpointOperation().get().isEndpointCacheRequired()); } | public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOperations(this).constructOperations()); Map<String, AuthorizerModel> authorizers = new HashMap<>(new AddCustomAuthorizers(this.service, getNamingStrategy()).constructAuthorizers()); OperationModel endpointOperation = null; boolean endpointCacheRequired = false; for (OperationModel o : operations.values()) { if (o.isEndpointOperation()) { endpointOperation = o; } if (o.getEndpointDiscovery() != null && o.getEndpointDiscovery().isRequired()) { endpointCacheRequired = true; } } if (endpointOperation != null) { endpointOperation.setEndpointCacheRequired(endpointCacheRequired); } for (IntermediateModelShapeProcessor processor : shapeProcessors) { shapes.putAll(processor.process(Collections.unmodifiableMap(operations), Collections.unmodifiableMap(shapes))); } operations.entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); paginators.getPagination().entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); log.info("{} shapes found in total.", shapes.size()); IntermediateModel fullModel = new IntermediateModel( constructMetadata(service, customConfig), operations, shapes, customConfig, endpointOperation, authorizers, paginators.getPagination(), namingStrategy, waiters.getWaiters()); customization.postprocess(fullModel); log.info("{} shapes remained after applying customizations.", fullModel.getShapes().size()); Map<String, ShapeModel> trimmedShapes = removeUnusedShapes(fullModel); trimmedShapes.entrySet().removeIf(e -> customConfig.getDeprecatedShapes().contains(e.getKey())); log.info("{} shapes remained after removing unused shapes.", trimmedShapes.size()); IntermediateModel trimmedModel = new IntermediateModel(fullModel.getMetadata(), fullModel.getOperations(), trimmedShapes, fullModel.getCustomizationConfig(), endpointOperation, fullModel.getCustomAuthorizers(), fullModel.getPaginators(), namingStrategy, fullModel.getWaiters()); linkMembersToShapes(trimmedModel); linkOperationsToInputOutputShapes(trimmedModel); linkCustomAuthorizationToRequestShapes(trimmedModel); setSimpleMethods(trimmedModel); return trimmedModel; } | IntermediateModelBuilder { public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOperations(this).constructOperations()); Map<String, AuthorizerModel> authorizers = new HashMap<>(new AddCustomAuthorizers(this.service, getNamingStrategy()).constructAuthorizers()); OperationModel endpointOperation = null; boolean endpointCacheRequired = false; for (OperationModel o : operations.values()) { if (o.isEndpointOperation()) { endpointOperation = o; } if (o.getEndpointDiscovery() != null && o.getEndpointDiscovery().isRequired()) { endpointCacheRequired = true; } } if (endpointOperation != null) { endpointOperation.setEndpointCacheRequired(endpointCacheRequired); } for (IntermediateModelShapeProcessor processor : shapeProcessors) { shapes.putAll(processor.process(Collections.unmodifiableMap(operations), Collections.unmodifiableMap(shapes))); } operations.entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); paginators.getPagination().entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); log.info("{} shapes found in total.", shapes.size()); IntermediateModel fullModel = new IntermediateModel( constructMetadata(service, customConfig), operations, shapes, customConfig, endpointOperation, authorizers, paginators.getPagination(), namingStrategy, waiters.getWaiters()); customization.postprocess(fullModel); log.info("{} shapes remained after applying customizations.", fullModel.getShapes().size()); Map<String, ShapeModel> trimmedShapes = removeUnusedShapes(fullModel); trimmedShapes.entrySet().removeIf(e -> customConfig.getDeprecatedShapes().contains(e.getKey())); log.info("{} shapes remained after removing unused shapes.", trimmedShapes.size()); IntermediateModel trimmedModel = new IntermediateModel(fullModel.getMetadata(), fullModel.getOperations(), trimmedShapes, fullModel.getCustomizationConfig(), endpointOperation, fullModel.getCustomAuthorizers(), fullModel.getPaginators(), namingStrategy, fullModel.getWaiters()); linkMembersToShapes(trimmedModel); linkOperationsToInputOutputShapes(trimmedModel); linkCustomAuthorizationToRequestShapes(trimmedModel); setSimpleMethods(trimmedModel); return trimmedModel; } } | IntermediateModelBuilder { public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOperations(this).constructOperations()); Map<String, AuthorizerModel> authorizers = new HashMap<>(new AddCustomAuthorizers(this.service, getNamingStrategy()).constructAuthorizers()); OperationModel endpointOperation = null; boolean endpointCacheRequired = false; for (OperationModel o : operations.values()) { if (o.isEndpointOperation()) { endpointOperation = o; } if (o.getEndpointDiscovery() != null && o.getEndpointDiscovery().isRequired()) { endpointCacheRequired = true; } } if (endpointOperation != null) { endpointOperation.setEndpointCacheRequired(endpointCacheRequired); } for (IntermediateModelShapeProcessor processor : shapeProcessors) { shapes.putAll(processor.process(Collections.unmodifiableMap(operations), Collections.unmodifiableMap(shapes))); } operations.entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); paginators.getPagination().entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); log.info("{} shapes found in total.", shapes.size()); IntermediateModel fullModel = new IntermediateModel( constructMetadata(service, customConfig), operations, shapes, customConfig, endpointOperation, authorizers, paginators.getPagination(), namingStrategy, waiters.getWaiters()); customization.postprocess(fullModel); log.info("{} shapes remained after applying customizations.", fullModel.getShapes().size()); Map<String, ShapeModel> trimmedShapes = removeUnusedShapes(fullModel); trimmedShapes.entrySet().removeIf(e -> customConfig.getDeprecatedShapes().contains(e.getKey())); log.info("{} shapes remained after removing unused shapes.", trimmedShapes.size()); IntermediateModel trimmedModel = new IntermediateModel(fullModel.getMetadata(), fullModel.getOperations(), trimmedShapes, fullModel.getCustomizationConfig(), endpointOperation, fullModel.getCustomAuthorizers(), fullModel.getPaginators(), namingStrategy, fullModel.getWaiters()); linkMembersToShapes(trimmedModel); linkOperationsToInputOutputShapes(trimmedModel); linkCustomAuthorizationToRequestShapes(trimmedModel); setSimpleMethods(trimmedModel); return trimmedModel; } IntermediateModelBuilder(C2jModels models); } | IntermediateModelBuilder { public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOperations(this).constructOperations()); Map<String, AuthorizerModel> authorizers = new HashMap<>(new AddCustomAuthorizers(this.service, getNamingStrategy()).constructAuthorizers()); OperationModel endpointOperation = null; boolean endpointCacheRequired = false; for (OperationModel o : operations.values()) { if (o.isEndpointOperation()) { endpointOperation = o; } if (o.getEndpointDiscovery() != null && o.getEndpointDiscovery().isRequired()) { endpointCacheRequired = true; } } if (endpointOperation != null) { endpointOperation.setEndpointCacheRequired(endpointCacheRequired); } for (IntermediateModelShapeProcessor processor : shapeProcessors) { shapes.putAll(processor.process(Collections.unmodifiableMap(operations), Collections.unmodifiableMap(shapes))); } operations.entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); paginators.getPagination().entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); log.info("{} shapes found in total.", shapes.size()); IntermediateModel fullModel = new IntermediateModel( constructMetadata(service, customConfig), operations, shapes, customConfig, endpointOperation, authorizers, paginators.getPagination(), namingStrategy, waiters.getWaiters()); customization.postprocess(fullModel); log.info("{} shapes remained after applying customizations.", fullModel.getShapes().size()); Map<String, ShapeModel> trimmedShapes = removeUnusedShapes(fullModel); trimmedShapes.entrySet().removeIf(e -> customConfig.getDeprecatedShapes().contains(e.getKey())); log.info("{} shapes remained after removing unused shapes.", trimmedShapes.size()); IntermediateModel trimmedModel = new IntermediateModel(fullModel.getMetadata(), fullModel.getOperations(), trimmedShapes, fullModel.getCustomizationConfig(), endpointOperation, fullModel.getCustomAuthorizers(), fullModel.getPaginators(), namingStrategy, fullModel.getWaiters()); linkMembersToShapes(trimmedModel); linkOperationsToInputOutputShapes(trimmedModel); linkCustomAuthorizationToRequestShapes(trimmedModel); setSimpleMethods(trimmedModel); return trimmedModel; } IntermediateModelBuilder(C2jModels models); IntermediateModel build(); CustomizationConfig getCustomConfig(); ServiceModel getService(); NamingStrategy getNamingStrategy(); TypeUtils getTypeUtils(); Paginators getPaginators(); } | IntermediateModelBuilder { public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOperations(this).constructOperations()); Map<String, AuthorizerModel> authorizers = new HashMap<>(new AddCustomAuthorizers(this.service, getNamingStrategy()).constructAuthorizers()); OperationModel endpointOperation = null; boolean endpointCacheRequired = false; for (OperationModel o : operations.values()) { if (o.isEndpointOperation()) { endpointOperation = o; } if (o.getEndpointDiscovery() != null && o.getEndpointDiscovery().isRequired()) { endpointCacheRequired = true; } } if (endpointOperation != null) { endpointOperation.setEndpointCacheRequired(endpointCacheRequired); } for (IntermediateModelShapeProcessor processor : shapeProcessors) { shapes.putAll(processor.process(Collections.unmodifiableMap(operations), Collections.unmodifiableMap(shapes))); } operations.entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); paginators.getPagination().entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); log.info("{} shapes found in total.", shapes.size()); IntermediateModel fullModel = new IntermediateModel( constructMetadata(service, customConfig), operations, shapes, customConfig, endpointOperation, authorizers, paginators.getPagination(), namingStrategy, waiters.getWaiters()); customization.postprocess(fullModel); log.info("{} shapes remained after applying customizations.", fullModel.getShapes().size()); Map<String, ShapeModel> trimmedShapes = removeUnusedShapes(fullModel); trimmedShapes.entrySet().removeIf(e -> customConfig.getDeprecatedShapes().contains(e.getKey())); log.info("{} shapes remained after removing unused shapes.", trimmedShapes.size()); IntermediateModel trimmedModel = new IntermediateModel(fullModel.getMetadata(), fullModel.getOperations(), trimmedShapes, fullModel.getCustomizationConfig(), endpointOperation, fullModel.getCustomAuthorizers(), fullModel.getPaginators(), namingStrategy, fullModel.getWaiters()); linkMembersToShapes(trimmedModel); linkOperationsToInputOutputShapes(trimmedModel); linkCustomAuthorizationToRequestShapes(trimmedModel); setSimpleMethods(trimmedModel); return trimmedModel; } IntermediateModelBuilder(C2jModels models); IntermediateModel build(); CustomizationConfig getCustomConfig(); ServiceModel getService(); NamingStrategy getNamingStrategy(); TypeUtils getTypeUtils(); Paginators getPaginators(); } |
@Test public void defaultEndpointDiscovery_false() { final File modelFile = new File(IntermediateModelBuilderTest.class .getResource("poet/client/c2j/endpointdiscoveryoptional/service-2.json").getFile()); IntermediateModel testModel = new IntermediateModelBuilder( C2jModels.builder() .serviceModel(ModelLoaderUtils.loadModel(ServiceModel.class, modelFile)) .customizationConfig(CustomizationConfig.create()) .build()) .build(); assertFalse(testModel.getEndpointOperation().get().isEndpointCacheRequired()); } | public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOperations(this).constructOperations()); Map<String, AuthorizerModel> authorizers = new HashMap<>(new AddCustomAuthorizers(this.service, getNamingStrategy()).constructAuthorizers()); OperationModel endpointOperation = null; boolean endpointCacheRequired = false; for (OperationModel o : operations.values()) { if (o.isEndpointOperation()) { endpointOperation = o; } if (o.getEndpointDiscovery() != null && o.getEndpointDiscovery().isRequired()) { endpointCacheRequired = true; } } if (endpointOperation != null) { endpointOperation.setEndpointCacheRequired(endpointCacheRequired); } for (IntermediateModelShapeProcessor processor : shapeProcessors) { shapes.putAll(processor.process(Collections.unmodifiableMap(operations), Collections.unmodifiableMap(shapes))); } operations.entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); paginators.getPagination().entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); log.info("{} shapes found in total.", shapes.size()); IntermediateModel fullModel = new IntermediateModel( constructMetadata(service, customConfig), operations, shapes, customConfig, endpointOperation, authorizers, paginators.getPagination(), namingStrategy, waiters.getWaiters()); customization.postprocess(fullModel); log.info("{} shapes remained after applying customizations.", fullModel.getShapes().size()); Map<String, ShapeModel> trimmedShapes = removeUnusedShapes(fullModel); trimmedShapes.entrySet().removeIf(e -> customConfig.getDeprecatedShapes().contains(e.getKey())); log.info("{} shapes remained after removing unused shapes.", trimmedShapes.size()); IntermediateModel trimmedModel = new IntermediateModel(fullModel.getMetadata(), fullModel.getOperations(), trimmedShapes, fullModel.getCustomizationConfig(), endpointOperation, fullModel.getCustomAuthorizers(), fullModel.getPaginators(), namingStrategy, fullModel.getWaiters()); linkMembersToShapes(trimmedModel); linkOperationsToInputOutputShapes(trimmedModel); linkCustomAuthorizationToRequestShapes(trimmedModel); setSimpleMethods(trimmedModel); return trimmedModel; } | IntermediateModelBuilder { public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOperations(this).constructOperations()); Map<String, AuthorizerModel> authorizers = new HashMap<>(new AddCustomAuthorizers(this.service, getNamingStrategy()).constructAuthorizers()); OperationModel endpointOperation = null; boolean endpointCacheRequired = false; for (OperationModel o : operations.values()) { if (o.isEndpointOperation()) { endpointOperation = o; } if (o.getEndpointDiscovery() != null && o.getEndpointDiscovery().isRequired()) { endpointCacheRequired = true; } } if (endpointOperation != null) { endpointOperation.setEndpointCacheRequired(endpointCacheRequired); } for (IntermediateModelShapeProcessor processor : shapeProcessors) { shapes.putAll(processor.process(Collections.unmodifiableMap(operations), Collections.unmodifiableMap(shapes))); } operations.entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); paginators.getPagination().entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); log.info("{} shapes found in total.", shapes.size()); IntermediateModel fullModel = new IntermediateModel( constructMetadata(service, customConfig), operations, shapes, customConfig, endpointOperation, authorizers, paginators.getPagination(), namingStrategy, waiters.getWaiters()); customization.postprocess(fullModel); log.info("{} shapes remained after applying customizations.", fullModel.getShapes().size()); Map<String, ShapeModel> trimmedShapes = removeUnusedShapes(fullModel); trimmedShapes.entrySet().removeIf(e -> customConfig.getDeprecatedShapes().contains(e.getKey())); log.info("{} shapes remained after removing unused shapes.", trimmedShapes.size()); IntermediateModel trimmedModel = new IntermediateModel(fullModel.getMetadata(), fullModel.getOperations(), trimmedShapes, fullModel.getCustomizationConfig(), endpointOperation, fullModel.getCustomAuthorizers(), fullModel.getPaginators(), namingStrategy, fullModel.getWaiters()); linkMembersToShapes(trimmedModel); linkOperationsToInputOutputShapes(trimmedModel); linkCustomAuthorizationToRequestShapes(trimmedModel); setSimpleMethods(trimmedModel); return trimmedModel; } } | IntermediateModelBuilder { public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOperations(this).constructOperations()); Map<String, AuthorizerModel> authorizers = new HashMap<>(new AddCustomAuthorizers(this.service, getNamingStrategy()).constructAuthorizers()); OperationModel endpointOperation = null; boolean endpointCacheRequired = false; for (OperationModel o : operations.values()) { if (o.isEndpointOperation()) { endpointOperation = o; } if (o.getEndpointDiscovery() != null && o.getEndpointDiscovery().isRequired()) { endpointCacheRequired = true; } } if (endpointOperation != null) { endpointOperation.setEndpointCacheRequired(endpointCacheRequired); } for (IntermediateModelShapeProcessor processor : shapeProcessors) { shapes.putAll(processor.process(Collections.unmodifiableMap(operations), Collections.unmodifiableMap(shapes))); } operations.entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); paginators.getPagination().entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); log.info("{} shapes found in total.", shapes.size()); IntermediateModel fullModel = new IntermediateModel( constructMetadata(service, customConfig), operations, shapes, customConfig, endpointOperation, authorizers, paginators.getPagination(), namingStrategy, waiters.getWaiters()); customization.postprocess(fullModel); log.info("{} shapes remained after applying customizations.", fullModel.getShapes().size()); Map<String, ShapeModel> trimmedShapes = removeUnusedShapes(fullModel); trimmedShapes.entrySet().removeIf(e -> customConfig.getDeprecatedShapes().contains(e.getKey())); log.info("{} shapes remained after removing unused shapes.", trimmedShapes.size()); IntermediateModel trimmedModel = new IntermediateModel(fullModel.getMetadata(), fullModel.getOperations(), trimmedShapes, fullModel.getCustomizationConfig(), endpointOperation, fullModel.getCustomAuthorizers(), fullModel.getPaginators(), namingStrategy, fullModel.getWaiters()); linkMembersToShapes(trimmedModel); linkOperationsToInputOutputShapes(trimmedModel); linkCustomAuthorizationToRequestShapes(trimmedModel); setSimpleMethods(trimmedModel); return trimmedModel; } IntermediateModelBuilder(C2jModels models); } | IntermediateModelBuilder { public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOperations(this).constructOperations()); Map<String, AuthorizerModel> authorizers = new HashMap<>(new AddCustomAuthorizers(this.service, getNamingStrategy()).constructAuthorizers()); OperationModel endpointOperation = null; boolean endpointCacheRequired = false; for (OperationModel o : operations.values()) { if (o.isEndpointOperation()) { endpointOperation = o; } if (o.getEndpointDiscovery() != null && o.getEndpointDiscovery().isRequired()) { endpointCacheRequired = true; } } if (endpointOperation != null) { endpointOperation.setEndpointCacheRequired(endpointCacheRequired); } for (IntermediateModelShapeProcessor processor : shapeProcessors) { shapes.putAll(processor.process(Collections.unmodifiableMap(operations), Collections.unmodifiableMap(shapes))); } operations.entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); paginators.getPagination().entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); log.info("{} shapes found in total.", shapes.size()); IntermediateModel fullModel = new IntermediateModel( constructMetadata(service, customConfig), operations, shapes, customConfig, endpointOperation, authorizers, paginators.getPagination(), namingStrategy, waiters.getWaiters()); customization.postprocess(fullModel); log.info("{} shapes remained after applying customizations.", fullModel.getShapes().size()); Map<String, ShapeModel> trimmedShapes = removeUnusedShapes(fullModel); trimmedShapes.entrySet().removeIf(e -> customConfig.getDeprecatedShapes().contains(e.getKey())); log.info("{} shapes remained after removing unused shapes.", trimmedShapes.size()); IntermediateModel trimmedModel = new IntermediateModel(fullModel.getMetadata(), fullModel.getOperations(), trimmedShapes, fullModel.getCustomizationConfig(), endpointOperation, fullModel.getCustomAuthorizers(), fullModel.getPaginators(), namingStrategy, fullModel.getWaiters()); linkMembersToShapes(trimmedModel); linkOperationsToInputOutputShapes(trimmedModel); linkCustomAuthorizationToRequestShapes(trimmedModel); setSimpleMethods(trimmedModel); return trimmedModel; } IntermediateModelBuilder(C2jModels models); IntermediateModel build(); CustomizationConfig getCustomConfig(); ServiceModel getService(); NamingStrategy getNamingStrategy(); TypeUtils getTypeUtils(); Paginators getPaginators(); } | IntermediateModelBuilder { public IntermediateModel build() { CodegenCustomizationProcessor customization = DefaultCustomizationProcessor .getProcessorFor(customConfig); customization.preprocess(service); Map<String, ShapeModel> shapes = new HashMap<>(); Map<String, OperationModel> operations = new TreeMap<>(new AddOperations(this).constructOperations()); Map<String, AuthorizerModel> authorizers = new HashMap<>(new AddCustomAuthorizers(this.service, getNamingStrategy()).constructAuthorizers()); OperationModel endpointOperation = null; boolean endpointCacheRequired = false; for (OperationModel o : operations.values()) { if (o.isEndpointOperation()) { endpointOperation = o; } if (o.getEndpointDiscovery() != null && o.getEndpointDiscovery().isRequired()) { endpointCacheRequired = true; } } if (endpointOperation != null) { endpointOperation.setEndpointCacheRequired(endpointCacheRequired); } for (IntermediateModelShapeProcessor processor : shapeProcessors) { shapes.putAll(processor.process(Collections.unmodifiableMap(operations), Collections.unmodifiableMap(shapes))); } operations.entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); paginators.getPagination().entrySet().removeIf(e -> customConfig.getDeprecatedOperations().contains(e.getKey())); log.info("{} shapes found in total.", shapes.size()); IntermediateModel fullModel = new IntermediateModel( constructMetadata(service, customConfig), operations, shapes, customConfig, endpointOperation, authorizers, paginators.getPagination(), namingStrategy, waiters.getWaiters()); customization.postprocess(fullModel); log.info("{} shapes remained after applying customizations.", fullModel.getShapes().size()); Map<String, ShapeModel> trimmedShapes = removeUnusedShapes(fullModel); trimmedShapes.entrySet().removeIf(e -> customConfig.getDeprecatedShapes().contains(e.getKey())); log.info("{} shapes remained after removing unused shapes.", trimmedShapes.size()); IntermediateModel trimmedModel = new IntermediateModel(fullModel.getMetadata(), fullModel.getOperations(), trimmedShapes, fullModel.getCustomizationConfig(), endpointOperation, fullModel.getCustomAuthorizers(), fullModel.getPaginators(), namingStrategy, fullModel.getWaiters()); linkMembersToShapes(trimmedModel); linkOperationsToInputOutputShapes(trimmedModel); linkCustomAuthorizationToRequestShapes(trimmedModel); setSimpleMethods(trimmedModel); return trimmedModel; } IntermediateModelBuilder(C2jModels models); IntermediateModel build(); CustomizationConfig getCustomConfig(); ServiceModel getService(); NamingStrategy getNamingStrategy(); TypeUtils getTypeUtils(); Paginators getPaginators(); } |
@Test public void modifyHttpRequest_setsExpect100Continue_whenSdkRequestIsPutObject() { final SdkHttpRequest modifiedRequest = interceptor.modifyHttpRequest(modifyHttpRequestContext(PutObjectRequest.builder().build()), new ExecutionAttributes()); assertThat(modifiedRequest.firstMatchingHeader("Expect")).hasValue("100-continue"); } | @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { if (context.request() instanceof PutObjectRequest) { return context.httpRequest().toBuilder().putHeader("Expect", "100-continue").build(); } return context.httpRequest(); } | PutObjectInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { if (context.request() instanceof PutObjectRequest) { return context.httpRequest().toBuilder().putHeader("Expect", "100-continue").build(); } return context.httpRequest(); } } | PutObjectInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { if (context.request() instanceof PutObjectRequest) { return context.httpRequest().toBuilder().putHeader("Expect", "100-continue").build(); } return context.httpRequest(); } } | PutObjectInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { if (context.request() instanceof PutObjectRequest) { return context.httpRequest().toBuilder().putHeader("Expect", "100-continue").build(); } return context.httpRequest(); } @Override SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); } | PutObjectInterceptor implements ExecutionInterceptor { @Override public SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context, ExecutionAttributes executionAttributes) { if (context.request() instanceof PutObjectRequest) { return context.httpRequest().toBuilder().putHeader("Expect", "100-continue").build(); } return context.httpRequest(); } @Override SdkHttpRequest modifyHttpRequest(Context.ModifyHttpRequest context,
ExecutionAttributes executionAttributes); } |
@Test public void build_missingProperty_expiration() { assertThatThrownBy(() -> generateMinimal().toBuilder().expiration(null).build()) .isInstanceOf(NullPointerException.class) .hasMessageContaining("expiration"); } | @Override public Builder toBuilder() { return new DefaultBuilder(this); } | PresignedGetObjectRequest extends PresignedRequest implements ToCopyableBuilder<PresignedGetObjectRequest.Builder, PresignedGetObjectRequest> { @Override public Builder toBuilder() { return new DefaultBuilder(this); } } | PresignedGetObjectRequest extends PresignedRequest implements ToCopyableBuilder<PresignedGetObjectRequest.Builder, PresignedGetObjectRequest> { @Override public Builder toBuilder() { return new DefaultBuilder(this); } private PresignedGetObjectRequest(DefaultBuilder builder); } | PresignedGetObjectRequest extends PresignedRequest implements ToCopyableBuilder<PresignedGetObjectRequest.Builder, PresignedGetObjectRequest> { @Override public Builder toBuilder() { return new DefaultBuilder(this); } private PresignedGetObjectRequest(DefaultBuilder builder); static Builder builder(); @Override Builder toBuilder(); } | PresignedGetObjectRequest extends PresignedRequest implements ToCopyableBuilder<PresignedGetObjectRequest.Builder, PresignedGetObjectRequest> { @Override public Builder toBuilder() { return new DefaultBuilder(this); } private PresignedGetObjectRequest(DefaultBuilder builder); static Builder builder(); @Override Builder toBuilder(); } |
@Test public void strip_html_tags_null_or_empty_input_returns_empty_string() { Assert.assertThat(DocumentationUtils.stripHtmlTags(null), Matchers .isEmptyString()); Assert.assertThat(DocumentationUtils.stripHtmlTags(""), Matchers .isEmptyString()); } | public static String stripHtmlTags(String documentation) { if (documentation == null) { return ""; } if (documentation.startsWith("<")) { int startTagIndex = documentation.indexOf(">"); int closingTagIndex = documentation.lastIndexOf("<"); if (closingTagIndex > startTagIndex) { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1, closingTagIndex)); } else { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1)); } } return documentation.trim(); } | DocumentationUtils { public static String stripHtmlTags(String documentation) { if (documentation == null) { return ""; } if (documentation.startsWith("<")) { int startTagIndex = documentation.indexOf(">"); int closingTagIndex = documentation.lastIndexOf("<"); if (closingTagIndex > startTagIndex) { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1, closingTagIndex)); } else { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1)); } } return documentation.trim(); } } | DocumentationUtils { public static String stripHtmlTags(String documentation) { if (documentation == null) { return ""; } if (documentation.startsWith("<")) { int startTagIndex = documentation.indexOf(">"); int closingTagIndex = documentation.lastIndexOf("<"); if (closingTagIndex > startTagIndex) { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1, closingTagIndex)); } else { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1)); } } return documentation.trim(); } private DocumentationUtils(); } | DocumentationUtils { public static String stripHtmlTags(String documentation) { if (documentation == null) { return ""; } if (documentation.startsWith("<")) { int startTagIndex = documentation.indexOf(">"); int closingTagIndex = documentation.lastIndexOf("<"); if (closingTagIndex > startTagIndex) { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1, closingTagIndex)); } else { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1)); } } return documentation.trim(); } private DocumentationUtils(); static String stripHtmlTags(String documentation); static String escapeIllegalCharacters(String documentation); static String createLinkToServiceDocumentation(Metadata metadata, String name); static String createLinkToServiceDocumentation(Metadata metadata, ShapeModel shapeModel); static String removeFromEnd(String string, String stringToRemove); static String defaultSetter(); static String defaultSetterParam(); static String defaultGetter(); static String defaultGetterParam(); static String defaultFluentReturn(); static String defaultExistenceCheck(); } | DocumentationUtils { public static String stripHtmlTags(String documentation) { if (documentation == null) { return ""; } if (documentation.startsWith("<")) { int startTagIndex = documentation.indexOf(">"); int closingTagIndex = documentation.lastIndexOf("<"); if (closingTagIndex > startTagIndex) { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1, closingTagIndex)); } else { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1)); } } return documentation.trim(); } private DocumentationUtils(); static String stripHtmlTags(String documentation); static String escapeIllegalCharacters(String documentation); static String createLinkToServiceDocumentation(Metadata metadata, String name); static String createLinkToServiceDocumentation(Metadata metadata, ShapeModel shapeModel); static String removeFromEnd(String string, String stringToRemove); static String defaultSetter(); static String defaultSetterParam(); static String defaultGetter(); static String defaultGetterParam(); static String defaultFluentReturn(); static String defaultExistenceCheck(); } |
@Test public void html_tags_at_start_of_string_are_removed() { Assert.assertEquals("foo", DocumentationUtils.stripHtmlTags ("<bar>foo</bar>")); } | public static String stripHtmlTags(String documentation) { if (documentation == null) { return ""; } if (documentation.startsWith("<")) { int startTagIndex = documentation.indexOf(">"); int closingTagIndex = documentation.lastIndexOf("<"); if (closingTagIndex > startTagIndex) { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1, closingTagIndex)); } else { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1)); } } return documentation.trim(); } | DocumentationUtils { public static String stripHtmlTags(String documentation) { if (documentation == null) { return ""; } if (documentation.startsWith("<")) { int startTagIndex = documentation.indexOf(">"); int closingTagIndex = documentation.lastIndexOf("<"); if (closingTagIndex > startTagIndex) { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1, closingTagIndex)); } else { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1)); } } return documentation.trim(); } } | DocumentationUtils { public static String stripHtmlTags(String documentation) { if (documentation == null) { return ""; } if (documentation.startsWith("<")) { int startTagIndex = documentation.indexOf(">"); int closingTagIndex = documentation.lastIndexOf("<"); if (closingTagIndex > startTagIndex) { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1, closingTagIndex)); } else { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1)); } } return documentation.trim(); } private DocumentationUtils(); } | DocumentationUtils { public static String stripHtmlTags(String documentation) { if (documentation == null) { return ""; } if (documentation.startsWith("<")) { int startTagIndex = documentation.indexOf(">"); int closingTagIndex = documentation.lastIndexOf("<"); if (closingTagIndex > startTagIndex) { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1, closingTagIndex)); } else { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1)); } } return documentation.trim(); } private DocumentationUtils(); static String stripHtmlTags(String documentation); static String escapeIllegalCharacters(String documentation); static String createLinkToServiceDocumentation(Metadata metadata, String name); static String createLinkToServiceDocumentation(Metadata metadata, ShapeModel shapeModel); static String removeFromEnd(String string, String stringToRemove); static String defaultSetter(); static String defaultSetterParam(); static String defaultGetter(); static String defaultGetterParam(); static String defaultFluentReturn(); static String defaultExistenceCheck(); } | DocumentationUtils { public static String stripHtmlTags(String documentation) { if (documentation == null) { return ""; } if (documentation.startsWith("<")) { int startTagIndex = documentation.indexOf(">"); int closingTagIndex = documentation.lastIndexOf("<"); if (closingTagIndex > startTagIndex) { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1, closingTagIndex)); } else { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1)); } } return documentation.trim(); } private DocumentationUtils(); static String stripHtmlTags(String documentation); static String escapeIllegalCharacters(String documentation); static String createLinkToServiceDocumentation(Metadata metadata, String name); static String createLinkToServiceDocumentation(Metadata metadata, ShapeModel shapeModel); static String removeFromEnd(String string, String stringToRemove); static String defaultSetter(); static String defaultSetterParam(); static String defaultGetter(); static String defaultGetterParam(); static String defaultFluentReturn(); static String defaultExistenceCheck(); } |
@Test public void empty_html_tags_at_start_are_removed() { Assert.assertThat(DocumentationUtils.stripHtmlTags("<p></p>"), Matchers .isEmptyString()); Assert.assertThat(DocumentationUtils.stripHtmlTags("<p/>"), Matchers .isEmptyString()); } | public static String stripHtmlTags(String documentation) { if (documentation == null) { return ""; } if (documentation.startsWith("<")) { int startTagIndex = documentation.indexOf(">"); int closingTagIndex = documentation.lastIndexOf("<"); if (closingTagIndex > startTagIndex) { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1, closingTagIndex)); } else { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1)); } } return documentation.trim(); } | DocumentationUtils { public static String stripHtmlTags(String documentation) { if (documentation == null) { return ""; } if (documentation.startsWith("<")) { int startTagIndex = documentation.indexOf(">"); int closingTagIndex = documentation.lastIndexOf("<"); if (closingTagIndex > startTagIndex) { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1, closingTagIndex)); } else { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1)); } } return documentation.trim(); } } | DocumentationUtils { public static String stripHtmlTags(String documentation) { if (documentation == null) { return ""; } if (documentation.startsWith("<")) { int startTagIndex = documentation.indexOf(">"); int closingTagIndex = documentation.lastIndexOf("<"); if (closingTagIndex > startTagIndex) { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1, closingTagIndex)); } else { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1)); } } return documentation.trim(); } private DocumentationUtils(); } | DocumentationUtils { public static String stripHtmlTags(String documentation) { if (documentation == null) { return ""; } if (documentation.startsWith("<")) { int startTagIndex = documentation.indexOf(">"); int closingTagIndex = documentation.lastIndexOf("<"); if (closingTagIndex > startTagIndex) { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1, closingTagIndex)); } else { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1)); } } return documentation.trim(); } private DocumentationUtils(); static String stripHtmlTags(String documentation); static String escapeIllegalCharacters(String documentation); static String createLinkToServiceDocumentation(Metadata metadata, String name); static String createLinkToServiceDocumentation(Metadata metadata, ShapeModel shapeModel); static String removeFromEnd(String string, String stringToRemove); static String defaultSetter(); static String defaultSetterParam(); static String defaultGetter(); static String defaultGetterParam(); static String defaultFluentReturn(); static String defaultExistenceCheck(); } | DocumentationUtils { public static String stripHtmlTags(String documentation) { if (documentation == null) { return ""; } if (documentation.startsWith("<")) { int startTagIndex = documentation.indexOf(">"); int closingTagIndex = documentation.lastIndexOf("<"); if (closingTagIndex > startTagIndex) { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1, closingTagIndex)); } else { documentation = stripHtmlTags(documentation.substring(startTagIndex + 1)); } } return documentation.trim(); } private DocumentationUtils(); static String stripHtmlTags(String documentation); static String escapeIllegalCharacters(String documentation); static String createLinkToServiceDocumentation(Metadata metadata, String name); static String createLinkToServiceDocumentation(Metadata metadata, ShapeModel shapeModel); static String removeFromEnd(String string, String stringToRemove); static String defaultSetter(); static String defaultSetterParam(); static String defaultGetter(); static String defaultGetterParam(); static String defaultFluentReturn(); static String defaultExistenceCheck(); } |
@Test public void testUnCapitalize() { capitalizedToUncapitalized.forEach((capitalized,unCapitalized) -> assertThat(Utils.unCapitalize(capitalized), is(equalTo(unCapitalized)))); } | public static String unCapitalize(String name) { if (name == null || name.trim().isEmpty()) { throw new IllegalArgumentException("Name cannot be null or empty"); } StringBuilder sb = new StringBuilder(name.length()); int i = 0; do { sb.append(Character.toLowerCase(name.charAt(i++))); } while ((i < name.length() && Character.isUpperCase(name.charAt(i))) && !(i < name.length() - 1 && Character.isLowerCase(name.charAt(i + 1)))); sb.append(name.substring(i)); return sb.toString(); } | Utils { public static String unCapitalize(String name) { if (name == null || name.trim().isEmpty()) { throw new IllegalArgumentException("Name cannot be null or empty"); } StringBuilder sb = new StringBuilder(name.length()); int i = 0; do { sb.append(Character.toLowerCase(name.charAt(i++))); } while ((i < name.length() && Character.isUpperCase(name.charAt(i))) && !(i < name.length() - 1 && Character.isLowerCase(name.charAt(i + 1)))); sb.append(name.substring(i)); return sb.toString(); } } | Utils { public static String unCapitalize(String name) { if (name == null || name.trim().isEmpty()) { throw new IllegalArgumentException("Name cannot be null or empty"); } StringBuilder sb = new StringBuilder(name.length()); int i = 0; do { sb.append(Character.toLowerCase(name.charAt(i++))); } while ((i < name.length() && Character.isUpperCase(name.charAt(i))) && !(i < name.length() - 1 && Character.isLowerCase(name.charAt(i + 1)))); sb.append(name.substring(i)); return sb.toString(); } private Utils(); } | Utils { public static String unCapitalize(String name) { if (name == null || name.trim().isEmpty()) { throw new IllegalArgumentException("Name cannot be null or empty"); } StringBuilder sb = new StringBuilder(name.length()); int i = 0; do { sb.append(Character.toLowerCase(name.charAt(i++))); } while ((i < name.length() && Character.isUpperCase(name.charAt(i))) && !(i < name.length() - 1 && Character.isLowerCase(name.charAt(i + 1)))); sb.append(name.substring(i)); return sb.toString(); } private Utils(); static boolean isScalar(Shape shape); static boolean isStructure(Shape shape); static boolean isListShape(Shape shape); static boolean isMapShape(Shape shape); static boolean isEnumShape(Shape shape); static boolean isExceptionShape(Shape shape); static boolean isOrContainsEnumShape(Shape shape, Map<String, Shape> allShapes); static boolean isOrContainsEnum(MemberModel member); static boolean isListWithEnumShape(MemberModel member); static boolean isMapWithEnumShape(MemberModel member); static boolean isMapKeyWithEnumShape(MapModel mapModel); static boolean isMapValueWithEnumShape(MapModel mapModel); static String unCapitalize(String name); static String capitalize(String name); static String removeLeading(String str, String toRemove); static String removeTrailing(String str, String toRemove); static String getFileNamePrefix(ServiceModel serviceModel); static String directoryToPackage(String directoryPath); static String packageToDirectory(String packageName); static String getDefaultEndpointWithoutHttpProtocol(String endpoint); static File createDirectory(String path); static void createDirectory(File dir); static File createFile(String dir, String fileName); static boolean isNullOrEmpty(String str); static void closeQuietly(Closeable closeable); static InputStream getRequiredResourceAsStream(Class<?> clzz, String location); static ShapeModel findShapeModelByC2jName(IntermediateModel intermediateModel, String shapeC2jName); static ShapeModel findShapeModelByC2jNameIfExists(IntermediateModel intermediateModel, String shapeC2jName); static ShapeModel findMemberShapeModelByC2jNameIfExists(IntermediateModel intermediateModel, String shapeC2jName); static List<ShapeModel> findShapesByC2jName(IntermediateModel intermediateModel, String shapeC2jName); static ShapeMarshaller createInputShapeMarshaller(ServiceMetadata service, Operation operation); } | Utils { public static String unCapitalize(String name) { if (name == null || name.trim().isEmpty()) { throw new IllegalArgumentException("Name cannot be null or empty"); } StringBuilder sb = new StringBuilder(name.length()); int i = 0; do { sb.append(Character.toLowerCase(name.charAt(i++))); } while ((i < name.length() && Character.isUpperCase(name.charAt(i))) && !(i < name.length() - 1 && Character.isLowerCase(name.charAt(i + 1)))); sb.append(name.substring(i)); return sb.toString(); } private Utils(); static boolean isScalar(Shape shape); static boolean isStructure(Shape shape); static boolean isListShape(Shape shape); static boolean isMapShape(Shape shape); static boolean isEnumShape(Shape shape); static boolean isExceptionShape(Shape shape); static boolean isOrContainsEnumShape(Shape shape, Map<String, Shape> allShapes); static boolean isOrContainsEnum(MemberModel member); static boolean isListWithEnumShape(MemberModel member); static boolean isMapWithEnumShape(MemberModel member); static boolean isMapKeyWithEnumShape(MapModel mapModel); static boolean isMapValueWithEnumShape(MapModel mapModel); static String unCapitalize(String name); static String capitalize(String name); static String removeLeading(String str, String toRemove); static String removeTrailing(String str, String toRemove); static String getFileNamePrefix(ServiceModel serviceModel); static String directoryToPackage(String directoryPath); static String packageToDirectory(String packageName); static String getDefaultEndpointWithoutHttpProtocol(String endpoint); static File createDirectory(String path); static void createDirectory(File dir); static File createFile(String dir, String fileName); static boolean isNullOrEmpty(String str); static void closeQuietly(Closeable closeable); static InputStream getRequiredResourceAsStream(Class<?> clzz, String location); static ShapeModel findShapeModelByC2jName(IntermediateModel intermediateModel, String shapeC2jName); static ShapeModel findShapeModelByC2jNameIfExists(IntermediateModel intermediateModel, String shapeC2jName); static ShapeModel findMemberShapeModelByC2jNameIfExists(IntermediateModel intermediateModel, String shapeC2jName); static List<ShapeModel> findShapesByC2jName(IntermediateModel intermediateModel, String shapeC2jName); static ShapeMarshaller createInputShapeMarshaller(ServiceMetadata service, Operation operation); } |
@Test public void unusedImportsAreRemoved() throws Exception { String content = loadFileContents(FILE_WITH_UNUSED_IMPORTS_JAVA); String expected = loadFileContents(FILE_WITHOUT_UNUSED_IMPORTS_JAVA); String result = sut.apply(content); assertThat(result, equalToIgnoringWhiteSpace(expected)); } | @Override public String apply(String content) { return findUnusedImports(content).stream().map(this::removeImportFunction).reduce(Function.identity(), Function::andThen).apply(content); } | UnusedImportRemover implements CodeTransformer { @Override public String apply(String content) { return findUnusedImports(content).stream().map(this::removeImportFunction).reduce(Function.identity(), Function::andThen).apply(content); } } | UnusedImportRemover implements CodeTransformer { @Override public String apply(String content) { return findUnusedImports(content).stream().map(this::removeImportFunction).reduce(Function.identity(), Function::andThen).apply(content); } } | UnusedImportRemover implements CodeTransformer { @Override public String apply(String content) { return findUnusedImports(content).stream().map(this::removeImportFunction).reduce(Function.identity(), Function::andThen).apply(content); } @Override String apply(String content); } | UnusedImportRemover implements CodeTransformer { @Override public String apply(String content) { return findUnusedImports(content).stream().map(this::removeImportFunction).reduce(Function.identity(), Function::andThen).apply(content); } @Override String apply(String content); } |
@Test public void nonJavaContentIsIgnored() throws Exception { String jsonContent = "{ \"SomeKey\": 4, \"ADict\": { \"SubKey\": \"Subvalue\" } }"; String result = sut.apply(jsonContent); assertThat(result, equalTo(jsonContent)); } | @Override public String apply(String content) { return findUnusedImports(content).stream().map(this::removeImportFunction).reduce(Function.identity(), Function::andThen).apply(content); } | UnusedImportRemover implements CodeTransformer { @Override public String apply(String content) { return findUnusedImports(content).stream().map(this::removeImportFunction).reduce(Function.identity(), Function::andThen).apply(content); } } | UnusedImportRemover implements CodeTransformer { @Override public String apply(String content) { return findUnusedImports(content).stream().map(this::removeImportFunction).reduce(Function.identity(), Function::andThen).apply(content); } } | UnusedImportRemover implements CodeTransformer { @Override public String apply(String content) { return findUnusedImports(content).stream().map(this::removeImportFunction).reduce(Function.identity(), Function::andThen).apply(content); } @Override String apply(String content); } | UnusedImportRemover implements CodeTransformer { @Override public String apply(String content) { return findUnusedImports(content).stream().map(this::removeImportFunction).reduce(Function.identity(), Function::andThen).apply(content); } @Override String apply(String content); } |
@Test public void responseMetadataGeneration() { ResponseMetadataSpec spec = new ResponseMetadataSpec(model); assertThat(spec, generatesTo(spec.className().simpleName().toLowerCase() + ".java")); AwsServiceBaseResponseSpec responseSpec = new AwsServiceBaseResponseSpec(model); assertThat(responseSpec, generatesTo(responseSpec.className().simpleName().toLowerCase() + ".java")); } | @Override public ClassName className() { return poetExtensions.getResponseMetadataClass(); } | ResponseMetadataSpec implements ClassSpec { @Override public ClassName className() { return poetExtensions.getResponseMetadataClass(); } } | ResponseMetadataSpec implements ClassSpec { @Override public ClassName className() { return poetExtensions.getResponseMetadataClass(); } ResponseMetadataSpec(IntermediateModel model); } | ResponseMetadataSpec implements ClassSpec { @Override public ClassName className() { return poetExtensions.getResponseMetadataClass(); } ResponseMetadataSpec(IntermediateModel model); @Override TypeSpec poetSpec(); @Override ClassName className(); } | ResponseMetadataSpec implements ClassSpec { @Override public ClassName className() { return poetExtensions.getResponseMetadataClass(); } ResponseMetadataSpec(IntermediateModel model); @Override TypeSpec poetSpec(); @Override ClassName className(); } |
@Test public void customResponseMetadataGeneration() { ResponseMetadataSpec spec = new ResponseMetadataSpec(modelWithCustomizedResponseMetadata); assertThat(spec, generatesTo("./customresponsemetadata/" + spec.className().simpleName().toLowerCase() + ".java")); AwsServiceBaseResponseSpec responseSpec = new AwsServiceBaseResponseSpec(modelWithCustomizedResponseMetadata); assertThat(responseSpec, generatesTo("./customresponsemetadata/" + responseSpec.className().simpleName().toLowerCase() + ".java")); } | @Override public ClassName className() { return poetExtensions.getResponseMetadataClass(); } | ResponseMetadataSpec implements ClassSpec { @Override public ClassName className() { return poetExtensions.getResponseMetadataClass(); } } | ResponseMetadataSpec implements ClassSpec { @Override public ClassName className() { return poetExtensions.getResponseMetadataClass(); } ResponseMetadataSpec(IntermediateModel model); } | ResponseMetadataSpec implements ClassSpec { @Override public ClassName className() { return poetExtensions.getResponseMetadataClass(); } ResponseMetadataSpec(IntermediateModel model); @Override TypeSpec poetSpec(); @Override ClassName className(); } | ResponseMetadataSpec implements ClassSpec { @Override public ClassName className() { return poetExtensions.getResponseMetadataClass(); } ResponseMetadataSpec(IntermediateModel model); @Override TypeSpec poetSpec(); @Override ClassName className(); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.